首页 > 解决方案 > 如何通过串行代码将python-to-arduino转换为通过串行代码的python3-to-arduino?

问题描述

下面的代码用于在 spyder 中通过串行与 arduino 进行通信。在 spyder 的控制台窗口中,我会看到打印出的数据行:

78.7,77.9,100,80

78.7,77.9,100,80

78.7,77.9,100,80

78.7,77.9,100,80 ...

数据来自两个温度探头、一个流量计和恒温器设定温度。

我将我的 Kubuntu 18.04 系统升级到所有东西 python3。现在,代码运行,但 spyder3 控制台窗口不显示可见字符,而是滚动空白行。我用于解析和绘制此数据的其余 python 代码不起作用。

我花了一整天的时间试图解决这个问题,但没有运气。我猜对于比我更有经验的人来说,这是一个简单的解决方法。

旧的工作代码和下面的代码之间的唯一区别是打印语句添加了括号以消除语法错误。

python

""" This code was originally copied from:
Listen to serial, return most recent numeric values
Lots of help from here:
http://stackoverflow.com/questions/1093598/pyserial-how-to-read-last-line-sent-from-serial-device
"""

from threading import Thread

import time
import serial

last_received = ''
def receiving(ser):
    global last_received
    buffer = ''
    while True:
        buffer = buffer + ser.read(ser.inWaiting())
        if '\n' in buffer:
            lines = buffer.split('\n') # Guaranteed to have at least 2 entries
            last_received = lines[-2]
            #If the Arduino sends lots of empty lines, you'll lose the
            #last filled line, so you could make the above statement conditional
            #like so: if lines[-2]: last_received = lines[-2]
            buffer = lines[-1]


class SerialData(object):
    def __init__(self, init=50):
        try:
            self.ser = serial.Serial(
                port='/dev/ttyACM0',
                baudrate=9600,
                bytesize=serial.EIGHTBITS,
                parity=serial.PARITY_NONE,
                stopbits=serial.STOPBITS_ONE,
                timeout=0.1,
                xonxoff=0,
                rtscts=0,
                interCharTimeout=None
            )
        except serial.serialutil.SerialException:
            #no serial connection
            self.ser = None
        else:
            Thread(target=receiving, args=(self.ser,)).start()

    def next(self):
        if not self.ser:
            return '81.3,78.1,10.0,60.0,0' #100 #return anything so we can test when Arduino isn't connected
        #return a float value or try a few times until we get one
        for i in range(40):
            raw_line = last_received
            try:
               # return float(raw_line.strip())
                return str(raw_line.strip())
            except ValueError:
                print('bogus data',raw_line)
                time.sleep(.005)
        return 0.
    def __del__(self):
        if self.ser:
            self.ser.close()
    def write(self,val):
        self.ser.write(val)

if __name__=='__main__':
    s = SerialData()
    for i in range(500):
        time.sleep(.015)
        print( s.next())

标签: python-3.xserial-portpyserial

解决方案


Python 2.x 和 3.x 之间最显着的区别之一是文本字符串的编码方式。对于 Python 3.x,一切都是 Unicode,与 2.x 的 ASCII 相比,因此您只需解码从串行端口读取的原始字节:

buffer = buffer + ser.read(ser.inWaiting()).decode('utf-8')

编辑:现在你似乎有一个涉及异常的不同问题。看起来您的端口已打开,以确保您可以在实例化端口时更改处理异常的方式:

except serial.serialutil.SerialException as e: 
    print(e)
    self.ser = None

一旦你知道错误,你应该能够处理它。很可能您的端口在之前的会话中没有正确关闭。


推荐阅读