//Arduino + Relay Module + Limit Switches + 1 Hour Delay by Nudge Me (29 Nov 2018)
//This code can be tested on UnoArduSim.exe Simulator (https://www.sites.google.com/site/unoardusim/services/UnoArduSimV2.2.zip?attredirects=0&d=1)
//int delayTime = 60UL * 60UL * 1000UL; //1 hour delay
//int delayTime = 500; //1 seconds delay (for testing only)
int RelayPin1 = A2; //connect relay module's pin 1 to pin 11 of Arduino
int RelayPin2 = A3; //connect relay module's pin 2 to pin 12 of Arduino
int state = 0;
int Switch1 = A0; //connect limit switch 1 to pin 2 of Arduino
int Switch2 = A1; //connect limit switch 2 to pin 3 of Arduino
int input1, input2;
void setup() {
pinMode(RelayPin1, OUTPUT);
pinMode(RelayPin2, OUTPUT);
pinMode(Switch1, INPUT);
pinMode(Switch2, INPUT);
}
void loop() {
if (state == 0)
{
forward(); //motor turns forward
input1 = digitalRead(Switch1); //during turning forward, only limit switch 1 is observed
if (input1 == HIGH) //when the limit switch 1 is pushed (active low), the motor will stop for 1 hour and turn reverse after that
{
stopmotor();
delay(2000);
analogWrite(RelayPin1, LOW);
delay(2000);
analogWrite(RelayPin1, HIGH);
state = 0;
}
}
else if (state == 1)
{
reverse(); //motor turns reverse
input2 = digitalRead(Switch2); //during turning reverse, only limit switch 2 is observed
if (input2 == HIGH) //when the limit switch 2 is pushed (active low), the motor will stop for 1 hour and turn forward after that
{
stopmotor();
delay(2000);
analogWrite(RelayPin2, LOW);
delay(2000);
analogWrite(RelayPin2, HIGH);
state = 1;
}
}
}
void forward() {
digitalWrite(RelayPin1, LOW); //normally, giving LOW to relay will make it turn off
digitalWrite(RelayPin2, HIGH); //and giving HIGH will make it turn on (active low)
}
void reverse() {
digitalWrite(RelayPin2, LOW);
digitalWrite(RelayPin1, HIGH);
}
void stopmotor() {
digitalWrite(RelayPin1, HIGH); //so giving HIGH to both relays will make the relays turn off, and stop the motor
digitalWrite(RelayPin2, HIGH);}