I'm trying to get my Arduino to send my Raspberry Pi some ultrasonic information via a serial connection via the USB cable. I am close but my RPi is reading the input from the Arduino clipped inconsistently. If the Arduino is sending 36 (ie 36 inches) the RPi will sometimes read it as 36 but other times the RPi may read 3 or 6 or even 363. When I have the serial monitor run I notice that each line ends with "\r\n" and I think this may have my answer but I cannot crack this one. By the way I am using Python 2.7.3 to program on my RPi.
Here is the Arduino code:
const int pingPin = 2;
long duration, distanceInches, distanceCm;
void setup()
{
Serial.begin(9600);
}
void loop()
{
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delay(2);
digitalWrite(pingPin, HIGH);
delay(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
distanceInches = microsecondsToInches(duration);
distanceCm = microsecondsToCentimeters(duration);
Serial.print(distanceInches);
Serial.println();
delay(100);
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}
and here is the code on the Raspberry Pi:
from Tkinter import*
import serial
import time
import sys
chip = '/dev/ttyACM0'
baud = 9600
root = Tk()
def read():
ser = serial.Serial(chip, baud)
x = ser.readline()
y = int(x)
if y < 14 :
print 'Less than 14 Inches'
else :
print 'More than 14 Inches'
def key_imput (event):
key_press = event.char
if key_press.lower() == 'a':
read()
Button(text="Read", command=read).pack()
root.bind('<KeyPress>', key_imput)
root.mainloop()
Thank you,
Robb
\r\n
is a DOS style line ending (literally, "carriage return, newline"). Some network protocols use that instead of just\n
.