As I am really new to embedded development and arduino I tried to start with the samples and do slight changes but I am having difficulties with a simple one.
I tried to change the button sample and make it works as follows: the led starts on and everytime I press the button it switchs its mode. Problem is it is having a completely unpredictable behaviour. I guess I did something really wrong.
I'll paste the code here hoping anyone can point me out what I am doing wrong:
int ledPin = 13; // choose the pin for the LED
int inputPin = 2; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
int button = HIGH;
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare pushbutton as input
}
void loop(){
val = digitalRead(inputPin);
if (HIGH == val) {
if (button == HIGH)
button = LOW;
else
button = HIGH;
digitalWrite(ledPin, button); // turn LED
val = digitalRead(inputPin);
while (HIGH == val) {val = digitalRead(inputPin);}
}
}
If you're looking to just modify the sample code from the website ilke it seems you're trying to do I'd suggest something like this-
int ledPin = 13; // choose the pin for the LED
int inPin = 2; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inPin, INPUT); // declare pushbutton as input
}
void loop(){
val = digitalRead(inPin); // read input value
if (val == HIGH) { // check if the input is HIGH (button released)
digitalWrite(ledPin,[glow] HIGH[/glow]); // turn LED On
} else {
digitalWrite(ledPin, [glow]LOW[/glow]); // turn LED Off
}
}
Where you just flip flop the pin state to what you're looking for. Hope this is what you're going after. If you're actually looking for the LED to turn on and off with each button press there are many examples on the forum for this, just search for it and you should find one.