0°

Arduino内置教程-USB-鼠标按键控制

用鼠标库文件,你可以用一个Arduino Leonardo, Micro, 或者 Due来控制一个电脑的光标显示。这个例子示范了怎么用5个按键来移动屏幕上的光标。4个按键时方向(上下左右),1个是鼠标左键。

简介

  • 用鼠标库文件,你可以用一个Arduino Leonardo, Micro, 或者 Due来控制一个电脑的光标显示。这个例子示范了怎么用5个按键来移动屏幕上的光标。4个按键时方向(上下左右),1个是鼠标左键。
  • 光标移动是有关联的。每次读到输入时,光标的位置就会根据它当前位置更新。
  • 无论什么时候按下方向按键,Arduino都会移动鼠标,匹配一个高电平到范围是5的合适的方向。
  • 第5个按键用来控制鼠标左键按下。当按下第5个按键时,开发板发送一个按下到电脑。当按键松开时,电脑会意识到这件事。
  • 注意:当你用Mouse.move()命令时,Arduino会接管你的电脑键盘!为了确保你没有失去对电脑的控制同时运行这个函数,确定在你调用Mouse.move()前,启动一个可靠的控制系统。这个程序只会在你按下按键时更新光标位置。

硬件要求

  • Arduino Leonardo, Micro or Due开发板
  • 5 *按键
  • 5* 10kΩ电阻
  • 连接线
  • 面包板

电路

  • 通过一个 micro-USB 线连接你的开发板到你的电脑。按键连接到数字输入从pin2到pin6。确保你用上10kΩ下拉电阻。

原理图

样例代码

/*
  ButtonMouseControl

 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.

 created 15 Mar 2012
 modified 27 Mar 2012
 by Tom Igoe

 this code is in the public domain

 */

#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 the mouse button is not pressed:
  else {
    // if the mouse is pressed, release it:
    if (Mouse.isPressed(MOUSE_LEFT)) {
      Mouse.release(MOUSE_LEFT);
    }
  }

  // a delay so the mouse doesn't move too fast:
  delay(responseDelay);
}
「点点赞赏,手留余香」

    还没有人赞赏,快来当第一个赞赏的人吧!
0 条回复 A 作者 M 管理员
    所有的伟大,都源于一个勇敢的开始!
欢迎您,新朋友,感谢参与互动!欢迎您 {{author}},您在本站有{{commentsCount}}条评论