Using three toggle switches in line as keystrokes

Hello there :slight_smile:
Arduino Pro Micro
Arduino IDE 2.2.1
Windows 10

I have six toggle switches, each of which are supposed to only sent a "keystroke" (so sw1 -> "1", sw2 -> "2"... and so on) when toggled either on or off.
To save Pins I want to combine the switch's inputs if possible (A3). The outputs are right now connected to Pin 2 to 7.
The sinner I am, I decided to use ChatGPT but oh god what a mess. Maybe I used the wrong prompts but I got code which just didnt work. I will however attach the code I have been using prior to this where i only used one button which worked flawlessly.

Thanks for any help, ideas or maybe even solutions!

The Code:

#include "Keyboard.h"

const int switchPin = A3; 

void setup() {
  pinMode(switchPin, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  static int previousState = HIGH;

  int currentState = digitalRead(switchPin); 


  if (currentState != previousState) {
    delay(10); 

   
    if (currentState == LOW) {
      Keyboard.write('7');
    } else {
      Keyboard.write('7');
    }

    delay(10); 

    previousState = currentState; 
  }
}

you want to generate a '7' whenever the switch is toggles on or off and not just when toggled on or pressed?

the 2nd delay is unnecessary

look this over

// check multiple buttons and toggle LEDs

enum { Off = HIGH, On = LOW };

byte pinsLed [] = { 10, 11, 12 };
byte pinsBut [] = { A1, A2, A3 };
#define N_BUT   sizeof(pinsBut)

byte butState [N_BUT];

// -----------------------------------------------------------------------------
int
chkButtons ()
{
    for (unsigned n = 0; n < sizeof(pinsBut); n++)  {
        byte but = digitalRead (pinsBut [n]);

        if (butState [n] != but)  {
            butState [n] = but;

            delay (10);     // debounce

            if (On == but)
                return n;
        }
    }
    return -1;
}

// -----------------------------------------------------------------------------
void
loop ()
{
    switch (chkButtons ())  {
    case 2:
        digitalWrite (pinsLed [2], ! digitalRead (pinsLed [2]));
        break;

    case 1:
        digitalWrite (pinsLed [1], ! digitalRead (pinsLed [1]));
        break;

    case 0:
        digitalWrite (pinsLed [0], ! digitalRead (pinsLed [0]));
        break;
    }
}

// -----------------------------------------------------------------------------
void
setup ()
{
    Serial.begin (9600);

    for (unsigned n = 0; n < sizeof(pinsBut); n++)  {
        pinMode (pinsBut [n], INPUT_PULLUP);
        butState [n] = digitalRead (pinsBut [n]);
    }

    for (unsigned n = 0; n < sizeof(pinsLed); n++)  {
        digitalWrite (pinsLed [n], Off);
        pinMode      (pinsLed [n], OUTPUT);
    }
}

of course you can use another array containing the keyboard value corresponding to each switch

1 Like

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