baldengineer

Arduino Police Strobe (w/ millis())

Jul 28th, 2012
1,626
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*******************************
  2. * Arduino Police Lights Strobe Example
  3. * James C4S / www.cmiyc.com
  4. *
  5. * How to make lights strobe like police lights using millis() (no delay)
  6. *
  7. * http://www.cmiyc.com/tutorials/arduino-example-police-lights-with-millis
  8. *******************************/
  9.  
  10. // English for which LED to Strobe
  11. #define RED 0x0
  12. #define BLUE 0x1
  13.  
  14. // Variable to track which LED is on
  15. byte whichLED = RED;
  16.  
  17. // Where are the LEDs connected?
  18. const int LED_Red = 7;
  19. const int LED_Blue = 11;
  20.  
  21. // State variables for the LEDs
  22. byte Red_State = LOW;    
  23. byte Blue_State = LOW;    
  24.  
  25. // Some delay values to change flashing behavior
  26. unsigned long switchDelay = 250;
  27. unsigned long strobeDelay = 50;
  28.  
  29. // Seed the initial wait for the strobe effect
  30. unsigned long strobeWait = strobeDelay;
  31.  
  32. // Variable to see when we should swtich LEDs
  33. unsigned long waitUntilSwitch = switchDelay;  // seed initial wait
  34.  
  35.  
  36. void setup() {
  37.    pinMode(LED_Red, OUTPUT);
  38.    pinMode(LED_Blue, OUTPUT);
  39. }
  40.  
  41. void loop() {
  42.     digitalWrite(LED_Red, Red_State);     // each iteration of loop() will set the IO pins,
  43.     digitalWrite(LED_Blue, Blue_State);    // even if they don't change, that's okay
  44.  
  45.     // Toggle back and forth between the two LEDs
  46.     if ((long)(millis() - waitUntilSwitch)>=0) {
  47.         // time is up!
  48.         Red_State = LOW;
  49.         Blue_State = LOW;
  50.         whichLED = !whichLED;  // toggle LED to strobe
  51.         waitUntilSwitch += switchDelay;
  52.     }
  53.    
  54.     // Create the stobing effect
  55.     if ((long)(millis() - strobeWait)>=0) {
  56.         if (whichLED == RED)
  57.             Red_State = !Red_State;
  58.         if (whichLED == BLUE)
  59.             Blue_State = !Blue_State;
  60.         strobeWait += strobeDelay;
  61.     }  
  62. }
RAW Paste Data