[英]Python/Arduino Serial communication
我們正在嘗試從Python與Arduino進行通信,但是在從python寫入串行端口時遇到問題
import serial
import time
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
time.sleep(2)
user_input = 'L'
while user_input != 'q':
user_input = input('H = on, L = off, q = quit' )
byte_command = user_input.encode()
print(byte_command)
ser.writelines(byte_command) # This line gives us the error.
time.sleep(0.5) # wait 0.5 seconds
print('q entered. Exiting the program')
ser.close()
以下是我們收到的錯誤:
返回len(data)TypeError:類型為'int'的對象沒有len()
writelines
接受字符串列表,因此您不能使用它發送單個字符串。 而是使用write
:
import serial
import time
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
time.sleep(2)
user_input = 'L'
while user_input != 'q':
user_input = input('H = on, L = off, q = quit')
byte_command = user_input.encode()
print(byte_command)
ser.write(byte_command) # This line gives us the error.
time.sleep(0.5) # wait 0.5 seconds
print('q entered. Exiting the program')
ser.close()
您的代碼可在我的計算機上使用。 我認為您嘗試使用的功能( writelines
)是不久前添加到pyserial的,因此也許您正在使用過時的版本。
據我所知,在任何情況下, writelines
都是從文件處理類繼承的,您實際上並不需要將其用於您要執行的操作。 其實我認為它沒有被很好地證明
只需將其更改為:
ser.write(byte_command)
如果願意,可以查看您擁有和/或更新的pyserial版本。
要檢查您的版本,請運行: pip3 list | grep serial
pip3 list | grep serial
如果沒有3.4版,則可以更新: pip3 install pyserial --upgrade
考慮到文件的writelines
工作方式(例如,請參見此處 ),您的錯誤實際上可能與您擁有的核心Python有關(供參考,我正在運行Python 3.7.3)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.