如何从python serial.readline()数据读取数据到字符串

时间:2019-03-18 09:45:22

标签: python raspberry-pi3

计划详情:

#!/usr/bin/env python
import time
import serial

ser = serial.Serial(
port='/dev/ttyS0', 
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
counter=0

def Off():
    print('17')

def Go():
    print('18')

if __name__ == '__main__':
    commands = {15:Go, 14:Off}

    try:
        ser.write(str.encode('allon'))

        while True:
            x=ser.readline()
            print(x)
            commands[x]()

    finally:
           print("ok")

标题

在输出中,我得到了

b'On\r\n'
b''
b'Ogg\r\n'
b''
b''
b'Off\r\n'
b'On\r\n'

但是我想要像x = 14这样的字符串 这样我就可以在命令x中传递该值

我在这里出错.........

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

#!/usr/bin/env python
import time
import serial

ser = serial.Serial(
    port='/dev/ttyS0', 
    baudrate = 9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=1
)
counter=0

def ON():  # added ON
    print('15')

def Off():
    print('17')

def Go():
    print('18')

if __name__ == '__main__':
    commands = {b'Go': Go, b'ON': On, b'Off': Off}  # changed commands dictionary

    try:
        ser.write(str.encode('allon'))

        while True:
            x = ser.readline().strip()  # added strip (removing \r\n)
            print(x)  # remove this line if you do not want all input to be printed
            if x in commands:  # added condition
                commands[x]()

    finally:
           print("ok")