[英]Serial missing data in RPI3 using Python
我正在使用 raspberry pi 3 和此代碼向設備發送請求並接收響應。
#!/usr/bin/python3.7
import socket # Import socket module
import thread
import time
import serial
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
input = '5A03010d0a75'
print "Sending request... "+input
ser.write(input.decode("hex"))
print "Request sent."
output=""
while True:
output += ser.read(1)
#time.sleep(0.1)
print "Reading... "+output.encode('hex')
它處理響應但缺少字節,它應該接收一個 56 字節長度的字符串而不是 53。
a5030119010000010001000a201201181801300901000205050301175017010514210003010401200105160398336300000d70000004000000004
缺少 3 個字節
串行配置是制造商在文檔中所說的。 該設備與我在 Delphi 中制作的其他應用程序配合良好。
EXTRA 這是我的 delphi 應用程序和這個 py 腳本的比較:
Delphi app
A5030119010000010001000A20120118180130090100020505030117501701051421000301040120010516039833630004060104C200007D
Python script
a503011901000001000100 1201181801300901000205050301175017010514210003010401 010516039833630004060104c200007d
解決方案是將最大字節設置為 serial.read() 方法這應該與設備工作行為有關
#!/usr/bin/python3.7
#sudo python /home/testing.py
import serial
import time
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=5
)
input = '5A03010d0a75'
print "Sending request... "+input
ser.write(input.decode("hex"))
print "Request sent."
output=""
time.sleep(1)
while ser.inWaiting() > 0:
output += ser.read(10) #setting it to 10 will fix this problem
print "Reading... "+output.encode('hex')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.