Arduino - 滑鼠按鈕控制

使用滑鼠庫,你可以使用 Arduino Leonardo,Micro 或 Due 來控制計算機的螢幕游標。

此特定示例使用五個按鈕移動螢幕上的游標。其中四個按鈕是方向性的(向上,向下,向左,向右),一個用於滑鼠左鍵單擊。Arduino 的游標移動始終是相對的。每次讀取輸入時,游標的位置都會相對於其當前位置進行更新。

每當按下一個方向按鈕時,Arduino 將移動滑鼠。第 5 個按鈕用於控制滑鼠左鍵單擊。釋放按鈕後,計算機將識別該事件。

需要的元件

你將需要以下元件 -

  • 1×麵包板
  • 1×Arduino Leonardo,Micro 或 Due board
  • 5×10k 歐姆電阻器
  • 5×瞬時按鈕

程式

按照電路圖並連線面包板上的元件,如下圖所示。

滑鼠按鈕麵包板

草圖

在你的計算機上開啟 Arduino IDE 軟體。用 Arduino 語言編碼將控制你的電路。單擊“新建”開啟新的草圖檔案。

對於此示例,你需要使用 Arduino IDE 1.6.7

草圖

Arduino 程式碼

/*
   Button Mouse Control
   For Leonardo and Due boards only .Controls the mouse from 
   five pushbuttons on an Arduino Leonardo, Micro or Due.
   Hardware:
   * 5 pushbuttons attached to D2, D3, D4, D5, D6
   The mouse movement is always relative. This sketch reads
   four pushbuttons, and uses them to set the movement of the mouse.
   WARNING: When you use the Mouse.move() command, the Arduino takes
   over your mouse! Make sure you have control before you use the mouse commands.
*/

#include "Mouse.h"
// set pin numbers for the five buttons:
const int upButton = 2;
const int downButton = 3;
const int leftButton = 4;
const int rightButton = 5;
const int mouseButton = 6;
int range = 5; // output range of X or Y movement; affects movement speed
int responseDelay = 10; // response delay of the mouse, in ms

void setup() {
   // initialize the buttons' inputs:
   pinMode(upButton, INPUT);
   pinMode(downButton, INPUT);
   pinMode(leftButton, INPUT);
   pinMode(rightButton, INPUT);
   pinMode(mouseButton, INPUT);
   // initialize mouse control:
   Mouse.begin();
}

void loop() {
   // read the buttons:
   int upState = digitalRead(upButton);
   int downState = digitalRead(downButton);
   int rightState = digitalRead(rightButton);
   int leftState = digitalRead(leftButton);
   int clickState = digitalRead(mouseButton);
   // calculate the movement distance based on the button states:
   int xDistance = (leftState - rightState) * range;
   int yDistance = (upState - downState) * range;
   // if X or Y is non-zero, move:
   if ((xDistance != 0) || (yDistance != 0)) {
      Mouse.move(xDistance, yDistance, 0);
   }

   // if the mouse button is pressed:
   if (clickState == HIGH) {
      // if the mouse is not pressed, press it:
      if (!Mouse.isPressed(MOUSE_LEFT)) {
         Mouse.press(MOUSE_LEFT);
      }
   } else {                           // else the mouse button is not pressed:
      // if the mouse is pressed, release it:
      if (Mouse.isPressed(MOUSE_LEFT)) {
         Mouse.release(MOUSE_LEFT);
      }
   }
   // a delay so the mouse does not move too fast:
   delay(responseDelay);
}

程式碼注意

使用 micro-USB 線將電路板連線到計算機。按鈕連線到引腳 2 至 6 的數字輸入。確保使用 10k 下拉電阻。