Simple sequence detection in Arduino

A question on how to do a button sequence detectuion was asked in a FB group about escape room technology. This can be done in many ways, even without any microcontrollers. What we’re looking for is a state machine. Going from one state to the next require that the previous state was set. Let’s try:

Please be advised that I haven’t tested this code.

Use it on your own risk!

2 Comments:

  1. Nikos Stivaktakis

    I suggest this quick fix:

    void loop()
    {
    if(digitalRead(button1)==0) { if(state==0) state=1; else if(state!=1) state=0; }
    if(digitalRead(button2)==0) { if(state==1) state=2; else if(state!=2) state=0; }
    if(digitalRead(button3)==0) { if(state==2) state=3; else if(state!=3) state=0; }
    if(digitalRead(button4)==0) { if(state==3) state=4; else if(state!=4) state=0; }
    if(digitalRead(button5)==0) { if(state==4) state=5; else if(state!=5) state=0; }
    if(digitalRead(button6)==0) { if(state==5) state=6; else if(state!=6) state=0; }

    if(state==6)
    {
    digitalWrite(output,HIGH);
    delay(1000);
    digitalWrite(output,LOW);

    state=0;
    }
    }

    • Thanks for the fix! This should avoid problems with debounce which I completely forgot to think about (I have only checked that the code is compiling 😉
      I will update the code example, but I will keep unlock procedure – you are correct but my approach will only toggle the output state where you reset after a second.

Leave a Reply