Arduino - 鼠标控制

Arduino - 鼠标控制 首页 / Arduino入门教程 / Arduino - 鼠标控制

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

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

所需组件

您将需要以下组件-

  • 1×Breadboard
  • 1×Arduino Leonardo,Micro或Due board
  • 5×10k欧姆电阻器
  • 5× momentary pushbuttons

电路图

遵循电路图,并连接面包板上的组件,如下图所示。

链接:https://www.learnfk.comhttps://www.learnfk.com/arduino/arduino-mouse-button-control.html

来源:LearnFk无涯教程网

Mouse Button Breadboard

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"
//为五个按钮设置引脚号:
const int upButton=2;
const int downButton=3;
const int leftButton=4;
const int rightButton=5;
const int mouseButton=6;
int range=5; //X或Y运动的输出范围;影响移动速度
int responseDelay=10; //鼠标响应延迟,ms

void setup() {
   //初始化按钮的输入:
   pinMode(upButton, INPUT);
   pinMode(downButton, INPUT);
   pinMode(leftButton, INPUT);
   pinMode(rightButton, INPUT);
   pinMode(mouseButton, INPUT);
   //初始化鼠标控制:
   Mouse.begin();
}

void loop() {
   //阅读按钮:
   int upState=digitalRead(upButton);
   int downState=digitalRead(downButton);
   int rightState=digitalRead(rightButton);
   int leftState=digitalRead(leftButton);
   int clickState=digitalRead(mouseButton);
   //根据按钮状态计算移动距离:
   int xDistance=(leftState - rightState) * range;
   int yDistance=(upState - downState) * range;
   //如果 X 或 Y 不为零,则移动:
   if ((xDistance != 0) || (yDistance != 0)) {
      Mouse.move(xDistance, yDistance, 0);
   }

   //如果按下鼠标按钮:
   if (clickState == HIGH) {
      //如果未按下鼠标,请按下它:
      if (!Mouse.isPressed(MOUSE_LEFT)) {
         Mouse.press(MOUSE_LEFT);
      }
   } else {                           //否则不按下鼠标按钮:
      //如果鼠标被按下,释放它:
      if (Mouse.isPressed(MOUSE_LEFT)) {
         Mouse.release(MOUSE_LEFT);
      }
   }
   //延迟,这样鼠标就不会移动得太快:
   delay(responseDelay);
}

注意代码

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

无涯教程网

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

数据结构与算法之美 -〔王争〕

如何做好一场技术演讲 -〔极客时间〕

Nginx核心知识150讲 -〔陶辉〕

Node.js开发实战 -〔杨浩〕

现代C++编程实战 -〔吴咏炜〕

性能测试实战30讲 -〔高楼〕

Kafka核心源码解读 -〔胡夕〕

搞定音频技术 -〔冯建元 〕

郭东白的架构课 -〔郭东白〕

好记忆不如烂笔头。留下您的足迹吧 :)