Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Define Pins
- #define LEDPIN 13
- #define BUTTONPIN 12
- #define ANARANDPIN A0
- // Define Random intervals
- #define RND_MIN 100 // In ms
- #define RND_MAX 500 // In ms
- int state = 0; // store current state machine state
- int ledState = LOW; // ledState used to set the LED
- long startStateMillis = 0; // time we entered blinking state
- long currentMillis = 0; // current time
- long nextLedEvent = 0; // time of next led event
- void setup() {
- pinMode(LEDPIN, OUTPUT);
- pinMode(BUTTONPIN, INPUT);
- pinMode(ANARANDPIN, INPUT);
- randomSeed(analogRead(ANARANDPIN));
- Serial.begin(9600);
- }
- void loop()
- {
- // get current time
- currentMillis = millis();
- if(state == 0)
- {
- // wait for button press
- if(digitalRead(BUTTONPIN) == LOW)
- {
- // go to next state (no need to debounce)
- state = 1;
- }
- }
- else if(state == 1)
- {
- // delay 5 sec.
- if(startStateMillis == 0)
- {
- // get current time
- startStateMillis = millis();
- }
- // be in this state for 5000 ms
- if(currentMillis >= startStateMillis + 5000)
- {
- startStateMillis = 0;
- state = 2;
- }
- // do nothing
- }
- else if(state == 2)
- {
- // random flash 5 seconds
- if(startStateMillis == 0)
- {
- // get current time
- startStateMillis = millis();
- // turn led on (save state)
- ledState = HIGH;
- digitalWrite(LEDPIN, ledState);
- // calculate next led transition
- nextLedEvent = currentMillis + random(RND_MIN, RND_MAX);
- }
- // be in this state for 5000 ms
- if(currentMillis >= startStateMillis + 5000)
- {
- // end 5 seconds of random blinking
- state = 0; // go back to base state
- startStateMillis = 0;
- nextLedEvent = 0;
- // turn led off (save state)
- ledState = LOW;
- digitalWrite(LEDPIN, ledState);
- }
- // process led events
- // check for current state to handle exit transition
- if(currentMillis >= nextLedEvent && state==2)
- {
- // change led state (save state)
- if (ledState == LOW)
- ledState = HIGH;
- else
- ledState = LOW;
- digitalWrite(LEDPIN, ledState);
- nextLedEvent = currentMillis + random(RND_MIN, RND_MAX);
- }
- }
- else // should never get here
- {
- // reset state
- state = 0;
- }
- Serial.println(state);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement