Go Down

Topic: Trying to turn off an output 1second after a switch is tripped (Read 756 times) previous topic - next topic


Dec 20, 2012, 02:25 am Last Edit: Dec 20, 2012, 02:36 am by cosmos275 Reason: 1
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?

Code: [Select]

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);

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)
    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)
digitalWrite(LedPin, LOW);
latch = false;

    if(hours == 4)
      //do something later
    if(hours>= 24)
      time_old = time_new;
      hours = 0;


Wait, sorry, I found it

if(latch = true)

should be

if(latch == true)

now it's working


very nice!

So would you using Tools  + Auto format before posting code.

Code that runs
           all over the
                                           like yours
is pretty
                hard to read.
The art of getting good answers lies in asking good questions.

Go Up