I just received my new Arduino nano, and started to learn by doing, I do some blink led, potentiometer simple projects, and so on. now I want to do another simple project: turn on and off led by a simple button.
int pushButton = 7;
int LED = 9;
int val = 0;
void setup() {
Serial.begin(9600);
pinMode(pushButton, INPUT);
pinMode(LED, OUTPUT);
}
void loop() {
int buttonState = digitalRead(pushButton);
Serial.println(buttonState);
delay(1);
val = digitalRead(pushButton);
if (val == HIGH) {
digitalWrite(LED, LOW);
} else {
digitalWrite(LED, HIGH);
}
}
u can see in the code, that the Arduino send noted by serial port to the computer, and I can see when I push the button, I get the notes from the serial monitor, but the led don't turn on/off.
You have two variables for the button State, which is absolutely unnecessary. Also it would be enough to define them as booleans, but this is just finetuning...
thank a lot, you helped me so much.
i change the led sides(my electrical knowledge is not so good as you see)
and change the code(so it doesn't read the input 2 times)
and now it's working but i have another problem...
when i close the serial plotter, the program stop to work and led not working with me.
.. you should consider to debounce your button; otherwise you will get "surprising" flickering.
As serial.print is pretty slow - after removing this Serial.println your LED is reacting without a time buffer to the button reads and will present unpreductable results unless you care about debouncing the button.