📜  Arduino-鼠标按钮控制

📅  最后修改于: 2020-11-05 03:40:49             🧑  作者: Mango


使用鼠标库,您可以使用Arduino Leonardo,Micro或Due来控制计算机的屏幕光标。

此特定示例使用五个按钮来移动屏幕上的光标。其中四个按钮是方向性的(上,下,左,右),一个用于鼠标左键。 Arduino的光标移动始终是相对的。每次读取输入时,光标的位置都会相对于其当前位置进行更新。

每当按下方向按钮之一时,Arduino就会移动鼠标,在适当的方向上将HIGH输入映射到5的范围。

第五个按钮用于控制鼠标的左键单击。释放按钮后,计算机将识别该事件。

所需组件

您将需要以下组件-

  • 1×面包板
  • 1个Arduino Leonardo,Micro或Due板
  • 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);
}

注意代码

使用微型USB电缆将开发板连接至计算机。这些按钮从引脚2到6连接到数字输入。请确保使用10k下拉电阻。