簡體   English   中英

無法將字節從 Python serial.write() 發送到 Arduino

[英]Unable to send byte from Python serial.write() to Arduino

我編寫了一個 python 腳本,該腳本向 Arduino 發送和接收數據。 我可以毫無問題地接收數據,但是當我發送數據時,Arduino 似乎只接收垃圾。 Arduino 通過 USB 連接到 linux 電腦,電腦正在運行 ZA7F5F35426B92741137231B56382。 由於原始代碼包含許多不相關的內容並且可能會分散注意力,因此我准備了最簡單的草圖來演示該問題:

Python代碼:

#! /usr/bin/env python

import serial
import time

if __name__ == '__main__':
    ser = serial.Serial("/dev/ttyACM0", 9600, timeout=0)
    time.sleep(5)   # Wait for Arduino to reset and init serial
    ser.write(67)

Arduino 草圖

const byte LED_PIN = 13;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);
  
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
}

void loop() {
  if (Serial.available() > 0) {      
    byte b = Serial.read();
    if (b == 67) {
         digitalWrite(LED_PIN, HIGH);
         delay(500);
         digitalWrite(LED_PIN, LOW);
    }
  }
}

此代碼在接收到值為 67(大寫 C)的字節時使板載 LED 閃爍。 這適用於 Arduino 串行監視器,但不適用於運行 Python 腳本時。 我覺得我的問題可能與這個問題有關,但在那種情況下,重點是用戶不考慮空串行輸入緩沖區的情況,而我認為問題實際上出在發送的數據中。 這就是為什么我決定省略接收部分並僅使用板載 LED 簡化示例的原因。

更新

我將 python 腳本中的最后一行更改為:

    ser.write(bytes([67]))

(注意在 integer 值周圍添加的 [])。

任何人都可以解釋為什么這種語法會產生正確的結果? 似乎我正在將單個條目數組傳遞給 function 字節()。

請原諒我在 Pyton 的技能很差,我知道這個問題可能是基本的。

這真的很簡單; 您嘗試的所有方法都符合 pyserial 庫的規范。

根據 Pyserial 文檔:

write(data)
Parameters: data – Data to send.
Returns:    Number of bytes written.
Return type:    int
Raises: SerialTimeoutException – In case a write timeout is configured for the port and the time is exceeded.
Write the bytes data to the port. This should be of type bytes (or compatible such as bytearray or memoryview). Unicode strings must be encoded (e.g. 'hello'.encode('utf-8').

這就是為什么b'C樣式和bytes調用一樣有效的原因。

歸因: Pyserial 頁面

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM