Hi
I'm really learning a lot reading the forum and I found many solutions to my problems, however I'm not able to find an answer to my latest problem. I would like to exchange data between raspberry pi and arduino so I have connected raspberry pi with arduino over serial RX/TX (UART) like this Easy Arduino - Raspberry Pi serial over GPIO - Raspberry Pi Forums and this is the code I use.
Arduino code:
#include <stdlib.h>
byte num = 0;
void setup ()
{
Serial.begin (9600);
}
void loop ()
{
if ( Serial.available() > 0 )
{
num = Serial.read ();
Serial.print( "RX: " );
Serial.write(num);
Serial.write(" ");
Serial.println(num);
}
delay(500);
}
rPi Python code:
#!/usr/bin/python
# code from
# http://shallowsky.com/blog/2011/Oct/16/
import serial
import time
import select
import sys
serialport = serial.Serial("/dev/ttyAMA0", 9600, timeout=0.5)
while True:
# Check whether the user has typed anything (timeout of .2 sec):
inp, outp, err = select.select([sys.stdin, serialport], [], [], .2)
# If the user has typed anything, send it to the Arduino:
if sys.stdin in inp :
line = sys.stdin.readline()
serialport.write(line)
# If the Arduino has printed anything, display it:
if serialport in inp :
line = serialport.readline().strip()
print "Arduino:", line
I connect all the wires, open serial monitor, run python script and all seems fine. Python waits for input, arduino is waiting for data on serial, but the moment I enter some character in python, arduino starts an endless loop of displaying its own printed characters.
// edited 10. mar 2013
In this example I entered "a" in python script and arduino returns "RX: a 97" but then it also thinks that string "RX: a 97" was sent to him over serial.
// end of edit
a
Arduino: RX: a 97
Arduino: RX: R 82
Arduino: RX: X 88
Arduino: RX: : 58
Arduino: RX: 32
Arduino: RX: a 97
Arduino: RX: 32
Arduino: RX: 9 57
Arduino: RX: 7 55
....
I know that Serial.print adds bytes to serial buffer, so i tried to clear the buffer at the end of the loop like this
delay(20);
while (Serial.read() != -1);
delay(500);
With this code it works almost as intended, but sometimes characters are not registered, I guess they get deleted when clearing the buffer. Maybe optimizing delays?
So I was wondering what would be the right/best way to receive data on arduino (only one character for example) and send a response over serial without having an effect on buffer or lost characters? Maybe disabling RX when transmitting over TX and vice-versa?
Thank you
