Pages: [1]   Go Down
Author Topic: Trying to turn off an output 1second after a switch is tripped  (Read 484 times)
0 Members and 1 Guest are viewing this topic.
Seattle, WA
Offline Offline
Newbie
*
Karma: 0
Posts: 45
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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;
     }
  
}
« Last Edit: December 19, 2012, 08:36:26 pm by cosmos275 » Logged

Seattle, WA
Offline Offline
Newbie
*
Karma: 0
Posts: 45
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Wait, sorry, I found it

if(latch = true)

should be

if(latch == true)

now it's working
Logged

Temple, Texas
Offline Offline
Sr. Member
****
Karma: 14
Posts: 361
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Or,

  if (latch) {
  ...
  }
Logged

Seattle, WA
Offline Offline
Newbie
*
Karma: 0
Posts: 45
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

very nice!  Thanks
Logged

Seattle, WA USA
Online Online
Brattain Member
*****
Karma: 643
Posts: 50440
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
very nice!
So would you using Tools  + Auto format before posting code.

Code that runs
           all over the
    page
                                           like yours
                does
is pretty
                hard to read.
Logged

Pages: [1]   Go Up
Jump to: