我正在编写一些代码以从串行接口读取并返回接收到的数据的整数值。

看来我需要从中删除"\r\n"。我尝试了拆分,但是没有用。

这是我的代码:

import time
import serial
import string

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

while 1:
    x = ser.readline()

    if "t" in x:
        print x
        x = int(x)
        print x
        print "temp"
    elif "h" in x:
        print  "hum "
    elif "g" in x:
        print  "gas "
    else:
        pass

    time.sleep(1)


然后我有这个错误:

 Traceback (most recent call last):
  File "/home/pi/read.py", line 26, in <module>
    x=int(x)
ValueError: invalid literal for int() with base 10: 't0\r\n'


有人可以帮忙吗?

最佳答案

像这样尝试:

import time
import serial
import string

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

while True:
    line = ser.readline().rstrip()
    if not line:
        continue

    resultType = line[0]
    data = int(line[1:])

    if resultType == 't':
        print "Temp: {}".format(data)
    elif resultType == 'h':
        print "Hum: {}".format(data)
    elif resultType == 'g':
        print "Gas: {}".format(data)
    else:
        pass

    time.sleep(1)


第一个更改是str.rstrip()从串行接口读取的行。这将从字符串末尾删除所有"\r\n"字符或空格。第二个更改是将行拆分为“类型”字母(line[0])和数据(行的其余部分)。

关于python - 将串行接口(interface)数据转换为整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38299571/

10-12 13:03