Hi all. So, I have a crude clock going. I'd like to turn on a motor at the top of the hour and let it run until it runs over a switch. When it hits the switch, I want it to wait ~1sec before turning it off. Right now it's not working.
What's happening is after an hour (5 seconds for now) elapses, the motor (LED for now) turns on then turns off after one second even though I haven't hit the switch.
Here's what I got. serial readouts are commented. Any ideas where it's going wrong?
unsigned long time_old;
unsigned long time_new;
const int LedPin = 13;
int hours = 0;
boolean timeout = false;
const int SWpin = 2;
boolean latch = false;
void setup()
{
pinMode(SWpin, INPUT_PULLUP);
digitalWrite(SWpin, HIGH);
time_old = millis();
pinMode(LedPin, OUTPUT);
Serial.begin(9600);
}
void loop(){
int swState = digitalRead(SWpin);
time_new = millis();
if(time_new - time_old >= (5UL * 1000)) // 1 hour has elapsed. shortened for debug (60UL*60*1000)
{
hours++;
time_old = time_new;
Serial.println(hours); //printing out 1, 2, 3, .. 24 then repeating (working)
Serial.println(swState); //printing out 1, 1, 1 ....
Serial.println(latch); //printing out 0, 0, 0...
digitalWrite(LedPin, HIGH); //turn on output
}
if(swState == 0) //switch has been hit (pullup)
{
delay(50); //debounce
latch = true;
}
if(latch = true)
{
delay(1000);
digitalWrite(LedPin, LOW);
latch = false;
}
if(hours == 4)
{
//do something later
}
if(hours>= 24)
{
time_old = time_new;
hours = 0;
}
}