Hello, I'm new to programming and I am currently going through a book with tutorials utilizing Arduino boards. I am using an UNO R3 and my IDE is using version 2.3.2 on a PC using windows 10. The code listed below is supposed to turn an LED on when a button is pressed, then turn it off when the button is pressed once again.
//turn on led when the button is pressed and off when the button is pressed again
const int LED = 13; //the pin for the led
const int BUTTON = 7; //the input pin where the button is connected
int val = 0; //val will be used to store the state of the input pin
int old_val = 0; // old_val will store last known val
int state = 0; //0 = led off while 1 = led on
void setup() {
// put your setup code here, to run once:
pinMode(LED, OUTPUT); //tells arsuino led is an output
pinMode(BUTTON, INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
val = digitalRead(BUTTON); //read input value and store it
// check whether the input is HIGH (button pressed)
// if so change state
if ((val == HIGH) && (old_val == LOW)){
state = 1 - state;
}
old_val = val; //val is now stored as old val
if (state == 1) {
digitalWrite(LED, HIGH); //turn on led
} else {
digitalWrite(LED, LOW); //tunn off led
}
}
This code was sporadic and would randomly work. This led me to believe there was a problem with the variables ability to change value correctly. So I attempted to print my variable values on the serial monitor to try and see what was happening. I added Serial.println() to the end of my code (as depicted below) and my code began working as expected with no other changes.
//turn on led when the button is pressed and off when the button is pressed again
const int LED = 13; //the pin for the led
const int BUTTON = 7; //the input pin where the button is connected
int val = 0; //val will be used to store the state of the input pin
int old_val = 0; // old_val will store last known val
int state = 0; //0 = led off while 1 = led on
void setup() {
// put your setup code here, to run once:
pinMode(LED, OUTPUT); //tells arsuino led is an output
pinMode(BUTTON, INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
val = digitalRead(BUTTON); //read input value and store it
// check whether the input is HIGH (button pressed)
// if so change state
if ((val == HIGH) && (old_val == LOW)){
state = 1 - state;
}
old_val = val; //val is now stored as old val
if (state == 1) {
digitalWrite(LED, HIGH); //turn on led
} else {
digitalWrite(LED, LOW); //tunn off led
}
Serial.println(state);
}
I am new to programing so I just want to know if there is something wrong with the original code or is there something else I'm not seeing, like a software issue? I appreciate any help you can give.