#include #define ENCXA 5 #define ENCXB 6 #define ENCYA 8 #define ENCYB 9 #define BTN_LEFT 10 #define BTN_MIDDLE 16 #define BTN_RIGHT 14 const uint8_t encodeA[] = {0b10, 0b00, 0b11, 0b01}; const uint8_t buttonIN[] = {BTN_LEFT, BTN_MIDDLE, BTN_RIGHT}; const uint8_t button[] = {MOUSE_LEFT, MOUSE_MIDDLE, MOUSE_RIGHT}; volatile int countX, countY; volatile uint8_t preX, preY; int preCountX, preCountY; uint8_t btnStat[3]; void setup() { pinMode(ENCXA, INPUT_PULLUP); pinMode(ENCXB, INPUT_PULLUP); pinMode(ENCYA, INPUT_PULLUP); pinMode(ENCYB, INPUT_PULLUP); for(int i=0; i<3; i++) pinMode(buttonIN[i], INPUT_PULLUP); // マウス初期化 Mouse.begin(); countX = 0; countY = 0; preCountX = 0; preCountY = 0; preX = 0; preY = 0; for(int i=0; i<3; i++) btnStat[i] = 1; // タイマ1割り込み 標準動作 TCCR1A = 0; TCCR1B |= _BV(CS11) | _BV(CS10); // 16MHzを64分周 TCNT1 = 0 - 250; // 1msでオーバーフロー TIMSK1 |= _BV(TOIE1); // タイマ1オーバーフロー割り込み許可 } ISR(TIMER1_OVF_vect) { uint8_t a, b, ab; // マウスX軸 a = digitalRead(ENCXA); b = digitalRead(ENCXB); ab = (a << 1) | b; if(preX != ab) { if(encodeA[preX] == ab) --countX; else ++countX; preX = ab; } // マウスY軸 a = digitalRead(ENCYA); b = digitalRead(ENCYB); ab = (a << 1) | b; if(preY != ab) { if(encodeA[preY] == ab) --countY; else ++countY; preY = ab; } TCNT1 = -250; // 1msでオーバーフロー } void loop() { int diffX, diffY; uint8_t bt; diffX = countX - preCountX; diffY = countY - preCountY; if((diffX != 0) || (diffY != 0)) { Mouse.move(diffX * 10, diffY * 10, 0); preCountX = countX; preCountY = countY; } for(int i=0; i<3; i++) { bt = digitalRead(buttonIN[i]); if(btnStat[i] != bt) { if(bt) Mouse.release(button[i]); else Mouse.press(button[i]); btnStat[i] = bt; } } }