I do this all the time. Two-way communications works just fine.
Yes I keep my ports open continuously. UNLESS I am running the IDE. The IDE requires that I not have any other programs trying to use the same serial port.
The code I use on the Arduino to open the port is much more simple than you're showing.
Serial.begin(9600);
while (Serial.available()>0) serIn=Serial.read();
to open it then flush the buffer using a char
variable.
Test it out in the serial monitor from your IDE to make sure the Arduino is working correctly before moving on to the Python program on the Raspberry Pi.
Note that the serial monitor will always send an end-of-line \n
- so to read single-character commands the best way is like so.
if (Serial.available()>0) {
serIn=Serial.read()
if (SerIn=='A') {
...do something...
}
while (Serial.available()>0) serIn=Serial.read();
}
On the Raspberry Pi in python, talking to a Nano, here is the Python code to open the port:
import serial
ser = serial.Serial("/dev/ttyUSB0",9600)
ser.flushInput()
Very simple.
Nano mounted on a breadboard so there is room for voltage dividers and such, then linked to the Rpi3 by the programming cable to send the readings to the Raspberry Pi and to receive instructions to toggle digital outputs which can switch relays.
(I always use single-character instructions. Arduino char 'X' means to shut off the inverter, for instance.)
Python code to process input from the serial port:
while True :
linein = ser.readline()
...etc - to process input from the Arduino.
Python code to write a single character out the serial port:
ser.write("A")
This sends the single character "A", which is received on the Arduino as a char
'A' in the read
loop shown above.
In Python you use double-quotes to denote a character for writing. ser.write
does not add an end-of-line.
If you are using an Uno the open sequence will instead be this because they tend to use a different port in Jessie.
import serial
ser = serial.Serial("/dev/ttyACM0",9600)
ser.flushInput()
You can see which ports are there with this bash command :
#ls /dev/tty*
No magic involved. Just very straightforward and simple.
There's only one gotcha: If you are running your Arduino IDE on the Raspberry Pi then you need to make sure you don't interfere with the serial port during program uploading to the Arduino.
This is important but not much of an issue once you have it tuned up and don't use the IDE as often.
My systems run 24x7 for days on end. I rarely need to change the programs now that they are stable. You can see some of the output generated by these systems here: https://www.sdsolarblog.com/montage
if (Serial.available() > 0)
line. If you remove that block, does the problem go away?