2

I'm trying to send data between Raspberry Pi and Teensy with serial connection.

Code for teensy :

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

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

Python code for Raspberry Pi :

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()

Result :

enter image description here

Why data seem to be corrupted? The parity bit is not supposed to prevent that?

Aurélien
  • 259
  • 4
  • 12

3 Answers3

0

Try to insert ser.flushInput() and ser.flushOutput() after ser creation.

0

I was trying to communicate between an Arduino and Python 3 running on my laptop. The Arduino was supposed to receive 0x30, i.e. an ASCII 0 and reply with ASCII "Arduino reachable." (see the code at the end). The Python code was as simple as it gets:

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()

The Arduino was replying, but the reply didn't make much sense: 'A.V¥n\x0b\x92\x95a,+\x89lY©'. In the end, I've changed parity to serial.PARITY_NONE and that worked like a dream.

Also, I suggest the following method of waiting for the data to appear:

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.')

Related Arduino code

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;
        }
    }
}

Caveat

I'm sorry but I've had to edit this code before posting, and haven't had a chance to re-test it. However, the main solutions to errors like reported in the questions still hold:

  1. Wrong parity (probably stop bits also),
  2. Insufficient waiting for the data to appear (possibly not the cause of the problem but definitely a bad practice).
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Aleksander Lidtke
  • 2,876
  • 4
  • 29
  • 41
0

I encounter this before when I use. Why don't just use /dev/ttyUSB0? I am using it now it now and have no issue.