Hi,
I'm making a simple program that uses a LED and a push button to toggle the LED on and off. I'm using a variable named state for this, basically "if button pressed and state is 1 (on), set state to 0 (off) and turn off the LED" and the other way round.
Here's my code:
const int LED = D1;
const int button = D0;
int state;
void setup() {
pinMode(LED, OUTPUT);
pinMode(button, INPUT_PULLUP);
digitalWrite(LED, LOW);
}
void loop() {
if(digitalRead(button) == LOW){
if(state == 0){
state = 1;
digitalWrite(LED, HIGH);
} else if(state == 1) {
state = 0;
digitalWrite(LED, LOW);
}
}
}
I tried using const int state; but when I change it with int state = 1; it says it's read-only. Do I use a bool variable that stores true or false, or can I do something with the current int variable?
Thanks
I assume that the sketch does not do what you want. Your use of an int variable to hold the state is OK but there is a problem with how you read the button input
Think what happens if you hold down the button for long enough for the loop() function to run more than once. Bear in mind that the loop() function in your sketch runs millions of times per second
So, how to fix the problem ?
Clumsy and not a good idea, but try it anyway, put delay(1000); at the end of the loop function and don't hold the button down for more than one second
Much better, you need to detect when the button becomes pressed rather than when it is pressed. See the StateChangeDetection example in the IDE
When you put const you are promising that the value of the variable will NEVER change. Then you tried to change it, so you go an error. That should be expected. Don't use const for things that can change.
1. I would like to describe your hardware setup by Fig-1. I assume that you are using UNOR3 and as such I have preferred to connect SW/button at DPin-4 and LED at DPin-5 due to the fact that DPin-0/1 are usually remian connected with PC/IDE.
Figure-1:
2. I would like to describe the interactions of your button/LED with the help of the following Flow Chart (Fig-2) to enable you to visualize what is going on in the button/LED interactions.
Figure-2:
3. The following is a tested sketch for the Flow Chart of Fig-2, which may help you to write better codes by discarding while-do structure. Please, just press the switch and release it immediately. If you hold down the button/SW1, you will observe that LED is blinking.
#define button 4
#define LED 5
bool state = false;
void setup()
{
pinMode(LED, OUTPUT);
pinMode(button, INPUT_PULLUP);
}
void loop()
{
while (digitalRead(button) != LOW)
{
; //wait
}
if (state == false) //LED is Off
{
digitalWrite(LED, HIGH); //turn On LED
state = true;
}
else
{
digitalWrite(LED, LOW);
state = false;
}
delay(200);
}