Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- This is a combination of the examples
- - "Button" and
- - "Blink without Delay"
- Function of the sketch:
- Turns a light emitting diode(LED) connected to digital pin 13,
- ON for a time interval (here 60 seconds),
- when pressing a pushbutton attached to pin 2 (or pulling pin 2 HIGH).
- The time is from 60 seconds from the release of the button,
- and the time will be extended if the button is pressed
- before the 60 seconds is up.
- Because we combine with the method from "Blink without Delay"
- other code can run at the same time without
- being interrupted/stopped by the timeout code needed to
- turn the LED on and off.
- The circuit:
- - LED attached from pin 13 to ground
- - pushbutton attached to pin 2 from +5V
- - 10K resistor attached to pin 2 from ground
- - Note: on most Arduinos there is already an LED on the board
- attached to pin 13.
- - Note 2: The pushbutton is connected to be active on a HIGH of pin 2.
- */
- //// Button/input constants and variables
- // constants won't change. They're used here to set pin numbers:
- const int buttonPin = 2; // the number of the pushbutton pin
- const int ledPin = 13; // the number of the LED pin
- // variables will change:
- int buttonState = 0; // variable for reading the pushbutton status
- //// Timeout constants and variables
- // constants won't change.
- const long interval = 60000; // interval (in milliseconds) to keep the LED ON for (60 seconds)
- // variables will change:
- unsigned long previousMillis = 0; // will store last time the LED was turned ON
- void setup() {
- // initialize the LED pin as an output:
- pinMode(ledPin, OUTPUT);
- // initialize the pushbutton pin as an input:
- pinMode(buttonPin, INPUT);
- }
- void loop() {
- // check to see if it's time to blink the LED (or to turn the LED on or off) ;
- // that is, if the difference between the current time
- // and last time you blinked the LED (or turned the LED on) is bigger than
- // the interval at which you want to blink the LED (turn the LED off).
- unsigned long currentMillis = millis();
- // read the state of the pushbutton value:
- buttonState = digitalRead(buttonPin);
- // check if the pushbutton is pressed (or the pin is HIGH).
- // If it is, the buttonState is HIGH:
- if (buttonState == HIGH) {
- // turn LED on:
- digitalWrite(ledPin, HIGH);
- // save the start of the press/activation time
- previousMillis = currentMillis;
- }
- // check to see if there is a timeout condition
- if (currentMillis - previousMillis >= interval) {
- // turn LED off:
- digitalWrite(ledPin, LOW);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment