1

我需要将鼠标坐标从 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

1 回答 1

1

您需要发送更多字节来表示每个数字。假设您每个数字使用 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();
  }
}
于 2020-09-21T11:07:03.173 回答