Friday, September 5, 2014

Working with Inputs (Introduction)


Image used under CC0 licence


Copy and paste the code that follows the line of asterisks:

*************************************************

// Define some variables for later use ...
//    - "const int" is used for values that won't chance in our sketch
//    - we're going to make a constant integer called "ledPin" and assign it to the pin the LED is connected to

const int ledPin = 8; // substitute whatever pin you're using for 8

//    - now make a constant integer called "buttonPin" and assign it to the pin the button (or switch) will be connected to

const int buttonPin = 5; // susbtitute whatever pin you're using for 5

//    - "int" is used for values that will change in our sketch
//    - we're going to make a integer variable called "buttonState" that we'll use to measure the button's state

int buttonState;

// Intialize the pins in the setup:

void setup()
{
  pinMode(ledPin,OUTPUT); 
  pinMode(buttonPin,INPUT_PULLUP);
}

// Put the code to be run over and over in the loop:

void loop()
{
  buttonState = digitalRead(buttonPin); // we're "reading" the voltage on in the input pin and assigning it to our variable called buttonState
  // Since we did a digital read, there are only two possible values now for buttonState -- it's either HIGH or LOW
  
  if(buttonState == HIGH)
  {
    digitalWrite(ledPin,HIGH);
  }

  else
  {
    digitalWrite(ledPin,LOW);
  }


}

1 comment: