I'm making a project with three buttons. What I'm trying to do is to disable other buttons (make them not respond to a click event) when one of three buttons is pressed.
For now I have this code:
const int button1=3;
const int button2=4;
const int button3=5;
int button1State=0;
int button2State=0;
int button3State=0;
void setup() {
pinMode(button1, INPUT);
pinMode(button2, INPUT);
pinMode(button3, INPUT);
}
void loop() {
button1State=digitalRead(button1);
button2State=digitalRead(button2);
button3State=digitalRead(button3);
if( button1State == HIGH){
// do some stuff
}
if( button2State == HIGH){
// do some stuff
}
if( button3State == HIGH){
// do some stuff
}
}
Do you have any ideas how I could do it?
Thanks is advance for any suggestions!
-
what code do you have so far?AMADANON Inc.– AMADANON Inc.2016年04月14日 01:25:58 +00:00Commented Apr 14, 2016 at 1:25
-
I've added a code to the post questionIryna D– Iryna D2016年04月18日 23:02:52 +00:00Commented Apr 18, 2016 at 23:02
-
Yea, definitely use an FSM as per my suggestion below.AMADANON Inc.– AMADANON Inc.2016年04月19日 02:39:44 +00:00Commented Apr 19, 2016 at 2:39
1 Answer 1
The best solution for this is a finite state machine. There are lots of tutorials on state machines, just google.
Finite state machines are a very important concept in coding. You will find the need for them everywhere. Do yourself a favour, and read up about them, practice them, understand them, love them. Understand when they will be useful, and when they are not. If you do not, you will be back here shortly, with another question, which could also be solved by a finite state machine.
I strongly recommend you use this task as a practice task for learning about finite state machines.
Note also that, in electrical circuits, you frequently get bounce - when you push a button, your arduino will see many "button presses" (from off, to on, back to off), until it settles down. See http://blog.kennyrasschaert.be/images/20140401/Bouncy_Switch.png for example. A state machine can also help you with this.
If you don't want to learn about FSMs, read on:
initialise last_button_pressed to 0 (meaning no button pressed)
if last_button_pressed>0
if not(is_button_pressed(last_button_pressed) then
last_button_pressed=0
else (no button is pressed)
for each button_to_check (1,2,3)
if last_button_pressed=0 and is_button_pressed(button_to_check) then
last_button_pressed=button_to_check
-
Thanks a lot for your suggestion. I'll surely learn about finite state machine and hope it will work for meIryna D– Iryna D2016年04月18日 22:36:30 +00:00Commented Apr 18, 2016 at 22:36
-
The principle of FSMs are not that difficult. Have a go, and post your state diagram here, and I will give you some more pointers. Then you can try implementing it, and I can give you more pointers.AMADANON Inc.– AMADANON Inc.2016年04月19日 02:44:43 +00:00Commented Apr 19, 2016 at 2:44