I already asked a question regarding communication between a Arduino and RPi through a USB serial connection and was able to solve major issues. Now my RPi and Arduino are talking to each other and getting along swimmingly... well almost.
I am using the following code for a simple task that could be almost completed without a Raspberry Pi (or without the Arduino). I have a ultrasonic sensor and a led hooked up to the Arduino and I am feeding the results to the RPi. The RPi is taking the results of the ultrasonic sensor and depending on the distance telling the Arduino to turn on the led. I am currently using the RPi as a way to start the process.
I have a raw input with the RPi "To start the ultrasonic sensor, please type "Start":". This works but after the two start communicating there is approximately a five second delay from when an object is close enough to light the led and when the led actually turns on. I would like to eventually use this on a robot and need a quicker reaction time.
Here is the Arduino Code:
int led = 10;
const int pingPin = 2;
long duration, distanceInches, distanceCm;
void setup()
{
pinMode(led, OUTPUT);
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(200);
char ch = Serial.read();
if (ch == 'a') digitalWrite(led, HIGH);
else if (ch == 's') digitalWrite(led, LOW);
delay(10);
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}
Here is the code for the Raspberry Pi in Python 2.7:
import serial
import time
import sys
chip = '/dev/ttyACM0'
baud = 9600
ser = serial.Serial(chip, baud)
ser.flush()
def run():
while True:
x = ser.readline()
y = int(x)
if y < 14 :
ser.write('a')
else :
ser.write('s')
time.sleep(0.010)
def start():
while True:
on = raw_input('To start the ultrasonic sensor, please type "Start": ')
if on == "Start":
run()
else :
print('Invalid command. Please try again')
start()
Thanks in advance for any help and let me know if you need any clarification.
Robb