与arduino的python 3串行通信

时间:2016-05-15 22:27:57

标签: python-3.x unicode arduino pyserial serial-communication

在此之前我不得不说我开始学习编程& Arduino,我宣称自己是一个无知的学徒。

大家好,我在操作从python中的arduino uno接收的数据时遇到问题。我的代码是:

import serial
import time
ser = serial.Serial('COM4', 115200, timeout=0)


i=150
while i>1:
   if ser.inWaiting()>0:         
      accline = ser.readline()
      nums=accline
      print (accline)
      #x=float(accline)
      time.sleep(.3)
      i=i-1

ser.close()

我得到的列表看起来像这样:

b'20, -0.03910064697265625000, -0.95796689987182617187, 0.10752676725387573242\r\n'
b'30, -0.03910064697265625000, -0.95796689987182617187, 0.10752676725387573242\r\n'
b'39, -0.03910064697265625000, -0.95796689987182617187, 0.10752676725387573242\r\n'
b'50, -0.03910064697265625000, -0.95796689987182617187, 0.10752676725387573242\r\n'
b'60, -0.03910064697265625000, -0.95796689987182617187, 0.10752676725387573242\r\n'
b'70, -0.03910064697265625000, -0.95796689987182617187, 0.10752676725387573242\r\n'
b'80, -0.03910064697265625000, -0.95796689987182617187, 0.10752676725387573242\r\n'
b'91, -0.03910064697265625000, -0.95796689987182617187, 0.10752676725387573242\r\n'
b'100, -0.03910064697265625000, -0.95796689987182617187, 0.10752676725387573242\r\n'
b'110, -0.03910064697265625000, -0.95796689987182617187, 0.10752676725387573242\r\n'
b'120, -0.03910064697265625000, -0.95796689987182617187, 0.10752676725387573242\r\n'

我一直在寻找摆脱那些b''' (似乎是一个二进制消息)和r \ n \来自数据,以便在列表[]中获取从讲座中获得的数据。我不知道该怎么做

我成功的做法是使用print清洁打印(accline.decode(' utf-8')(不知道xD是什么意思)获得我想要的东西,但有时只是(它随机出现) )。 错误讯息:

---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-94-9347cecf9200> in <module>()
      9         accline = ser.readline()
     10         nums=accline
---> 11         print (accline.decode('utf-8'))
     12         #x=float(accline)
     13         time.sleep(.3)

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 36:     invalid start byte

所以我的问题是:如何将数据存储在一个列表中(看起来很简单,但我很头疼:()

编辑:最后我解决了这个问题。代码如下:

import serial
import time
ser = serial.Serial('COM4', 115200, timeout=0)


i=10
while i>1:
    if ser.inWaiting()>0:         
        accline = ser.readline()[:-2]
        datanums=accline.split(b',')
        print (accline)
        print (datanums[])
        time.sleep(.3)
        i=i-1

ser.close()

0 个答案:

没有答案