Advertisement
baldengineer

broken millis logic

Jun 9th, 2015
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. unsigned int buzzer = 6;
  2. int relayPin = 5;
  3. unsigned long int runTime;
  4. unsigned long int restTime;
  5. unsigned int val = 0;
  6. unsigned long previousMillisRun = 0;
  7. unsigned long previousMillisRest = 0;
  8. boolean pwrOn = true;
  9. unsigned long myMillis;
  10.  
  11. void setup() {
  12.   pinMode(relayPin, OUTPUT);
  13.   digitalWrite(relayPin, HIGH);
  14. }
  15.  
  16. void loop() {
  17.       runTime = 1000;
  18.       restTime = 1000;
  19.       // you forgot this.
  20.       unsigned long myMillis = millis();
  21.  
  22.       // this code runs when millis reaches 1000 (or more)
  23.       // because previousMillisRun is set to 0, and runTime is 1000.
  24.       if (myMillis - previousMillisRun >= runTime && pwrOn == true)
  25.       {
  26.         // you store 1000
  27.         previousMillisRun = myMillis;
  28.         // turn the relay off
  29.         digitalWrite(relayPin, LOW);
  30.         // now you set your state variable to the opposite.
  31.         pwrOn = false;
  32.       }
  33.  
  34.       // guess what, this code executes IMMEDIATELY after the previous if-statement, BECAUSE
  35.       // pwrOn is now false. AND previousMillisRest is STILL 0!
  36.       if (myMillis - previousMillisRest >= restTime && pwrOn == false)
  37.       {
  38.         // so you store the same 1000 value
  39.         previousMillisRest = myMillis;
  40.         // turn the relay back on
  41.         digitalWrite(relayPin, HIGH);
  42.         // and re-enable the first if-statement.
  43.         pwrOn = true;
  44.       }
  45. // one second later, it happens again.
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement