ProMicroでポインティングスティックを作った
動作
- ジョイスティックを傾けるとマウスポインタがその向きに動く
- 2番ピンのボタンを押すとジョイスティックの初期位置がリセットされる
- 3番ピンのボタンを押すとジョイスティックを傾けた方向にスクロールする
- 4番ピンのボタンでマウスの左クリック
配線図
使ってるジョイスティックがライブラリになかったため, テキトーに繋いでる。
コード
#include "Mouse.h" const int _UDPIN = A2; // UD入力 const int _LRPIN = A1; // LR入力 //const int _SWPIN = 7; // デジタルピン const int RESET_PIN = 2; const int CENTER_PIN = 3; const int CLICK_PIN = 4; int range = 12; int responseDelay = 20; int threshold = 1; int center = range / 2; int init_lr = 512; int init_ud = 512; char scroll_count = 0; void setup() { Serial.begin(9600); // pinMode(_SWPIN,INPUT) ; pinMode(RESET_PIN, INPUT_PULLUP); pinMode(CENTER_PIN, INPUT_PULLUP); pinMode(CLICK_PIN, INPUT_PULLUP); init_lr = analogRead(_LRPIN); init_ud = analogRead(_UDPIN); Mouse.begin(); } void loop() { if(digitalRead(RESET_PIN) == LOW) { init_lr = analogRead(_LRPIN); init_ud = analogRead(_UDPIN); } int ud = readAxis(_UDPIN, init_ud); int lr = -readAxis(_LRPIN, init_lr); Serial.print("UP-DOWN:"); Serial.print(ud, DEC); //DECは10進数フォーマットを表す Serial.print(" - Left-Rright:"); Serial.println(lr, DEC); // if (digitalRead(_SWPIN) == HIGH) { // Serial.println("switch on"); // } if(digitalRead(CENTER_PIN) == LOW) { if( scroll_count == 3) { Mouse.move(0, 0, -lr); scroll_count = 0; } else { scroll_count++; } } else { Mouse.move(ud, lr, 0); } // read the mouse button and click or not click: // if the mouse button is pressed: if (digitalRead(CLICK_PIN) == LOW) { // if the mouse is not pressed, press it: if (!Mouse.isPressed(MOUSE_LEFT)) { Mouse.press(MOUSE_LEFT); } } // else the mouse button is not pressed: else { // if the mouse is pressed, release it: if (Mouse.isPressed(MOUSE_LEFT)) { Mouse.release(MOUSE_LEFT); } } delay(responseDelay); } int readAxis(int pin, int init) { int reading = analogRead(pin); // reading = reading * range / 1023; // int distance = reading - center; int distance = NumLog( reading - init ); if( abs(distance) < threshold ) { distance = 0; } return distance; } int NumLog(int i) { int tei = 2; int sign = 1; if(i<0) { sign = -1; i = -i; } int j=0; for(; i>tei; j++) { i /= tei; } return sign*j; }