问题描述
我需要将鼠标坐标从python发送到arduino。如您所知,有X和Y轴,并且在这些轴上有一些负值,例如-15或-10等。 Arduino的串行仅接受字节,因此字节限制为0到256。我的问题就从这里开始。我无法从python向arduino发送负值。这是我的python代码:
def mouse_move(x,y):
pax = [x,y]
arduino.write(pax)
print(pax)
例如,当x或y为负值(如-5)时,程序崩溃,因为字节数组为0-256。
这是我的arduino的代码:
#include <Mouse.h>
byte bf[2];
void setup() {
Serial.begin(9600);
Mouse.begin();
}
void loop() {
if (Serial.available() > 0) {
Serial.readBytes(bf,2);
Mouse.move(bf[0],bf[1],0);
Serial.read();
}
}
解决方法
您需要发送更多字节来代表每个数字。 假设每个数字使用4个字节。 请注意,此代码需要适应arduino的流行程度。 在python方面,您将必须执行以下操作:
def mouse_move(x,y):
bytes = x.to_bytes(4,byteorder = 'big') + y.to_bytes(4,byteorder = 'big')
arduino.write(bytes)
print(pax)
在接收器端,您需要从其字节构成者中重构数字 像这样:
byte bytes[4]
void loop() {
int x,y; /* use arduino int type of size 4 bytes */
if (Serial.available() > 0) {
Serial.readBytes(bytes,4);
x = bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[0]
Serial.readBytes(bytes,4);
y = bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[0]
Mouse.move(x,y,0);
Serial.read();
}
}