Hackster is hosting Hackster Holidays, Ep. 6: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Monday!Stream Hackster Holidays, Ep. 6 on Monday!
Matthew Chiang
Created November 30, 2015

Homework 04 Blink Without Delay and Soldering

Solder 4 short pieces of wire together and modify Exercise 1 to work without delay()

Showcase (no instructions)12
Homework 04 Blink Without Delay and Soldering

Story

Read more

Schematics

blink-without-delay.fzz

Code

Blink Without Delay

Java
Uses millis() to prevent the delay
/*
 * Blink without Delay
 */

// Constants
const int buttonPin = 7;    // input # for the switch on Arduino
const int ledPin = 13;      // input # for the LED pin

// Variables
int ledState = HIGH;         // current state of LED
int buttonState;             // current state based on the reading from the switch
int lastButtonState = LOW;   // the previous reading from the switch

long lastDebounceTime = 0;  // most recent time the LED was toggled. Long because units are in millisec, which will exceed 'int' quickly.
long debounceDelay = 50;    // the debounce time; increase if the output flickers
unsigned long previousMillis = 0; 
int interval = 400;


void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set the initial LED state
  digitalWrite(ledPin, ledState);
}

void loop() {
  // store the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);

  // check to see if you just toggled the switch (i.e. the input went from LOW to HIGH)
  // must have waited long enough since previous toggle to ignore noise

  // if the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    lastDebounceTime = millis(); // reset debouncing timer
  }

  // if the switch is toggled and you've waited longer than the debounce delay
  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) { // button state has changed
      buttonState = reading; // make the new button state whatever the reading is
      if (buttonState == HIGH) { // change the interval if the LED if the button state is HIGH
        interval = 1500 - interval;
      }
    }
  }

  unsigned long currentMillis = millis(); // store the current time
  
  if (currentMillis - previousMillis >= interval) { // store the time you most recently blinked the LED
    previousMillis = currentMillis; // update previous time to be the current time
    ledState = !ledState;  // toggle the LED's state
  }

  digitalWrite(ledPin, ledState); // set the LED state with the new state

  lastButtonState = reading; // store the reading as the last button state for the next loop iteration
}

Credits

Matthew Chiang

Matthew Chiang

16 projects • 9 followers

Comments