This is my the first code i have written and i have no idea why it doesnt work... It just says "error: 'buttonState' was not declared in this scope." can someone please help me to get started?
int ledpin1 = 11;
int ledpin2 = 12;
int buttonpin = 10;
void setup() {
pinMode(ledpin1, OUTPUT);
pinMode(ledpin2, OUTPUT);
pinMode(buttonpin, INPUT);
}
void loop() {
buttonState = digitalRead(buttonpin);
if (buttonState == HIGH) {
digitalWrite(ledpin1, HIGH);
digitalWrite(ledpin2, LOW);
}
else {
digitalWrite(ledpin1, LOW);
digitalWrite(ledpin2, HIGH);
}
}
You never said what type of a value buttonState is, which the compiler tells you about.
"not declared" means, you never said what it is in a location that I'm allowed to access.
So if you'd declare buttonState together with the ledpin's, he'll stop whining, if you'd put it in another function, he isn't allowed to look there for your 'declaration', so he'd still whine.
In short: you need to put buttonState up with the ledpin stuff, or assign its type in the loop function.
In your case, I'd just put 'byte' in front of "buttonState = digitalRead(buttonpin);", turning it into "byte buttonState = digitalRead(buttonpin);"
Just for fun. Here is this program using Hardware Abstraction Libraries:
//http://www.arduino.cc/playground/Profiles/AlphaBeta
#include <Button.h>
#include <LED.h>
Button button = Button(10,PULLDOWN);
LED led1 = LED(11);
LED led2 = LED(12);
void setup() {/*nothing to setup*/}
void loop(){
if (button.isPressed()) {
led1.on();
led2.off();
} else {
led1.off();
led2.on();
}
}