The below code uses digitalread() to check the state of a button and turn an LED on pin 13 on when pressed and off when not pressed.
int state = 0;
void setup(){
pinMode(13,OUTPUT);
pinMode(2,INPUT);
}
void loop(){
state = digitalRead(2); //Writes either HIGH or LOW to the state variable
if (state == HIGH){
digitalWrite(13,HIGH);
}
else{
digitalWrite(13,0);
}
}
Schematic:
To cause the program to do the opposite (have the LED on and turn off when the button is pressed) simply alter the if statement. Two alternatives are:
if (state != HIGH) or if (state == LOW)
Too add serial output referring to the LED and button state this is the new code:
int state = 0;
boolean change = HIGH;
void setup(){
pinMode(13,OUTPUT);
pinMode(2,INPUT);
Serial.begin(9600);
}
void loop(){
state = digitalRead(2);
if (state != HIGH){
digitalWrite(13,1);
if (change == HIGH){
Serial.println("LED On, Button Not Pressed");
change = !change;
}
}
else{
digitalWrite(13,0);
if (change == LOW){
Serial.println("LED Off, Button Pressed");
change = !change;
}
}
}
Wednesday, March 17, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment