Skip to content

Instantly share code, notes, and snippets.

@partlyhuman
Created January 5, 2023 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save partlyhuman/287f2556888738432c799bd79690e6f4 to your computer and use it in GitHub Desktop.
Save partlyhuman/287f2556888738432c799bd79690e6f4 to your computer and use it in GitHub Desktop.
DIY Arcade Spinner with Arduino Pro Micro 5V
#include <Mouse.h>
#include <Keyboard.h>
#include "EncoderTool.h"
#include "Bounce2.h"
using namespace EncoderTool;
// #undef P2 for player 1, #define P2 for player 2
#undef P2
#undef DEBUG
#define KEYSTROKE_MS 1
#define KEYHOLD_MS 30
#define PIN_A 9
#define MOUSE_MOVE_PX 10
#ifdef P2
#define KEY_A 'a'
#define KEY_LEFT 'd'
#define KEY_RIGHT 'g'
#else
#define KEY_A KEY_LEFT_CTRL
#define KEY_LEFT KEY_LEFT_ARROW
#define KEY_RIGHT KEY_RIGHT_ARROW
#endif
enum mode_t {
mode_keystroke,
mode_keyhold,
mode_axis,
mode_scroll,
mode_t_count
};
PolledEncoder encoder;
Bounce button_a;
mode_t mode;
unsigned long release_time;
static char last_dir;
void onEncoder(int position, int delta) {
switch (mode) {
case mode_keystroke:
{
char dir = (delta < 0) ? KEY_LEFT : KEY_RIGHT;
for (int i = 0; i < abs(delta); i++) {
Keyboard.press(dir);
delay(KEYSTROKE_MS);
Keyboard.releaseAll();
}
}
break;
case mode_keyhold:
{
char dir = (delta < 0) ? KEY_LEFT : KEY_RIGHT;
if (dir != last_dir && last_dir != 0) {
Keyboard.release(last_dir);
}
Keyboard.press(dir);
release_time = millis() + KEYHOLD_MS;
last_dir = dir;
}
break;
case mode_axis:
#ifdef P2
Mouse.move(0, delta * MOUSE_MOVE_PX, 0);
#else
Mouse.move(delta * MOUSE_MOVE_PX, 0, 0);
#endif
break;
case mode_scroll:
Mouse.move(0, 0, -delta);
break;
}
}
void setup()
{
#ifdef DEBUG
Serial.begin(9600);
#endif
encoder.begin(3, 2, 4);
encoder.attachCallback(onEncoder);
button_a.attach(PIN_A, INPUT_PULLUP);
button_a.interval(10);
Mouse.begin();
Keyboard.begin();
}
void loop()
{
encoder.tick();
if (encoder.buttonChanged() && encoder.getButton() == HIGH) {
mode = (mode_t)((mode + 1) % mode_t_count);
}
if (mode == mode_keyhold && last_dir != 0 && millis() > release_time) {
Keyboard.release(last_dir);
last_dir = 0;
}
button_a.update();
// pullup means low is active
if (button_a.fell()) {
Keyboard.press(KEY_A);
}
else if (button_a.rose()) {
Keyboard.release(KEY_A);
}
}
@partlyhuman
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment