串行连接损坏的数据

时间:2016-12-03 19:30:32

标签: python arduino pyserial teensy

我正在尝试使用串行连接在Raspberry Pi和Teensy之间发送数据。

青少年代码:

void setup() {
  Serial1.begin(9600);
}

void loop() {
  Serial1.println("HELLO");
  delay(1000);
}

Raspberry Pi的Python代码:

import serial
import sys
import string

ser = serial.Serial('/dev/ttyAMA0', 9600)
while True :
    try:
        data=ser.readline()
        print(data)
    except:
        print("Unexpected error: {}".format(sys.exc_info()))
        sys.exit()

结果:

enter image description here

为什么数据似乎已损坏?奇偶校验位不应该阻止它?

3 个答案:

答案 0 :(得分:0)

尝试在ser.flushInput()创建后插入ser.flushOutput()ser

答案 1 :(得分:0)

我正在尝试在笔记本电脑上运行的Arduino和Python 3之间进行通信。 Arduino应该可以接收0x30(即ASCII 0)并以ASCII "Arduino reachable."进行回复(请参阅最后的代码)。 Python代码非常简单:

import serial, time

ports=['/dev/ttyACM0']
fixture = serial.Serial(port=ports[0],baudrate=9600,timeout=2,stopbits=sm.serial.STOPBITS_ONE,parity=sm.serial.PARITY_EVEN,bytesize=sm.serial.EIGHTBITS)

fixture.write(b'0')
time.sleep(0.1)
if (fixture.inWaiting() > 0):
    dataStr = port.read(fixture.inWaiting())
    print(dataStr)

fixture.close()

Arduino在答复,但答复没有多大意义:'A.V¥n\x0b\x92\x95a,+\x89lY©'。最后,我将parity更改为serial.PARITY_NONE,那就像梦一样。

另外,我建议使用以下等待数据出现的方法:

TIMEOUT = 20
timeoutCounter=0

while fixture.inWaiting() <= 0: # Wait for data to appear.
    time.sleep(0.1)
    timeoutCounter += 1
    if timeoutCounter == TIMEOUT:
        fixture.close()
        raise BaseException('Getting test data from the Arduino timed out.')

相关的Arduino代码

void setup()
{
    Serial.begin(9600);
}

void loop()
{
    char cmdChar = '0'; // Which test case to execute. 0 - do nothing.
    // Wait until there is something in the serial port to read.
    if (Serial.available() > 0)
    {
        // Read the incoming serial data.
        cmdChar = Serial.read();
        // Eexecute the chosen test case.
        switch(cmdChar)
        {
            case '0':
                Serial.print("Arduino reachable."); // Send ASCII characters.
                break;
        }
    }
}

注意

很抱歉,但是我不得不在发布之前编辑此代码,并且没有机会对其进行重新测试。但是,针对问题中报告的错误的主要解决方案仍然有效:

  1. 奇偶校验错误(也可能是停止位)
  2. 没有足够的时间等待数据出现(可能不是问题的原因,但绝对是不正确的做法)。

答案 2 :(得分:0)

我在使用之前遇到了这个问题。为什么不只使用/ dev / ttyUSB0?我现在正在使用它,没有问题。

相关问题