0

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!

3
  • what code do you have so far? Apr 14 '16 at 1:25
  • I've added a code to the post question
    – Iryna D
    Apr 18 '16 at 23:02
  • Yea, definitely use an FSM as per my suggestion below. Apr 19 '16 at 2:39
2

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
2
  • Thanks a lot for your suggestion. I'll surely learn about finite state machine and hope it will work for me
    – Iryna D
    Apr 18 '16 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. Apr 19 '16 at 2:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.