[英]Pyserial - RS232 9600,8,N,1 send and receive data
我需要使用 RS232 協議將值傳遞給串行連接的設備。 我需要通過 8 個字節的數據傳遞命令,然后才能接收響應。我不知道如何在 PySerial 中編寫它,所以如果有人能幫忙,那就太好了(9600 波特,8 個數據位,否)奇偶校驗和 1 個停止位。)
import serial
ser = serial.Serial('/dev/ttyUSB0') # open serial port
print(ser.name) # check which port was really used
ser.write(b'hello') # write a string
ser.close() # close port
定時器管理器命令結構由 1 個起始字節、1 個命令字節、5 個數據字節和 1 個字節校驗和組成。 每個消息包的格式如下:
BYTE 0 BYTE 1 BYTE 2 BYTE 3 BYTE 4 BYTE 5 BYTE 6 BYTE 7
200 COMMAND DATA1 DATA2 DATA3 DATA4 DATA5 CK SUM
我希望從機器接收以下信息:如果成功接收到命令,定時器管理器將響應:
BYTE 0 BYTE 1 BYTE 2
6 0 6
我要發送的實際數據是我需要傳遞給計時器的數據的結構如下:
BYTE 0 BYTE 1 BYTE 2 BYTE 3 BYTE 4 BYTE 5 BYTE 6 BYTE 7
200 31 4 0 0 0 0 235
這是通過 bytearray 傳遞的嗎?
ser.write( bytearray(200,31,4,0,0,0,0,235) );
首先,由於您使用的是 RS232,您必須在變量中設置要發送的 ASCII 字符。 然后,當你輸入一個變量時,你想發送的所有句子,將它解碼成字節發送。 它會是這樣的。
def sendserial(sendstring):
ser.port(yourport)
try:
ser.open()
except Exception as e:
flag=1
if ser.isOpen():
try:
ser.flushInput()
ser.flushOutput()
ser.write(bytes(sendstring,'iso-8859-1'))
#iso 8859-1 is the only encode that works for me
time.sleep(0.5)
numOfLines = 0
while True:
resp = bytes.decode(ser.readline())
result = ord(str(response))
if result == ord(ACK)
#I set previously the ACK var to the ASCII symbol that the machine returns
response = 'Y'
else:
response = 'N'
numOfLines = numOfLines +1
if (numOfLines>=1):
break
ser.close()
except Exception as e1:
print('Communication error...:' + str(e1))
else:
pass
return(response)
我通常有這樣的事情來通過串行端口執行二進制 IO:
from timeit import default_timer as clk
from serial import Serial, SerialException
class TimeManager(object):
def __init__(self, port, baudrate=9600):
self.ser = Serial(port, baudrate=baudrate)
self.ser.open()
self.ser.flushInput()
self.ser.flushOutput()
def send(self, tx):
tx = bytearray(tx)
try:
self.ser.write(tx)
self.ser.flush()
except SerialException as e:
if e.args == (5, "WriteFile", "Access is denied."):
# This occurs on win32 when a USB serial port is
# unplugged and replugged. It should be fixed by
# closing and reopening the port, which should happen
# in the error handling of our caller.
raise IOError(errno.ENOENT, "Serial port disappeared.",
self.ser.portstr)
else:
raise
def receive(self):
rx = bytearray()
delay = 10e-3 # s
timeout = 1 # s
end_time = clk() + timeout
while True:
time_remaining = end_time - clk()
if time_remaining < 0:
break
rx += self.ser.read(self.ser.inWaiting())
if 0 in rx:
break
time.sleep(delay)
if time_remaining <= 0:
raise IOError(errno.ETIMEDOUT, "Communication timed out.")
return rx
tm = TimeManager("/dev/ttyS0")
我的設備發送空終止消息( if 0 in rx:
行中的if 0 in rx:
)。 您必須為您的消息找出類似的條件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.