我需要將鼠標坐標從 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(); }}
1 回答

弒天下
TA貢獻1818條經驗 獲得超8個贊
您需要發送更多字節來表示每個數字。假設每個數字使用 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();
}
}
添加回答
舉報
0/150
提交
取消