user3481947
user3481947

Reputation: 25

Serial communication sending/receiving data between Arduino and Python

I've connected both Arduino and Raspberry Pi vis USB serial communication. On Raspeberry Side, Python code has to read three ultrasonic sensors using below attached code. Thus, depending to sensors information Python will send command via a string e.g. M, 2000, 1500 to drive the two wheels of a robot. The problem is each time I run python code, it loses some digits or comma, for example if Arduino sends 200, 122, 60 (left, centre, right) distance, on python side I receive some times same data but most the time there is a missing number or even the comma and thus the split function shows error because instead of having three sensors if I lose the comma in reading then it will be just like two sensors.

import serial
import time
import string
DEVICE = '/dev/ttyACM0'
BAUD = 9600
ser= serial.Serial(DEVICE, BAUD)
while (1==1):
    Sensors_Data=ser.readline()
    print Sensors_Data
    (left_distance, centre_distance, right_distance)=[int(s) for s in  Sensors_Data.split(',')]
    print left_distance
    print centre_distance
    print right_distance
    if (centre_distance<50):
        ser.write('M%4d' %1500)
        ser.write('M%4d' %1500)
    else:
        ser.write('M%4d' %1600)
        ser.write('M%4d' %1500)

Upvotes: 1

Views: 1376

Answers (1)

Sahil M
Sahil M

Reputation: 1847

First let's make sure you don't have extraneous characters like newlines and carriage returns.

import serial
import time
import string
DEVICE = '/dev/ttyACM0'
BAUD = 9600
ser= serial.Serial(DEVICE, BAUD)
while (1==1):
    Sensors_Data=ser.readline().encode('string-escape')
    print Sensors_Data # This should show you what all is there.
    Sensors_Data = Sensors_Data.split('\r\n')[0] # Assuming you have a carriage return and a newline, which is typical.
    (left_distance, centre_distance, right_distance)=[int(s) for s in  Sensors_Data.split(',')]
    print left_distance
    print centre_distance
    print right_distance
    if (centre_distance<50):
        ser.write('M%4d' %1500)
        ser.write('M%4d' %1500)
    else:
        ser.write('M%4d' %1600)
        ser.write('M%4d' %1500)

Upvotes: 1

Related Questions