亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通過pyserial問題發送負值

通過pyserial問題發送負值

富國滬深 2023-08-22 14:44:40
我需要將鼠標坐標從 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();

  }

}


查看完整回答
反對 回復 2023-08-22
  • 1 回答
  • 0 關注
  • 1627 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號