我想使用ardunio lenonardo来模拟鼠标运动。
我使用旋转编码器来控制鼠标运动,转速越大,鼠标运动越快,mouse.move 只在y轴上运动。低速转动时鼠标反应还好,但当旋转编码器高速转动时鼠标并未灵敏反应。
ardunio代码如下
#include <Mouse.h>
#define encoderPin A0
#define maxEncoderValue 1023
volatile unsigned int currentEncoder0Pos = 0;
volatile unsigned int previouscurrentEncoder0Pos = 0;
long wheelValue = 0;
bool isWheelValuePositive = true;
unsigned long lastActivationTime = 0; // 上次激活的时间
const unsigned long activationDelay = 5000; // 延迟时间,单位为毫秒
void setup() {
pinMode(encoderPin, INPUT);
pinMode(11,INPUT);//left mouse
Mouse.begin();
Serial.begin (9600);
pinMode(6, OUTPUT); // Direction
pinMode(5, OUTPUT); // Step
pinMode(7, OUTPUT);
pinMode(4, INPUT); // FeedingTouch
pinMode(3, INPUT); // Stop
pinMode(8, INPUT);
digitalWrite(7, LOW);
}
void loop() {
updateMouseWheel();
currentEncoder0Pos = analogRead(encoderPin);
}
// output mousewheel positive value when going in one direction
// and output a negative value when going in the opposite direction
void updateMouseWheel()
{
// 检查编码器的位置是否发生了变化
if(previouscurrentEncoder0Pos != currentEncoder0Pos)
{
// 如果当前的读数大于上一次的读数,那么认为是顺时针旋转
if(currentEncoder0Pos > previouscurrentEncoder0Pos)
{
// 如果滚轮之前是在反方向滚动,那么将滚轮值重置为0
if(!isWheelValuePositive)
{
wheelValue = 0;
isWheelValuePositive = true;
}
// 使滚轮值递增
wheelValue++;
}
// 如果当前的读数小于上一次的读数,那么认为是逆时针旋转
else if(currentEncoder0Pos < previouscurrentEncoder0Pos)
{
// 如果滚轮之前是在顺时针方向滚动,那么将滚轮值重置为0
if(isWheelValuePositive)
{
wheelValue = 0;
isWheelValuePositive = false;
}
// 使滚轮值递减
wheelValue--;
}
// 更新前一次的编码器位置为当前位置
previouscurrentEncoder0Pos = currentEncoder0Pos;
// 在串口打印出滚轮值
Serial.println (wheelValue);
// 模拟鼠标在y轴上的移动
Mouse.move(0,wheelValue,0);
}
}