Button Box / Toggle Switches

Im very new to arduinos and coding and what I want to make is a button box with switches. What I want it to do is when I flip the switch on it sends a single keystroke and when I flip the switch off It sends another keystroke.

Anyone know how to code this that could plz help me. Im trying to make a dashboard for my American Truck Simulator and I already found a code for the gauges but all I need is the switches.

Thank you

Which Arduino do you have? Only those with the 32U4 chip can send keystrokes.

Well planing to get the mega unless if that will not send keystrokes

// For Arduino Leonardo or Arduino Micro only
const byte SwitchPin = 7;
void setup() {
    pinMode(SwitchPin, INPUT_PULLUP);
}
void loop() {
    static byte lastSwitchState = LOW;
    static unsigned long lastSwitchStateTime = millis();

    byte currentSwitchState = digitalRead(SwitchPin);
    unsigned long currentTime = millis();


    // Looks for state change while filtering out contact bounces
    if (currentSwitchState != lastSwitchState && currentTime - lastSwitchStateTime > 10UL) {
        lastSwitchState = currentSwitchState;
        lastSwitchStateTime = currentTime;
        Keyboard.write(currentSwitchState ? 'n' : 'f');
    }
}

This code that johnwasser put in will work for switches. So when I turn on the switch it will push a key that I want. Lets say ''t''. When I flip the switch on it will hit ''t'' one time and then when I flip the switch off it will hit ''t'' one more time. Also to make the arduino do this or have these key strokes it has to be a Leonardo or a micro?

Also to make the arduino do this or have these key strokes it has to be a Leonardo or a micro?

Yes, the Arduino can do that. IF the Arduino is a Leonardo or a Micro (or some clone that uses a 32U4 chip).

Ok Thanks for your guys help. I really appreciate it. :slight_smile:

If you're worried about IO pins, you're not limited to just the capabilities of the Arduino itself. You can increase the number of digital pins you have available with external chips like a shift register (74HC165 and 74HC595 are popular) or port expander (like MCP23008). Datasheets for each are attached.

MCP23008 - 8-bit IO Expander with Serial Interface.pdf (295 KB)

74HC165 - 8-bit PISO Shift Register.pdf (1020 KB)

And the third datasheet.

74HC595 - 8-bit SIPO Shift Register Tristate.pdf (873 KB)

What would the code look like if you wanted to add additional toggle switches that functioned in the same way only with different keystrokes?

Basically just a copy paste job, adding in extra inputs in setup and variables to keep track of the state of each extra switch then adjusting the keystrokes within the Keyboard.write function.