#include Joystick_ j(0x13, 0x05, 32, 2, false, false, false, false, false, false, false, false, false, false, false); // 32 buttons 2 hats no axes uint8_t b = 0b00000000; //digital pins 0 to 7; x ^= (1 << n); - toggles nth bit of x. all other bits left alone. uint8_t b1 = 0b00000000; //digital pins 8 to 15 uint8_t b2 = 0b00000000; //digital pins 15 to 23 byte pins = 16; // we have 16 buttons bool g_lastButtonState[16]; //#define DEBUG void setup() { #if defined(DEBUG) Serial.begin(9600); // start serial for output #endif j.begin(); // init joystick for (int i = 2; i <= pins; i++) { pinMode(i, INPUT_PULLUP); // here we enable built-in pull up resistors for each pin, the default state of each pin is now 1 } } void loop() { // we will read 16 buttons into 3 bytes for (int i = 0; i <= pins; i++) { bool pin = !digitalRead(i); // note the ! before digitalRead - we invert our value if (pin == 1) { if (i < 8) { b |= (1 << i); // forces ith bit of b to be 1. all other bits left alone. } else if ( (i >= 8) && (i < 16)) { b1 |= (1 << (i - 8)); } else if (i >= 15) { b2 |= (1 << (i - 16)); } } else { if ( i < 8) { b &= ~(1 << i); // forces ith bit of b to be 0. all other bits left alone. } else if ( (i >= 8) && (i < 16)) { b1 &= ~(1 << (i - 8)); } else if (i >= 16) { b2 &= ~(1 << (i - 16)); } } } // we now have 3 bytes with button values, we can then send them to i2c or parse them locally: parse_button_array(b,0,0,0); parse_button_array(b1,9,0,0); parse_button_array(b2,17,0,0); #if defined(DEBUG) printBits(b); Serial.print(" "); printBits(b1); Serial.print(" "); printBits(b2); Serial.println(); #endif } void parse_button_array(uint8_t b, uint8_t start_btn, uint8_t end_btn, uint8_t byte_offset) { if (end_btn == 0) { end_btn = 8; } for (byte i = byte_offset; i < end_btn; i++) { bool v = (b >> i) & 1; if (v != g_lastButtonState[i + start_btn]) { j.setButton(i + start_btn, v); // here we send a joy button press if the button state has changed, 1st parameter is the button number, 2nd one is the value } g_lastButtonState[i + start_btn] = v; // here we save the value to our global array of last known button states } }