Keeping track of last event


I'm trying to write a switch case statement that keeps track of the previous case, and depending on the the previous case it does something:

my code so far is

void setup() {
  // initialize serial communication:

void loop() {
   if (Serial.available() > 0) {
   int inByte =;
   int prev=1;
   switch (inByte){
     case 'a':
         Serial.println(prev, DEC);
       case 'b':       
       if (prev==2){
         prev--;// sets prev back to 1
         Serial.println(prev, DEC);

What i tried to do was initialize prev to 1, so in case 'a' prev=1 and then i want to update prev to equal 2, so that after the user types 'a' 2 is stored in prev, which then allows the if statement incase b to be true.

However what happens with this code is that prev always goes back to 1 and never equals 2 so the if statement in case b is never true.

can someone please suggest a good way to make this work?

Thank you, :slight_smile:

The variable prev needs to be either global (declared outside of loop) or static, so that it is not reset on each pass through loop.

Thank you!! :smiley: