Advertisement
Guest User

Random Blink no delay

a guest
Oct 30th, 2014
999
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. // Define Pins
  2. #define LEDPIN 13
  3. #define BUTTONPIN 12
  4. #define ANARANDPIN A0
  5.  
  6. // Define Random intervals
  7. #define RND_MIN 100 // In ms
  8. #define RND_MAX 500 // In ms
  9.  
  10. int state = 0; // store current state machine state
  11. int ledState = LOW; // ledState used to set the LED
  12.  
  13. long startStateMillis = 0; // time we entered blinking state
  14. long currentMillis = 0; // current time
  15. long nextLedEvent = 0; // time of next led event
  16.  
  17.  
  18. void setup() {
  19. pinMode(LEDPIN, OUTPUT);
  20. pinMode(BUTTONPIN, INPUT);
  21. pinMode(ANARANDPIN, INPUT);
  22. randomSeed(analogRead(ANARANDPIN));
  23. Serial.begin(9600);
  24. }
  25.  
  26. void loop()
  27. {
  28. // get current time
  29. currentMillis = millis();
  30.  
  31. if(state == 0)
  32. {
  33. // wait for button press
  34. if(digitalRead(BUTTONPIN) == LOW)
  35. {
  36. // go to next state (no need to debounce)
  37. state = 1;
  38. }
  39. }
  40. else if(state == 1)
  41. {
  42. // delay 5 sec.
  43. if(startStateMillis == 0)
  44. {
  45. // get current time
  46. startStateMillis = millis();
  47. }
  48.  
  49. // be in this state for 5000 ms
  50. if(currentMillis >= startStateMillis + 5000)
  51. {
  52. startStateMillis = 0;
  53. state = 2;
  54. }
  55.  
  56. // do nothing
  57. }
  58. else if(state == 2)
  59. {
  60. // random flash 5 seconds
  61. if(startStateMillis == 0)
  62. {
  63. // get current time
  64. startStateMillis = millis();
  65. // turn led on (save state)
  66. ledState = HIGH;
  67. digitalWrite(LEDPIN, ledState);
  68. // calculate next led transition
  69. nextLedEvent = currentMillis + random(RND_MIN, RND_MAX);
  70. }
  71.  
  72. // be in this state for 5000 ms
  73. if(currentMillis >= startStateMillis + 5000)
  74. {
  75. // end 5 seconds of random blinking
  76. state = 0; // go back to base state
  77. startStateMillis = 0;
  78. nextLedEvent = 0;
  79. // turn led off (save state)
  80. ledState = LOW;
  81. digitalWrite(LEDPIN, ledState);
  82. }
  83.  
  84. // process led events
  85. // check for current state to handle exit transition
  86. if(currentMillis >= nextLedEvent && state==2)
  87. {
  88. // change led state (save state)
  89. if (ledState == LOW)
  90. ledState = HIGH;
  91. else
  92. ledState = LOW;
  93. digitalWrite(LEDPIN, ledState);
  94. nextLedEvent = currentMillis + random(RND_MIN, RND_MAX);
  95. }
  96. }
  97. else // should never get here
  98. {
  99. // reset state
  100. state = 0;
  101. }
  102. Serial.println(state);
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement