RPi和Arduino之间通过UART进行通信

时间:2018-07-02 07:15:36

标签: python

我正在使Arduino通过串行通信与RPi通信。当RPi将“ 1”发送给Arduino时,Arduino将使用传感器的数据进行回复。通信可以正常工作,但是在对接收到的数据进行分类时,发生了一些奇怪的事情……

Step 1: From RPi to Arduino. The message '1'
Step 2: Arduino acknowledged, then from Arduino to RPi, the message is '[0.10,8.0,1]'
Step 3: RPi split the received message into 3 data (since it's from 3 sensors) - Problem's at here

这是完整的编码:

import serial

ser=serial.Serial(port='/dev/ttyS0', baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_TWO, bytesize=serial.EIGHTBITS)

newData = False
receivedChar = ""
recvInProgress = False
data_0 = 0
data_1 =0
data_2 = 0

def recvWithStartEndMarkers():
    global newData
    global receivedChar
    global recvInProgress

    startMarker = '['
    endMarker = ']'

    while ser.inWaiting() > 0 and newData == False:
        rc = ser.read(1)
        rc = rc.decode('utf-8', errors='replace')

        if recvInProgress == True:
            if rc != endMarker:
               receivedChar += rc
            else:
               recvInProgress = False

        elif rc = startMarker:
            recvInProgress = True

def showNewData():
    global newData

    if newData == True:
        print(receivedChar) #The outcome at the console is "0.10,8.0,1" , which is what I want.
        newData = False

def Process_Recv_Data():
    global data_0
    global data_1
    global data_2

    if receivedChar != "":
        data = receivedChar.split(',')

        # PROBLEM IS AT HERE
        for each_data in data:
            print(each_data) 
        #At the console, I am seeing this:
        #0
        #.
        #1
        #0
        # 
        #
        #8
        #.
        #0
        #
        #
        #1

        receivedChar = ""

cmd = '1'
ser.write(cmd.encode())

while True:
    recvWithStartEndMarkers()
    showNewData()
    Process_Recv_Data()

因此,最终我无法将0.10放入data_0、8.0放入data_1和1放入data_2。为什么会这样?

ps,我知道我的编码很乱,不应该使用那么多的全局变量。稍后我会整理一下,所以请不要对此进行命令。谢谢。

1 个答案:

答案 0 :(得分:0)

感谢@AshSharma启发我解决问题所在。问题是,在完整接收全部数据之前,我正在执行拆分。解决方法如下:

def showNewData():
    global newData
    global receivedChar

    if newData == True:
        data = receivedChar.split(",")
        print(data)
        newData = False

#No need for def Process_Recv_Data() anymore

这是一个愚蠢的错误。 *人脸