Thursday, October 4, 2012

Arduino Toggling Fun!

Photo used through Creative Commons License by Snootlab.

Students in Honors Physics II will appreciate the helpful code shown below--it allows a single push-button switch to toggle an LED on and off (just copy and paste it into the Arduino IDE). Even if you're not a programmer, can you figure out the main idea of each line of code?


/*
Brian Bearss
10/1/2012

Button Experiment!


*/


int ledPin = 12; // connect a LED (and a current-limiting resistor) to pin 12

int inputPin = 7; // a push-button switch is connected here
int newState = 0; // a variable to keep track of the current position of the button
int oldState = 0; // a variable to keep track of the position of the button the last time through the loop
int ledState = 0; // a variable to keep track of the state of the LED (on or off)


void setup()

{
  pinMode(ledPin,OUTPUT);
  pinMode(inputPin,INPUT);
  //Serial.begin(9600);
}

void loop()

{
  newState = digitalRead(inputPin); // will be HIGH when button is depressed, LOW otherwise
  if(newState==HIGH)
  {
    if(oldState==LOW) // this means the button has "just" been pressed
    {
      if(ledState==LOW) // this applies when the LED was previously off
      {
        digitalWrite(ledPin,HIGH); //turn the LED on
        ledState=HIGH; // record that the LED is now on
      }
      else // this applies when the LED wsa previously on
      {
        digitalWrite(ledPin,LOW); // turn the LED off
        ledState=LOW; // record that the LED is now off
      }
    }
  }
    oldState=newState; // update the state of the button so we can tell when it has been pressed
    //Serial.println(newState);
    delay(10); // wait 10 ms to allow the pysical button to stabilize before repeating the loop
    
}

1 comment:

  1. Looks like some coding fun; makes sense to me.

    ReplyDelete