Dipsikha Halder
Created September 30, 2015

Homework 4: Avoiding Arduino delay(), Stepper Motors, Solder

BeginnerShowcase (no instructions)581
Homework 4: Avoiding Arduino delay(), Stepper Motors, Solder

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1

Hand tools and fabrication machines

Soldering iron (generic)
Soldering iron (generic)

Story

Read more

Code

The finished code

C/C++
Our challenge was to fuse the Blink without delay and switch debouncing without delay Arduino sketches to make the circuit work without using any calls to delay()
// Only change LED state on button transition, add switch debouncing
// Massimo Banzi, from "Getting Started with Arduino"

const int LED = 13;    // the pin for the LED
const int BUTTON = 7;  // input pin for switch
int val = 0;     // val  used to store state of input pin
int old = 0; // used to store the previous value of "val"
int state = 0;   // 1 = LED on 0 = LED off 

const long short_interval = 300; 
const long long_interval = 1000; 

int ledState = LOW;
unsigned long previousMillis = 0;

//define input and output
void setup() {
  pinMode(LED, OUTPUT);   
  pinMode(BUTTON, INPUT); 
}

void loop(){
  val = digitalRead(BUTTON); // read and store input value
  unsigned long currentMillis = millis();

  // check for a transition between the current value and the previous value
  if ((val == HIGH) && (old == LOW)){
    state = 1 - state; // change the state
    delay(10);        // wait for switch to stop bouncing
  }

  old = val; // update the value

  if (state == 1) {
    
    if (currentMillis - previousMillis >= short_interval) {
    // save the last time you blinked the LED
      previousMillis = currentMillis;
      // if the LED is off turn it on and vice-versa:
      if (ledState == LOW) {
        ledState = HIGH;
      } else {
        ledState = LOW;
      }
      // set the LED with the ledState of the variable:
      digitalWrite(LED, ledState);
    }
      
    } else {
       if (currentMillis - previousMillis >= long_interval) {
      // save the last time you blinked the LED
      previousMillis = currentMillis;
  
      // if the LED is off turn it on and vice-versa:
      if (ledState == LOW) {
        ledState = HIGH;
      } else {
        ledState = LOW;
      }
  
      // set the LED with the ledState of the variable:
      digitalWrite(LED, ledState);
    }
  }
}

Credits

Dipsikha Halder

Dipsikha Halder

9 projects • 1 follower

Comments