I have to program in Arduino a system that allows me to choose one of three options by pushing that number of times the button. After clicking 3 times, the counter have to reset and start all over again. Each time the button it’s pushed one of three LEDs is lighted.
This is my code, so far… but I don’t really know if it’s the best option to do it
const int led_dop=PIN_LED1;
const int led_ad=PIN_LED2;
const int led_fen=PIN_LED3;
const int button1=PIN_BTN1;
const int count=0;
void setup()
{
pinMode(led_dop,OUTPUT);
pinMode(led_ad,OUTPUT);
pinMode(led_fen,OUTPUT);
pinMode(button1,INPUT);
}
void loop()
{
static int button1_last=0;
int button1_state=digitalRead(button1);
while (button1_state != button1_last)
{
count++;
button1_last=button1_state;
}
if(count==1)
digitalWrite(led_dop,HIGH);
else if(count==2)
digitalWrite(led_ad,HIGH);
else if(count==3)
digitalWrite(led_fen,HIGH);
}
That’s what I have, I don’t know how to reset this and make the program do the count all over again. Can you help me??
Moderator edit: </mark> <mark>[code]</mark> <mark>
For example, you can start from the beginning if you press another time:
const int led_dop = PIN_LED1;
const int led_ad = PIN_LED2;
const int led_fen = PIN_LED3;
const int button1 = PIN_BTN1;
const int count = 0;
void setup()
{
pinMode(led_dop, OUTPUT);
pinMode(led_ad, OUTPUT);
pinMode(led_fen, OUTPUT);
pinMode(button1, INPUT);
}
void loop()
{
static int button1_last = 0;
int button1_state = digitalRead(button1);
while (button1_state != button1_last)
{
count++;
button1_last = button1_state;
if (count >= 4) {
count = 1;
}
}
switch (count) {
case 1:
digitalWrite(led_dop, HIGH);
break;
case 2:
digitalWrite(led_ad, HIGH);
break;
case 3:
digitalWrite(led_fen, HIGH);
break;
}
}
NOTE the differences in my code:
1- I add the code tags (to get that box with the code). The code tags are added by pressing the ' # ' icon in the top toolbar (next to the smiley faces);
2- I add the if in the while cycle:
if (count >= 4) {
count = 1;
}
so, if you press one more time the button, you restart the count.
3- I replace the if/else if by the switch/case (I think is better for more than 2 options to test).
I don't know if this part of the program:
int button1_state = digitalRead(button1);
while (button1_state != button1_last)
{
do what you want/think it do. What is the while for?