Else if loop problem

Hii,
Fairly new to coding + working with an Arduino for the first time.
Using a Pro Micro I wanted to map each button to a letter on the keyboard, and so far so good!


The problem is I'd like to have the fourth button write 'E' instead of 'D' as long as button one ('A') was the last pressed button. Problematic loop below:

  else if (digitalRead(6) == 0) 
  {
    if (int lastButtonPressed = 3)
    {
      Keyboard.write('E');
    }
    else
    {
      Keyboard.write('D');
    }
    int lastButtonPressed = 6;
    Serial.println(lastButtonPressed);
    delay(200);
  }

And here's the full code for context:

// key combonations
#include <Keyboard.h>

int lastButtonPressed = -1;

void setup() {
pinMode(3, INPUT_PULLUP); // usual button setup 
pinMode(4, INPUT_PULLUP); 
pinMode(5, INPUT_PULLUP);
pinMode(6, INPUT_PULLUP);

Serial.begin(9600); // serial debug
}

void loop() {
 Keyboard.begin();
 if (digitalRead(3) == 0)
  {
    Keyboard.write('A');
    int lastButtonPressed = 3;
    Serial.println(lastButtonPressed);
    delay(200);
  }
  else if (digitalRead(4) == 0) 
  {
    Keyboard.write('B');
    int lastButtonPressed = 4;
    Serial.println(lastButtonPressed);
    delay(200);
  }
  else if (digitalRead(5) == 0) 
  {
    Keyboard.write('C');
    int lastButtonPressed = 5;
    Serial.println(lastButtonPressed);
    delay(200);
  }
  else if (digitalRead(6) == 0) 
  {
    if (int lastButtonPressed = 3)
    {
      Keyboard.write('E');
    }
    else
    {
      Keyboard.write('D');
    }
    int lastButtonPressed = 6;
    Serial.println(lastButtonPressed);
    delay(200);
  }
  Keyboard.end();
}

My mistake is probably very simple but I thought it couldn't hurt to ask. Thanks (^ω^)

Oops

if (lastButtonPressed == 3)

1 Like

 if (digitalRead(3) == 0)
  {
    Keyboard.write('A');
    int lastButtonPressed = 3; //get rid of “int”
. . .
  • What is the purpose of having a local variable lastButtonPressed when you should use the global variable ?
1 Like

As suggested by @LarryD : get rid of int.
Each time you use int bla, a new local variable named bla will be made.
This local variable will shadow the global or higher scope variables with the same name.
Read on "variable scope".
bla = 0 will set variable bla to value 0.
bla == 0 will compare value stored in bla with 0 and yield True or False...

2 Likes

OMG! I didn’t catch that. Thanks!!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.