通过pyserial问题发送负值

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

  }

}


富国沪深
浏览 1585回答 1
1回答

弑天下

您需要发送更多字节来表示每个数字。假设每个数字使用 4 个字节。请注意,此代码需要适应 arduino 字节顺序。在 python 方面,你必须执行以下操作:def mouse_move(x, y):&nbsp; &nbsp; bytes = x.to_bytes(4, byteorder = 'big') + y.to_bytes(4, byteorder = 'big')&nbsp; &nbsp; arduino.write(bytes)&nbsp; &nbsp; print(pax)在接收方,您需要从字节组成部分重建数字,如下所示:byte bytes[4]&nbsp;void loop() {&nbsp; int x,y; /* use arduino int type of size 4 bytes&nbsp; */&nbsp; if (Serial.available() > 0) {&nbsp; &nbsp; Serial.readBytes(bytes, 4);&nbsp; &nbsp; x = bytes[0] << 24 | bytes[1] << 16 |&nbsp; bytes[2] << 8 |&nbsp; bytes[0]&nbsp; &nbsp; Serial.readBytes(bytes, 4);&nbsp; &nbsp; y = bytes[0] << 24 | bytes[1] << 16 |&nbsp; bytes[2] << 8 |&nbsp; bytes[0]&nbsp; &nbsp; Mouse.move(x, y, 0);&nbsp; &nbsp; Serial.read();&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python