Pyserial - RS232 9600,8,N,1发送和接收数据

时间:2017-06-01 21:27:25

标签: python python-2.7 python-3.x pyserial

我需要使用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

Timer Manager命令结构由一个起始字节,一个命令字节,五个字节的数据和一个字节的校验和组成。每个消息包的格式如下:

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

我希望从机器上接收以下内容: 如果成功收到命令,Timer Manager将响应:

  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) );

2 个答案:

答案 0 :(得分:1)

首先,由于您使用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) 

答案 1 :(得分:0)

我通常有类似的东西通过串口进行二进制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:行)。您必须为您的消息找出类似的条件。