pythonserializationarduinopyserialraspberry-pi-zero

Python Serial Writing but seemingly not reading. Raspberry Pi 0 to Arduino


I'm having trouble with a python script running on an RPI0 reading serial input from an Arduino. I know the Arduino's code is correct as everything works as intended interacting with the Arduino over the built in serial monitor in the Arduino software(send code a10(code to drive a relay HIGH), Arduino sends back 11(basically asking for how long), send code b5, Arduino will hold pin HIGH for 5 seconds(b5)).

However when I attempt to read any serial input in python using the pyserial module, nothing happens. I know it does successfully send the code to the arduino as it will hold the pin HIGH for the specified seconds when I rewrite the python script with ser.write("a10b5").

The serial connection is NOT USB. I'm using jumper wires with a voltage shifter in between them using the Arduino's and Pi's GPIO TX and RX pins.

Here is the code:

import time
import serial

ser = serial.Serial(
        port='/dev/ttyAMA0',
        baudrate = 9600,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS,
        timeout=None
)


print("sending data over serial now")
ser.write("a10") #a10 is relay HIGH code

while True:
        x = ser.read()
        if  x == 11:    ##arduino code 11(asking for how long)
                print("recieved code 11")
                print("arduino recieved relay HIGH code and is waiting for time to hold relay for")
                print("sending time now")
                ser.write('a5') # 5 seconds
                time.sleep(1)
        if x == 13:     #arduino code 13(water success)
                print("recieved code 13")
                print("arduino reports watering complete")
        x = 0    ##this is to clear the variable every loop. Not sure if it's needed

And here is a simple serial reader I've pulled from online. Opening it up in a second terminal and running it at the same time with my own script it will actually read the codes from the arduino business as usual.

#!/usr/bin/env python
import time
import serial
ser = serial.Serial(
 port='/dev/ttyAMA0',
 baudrate = 57600,
parity=serial.PARITY_NONE,
 stopbits=serial.STOPBITS_ONE,
 bytesize=serial.EIGHTBITS,
 timeout=1
)
while True:
 x=ser.readline()
 print x

What gives?


Solution

  • Answering my own question. In the arduino code I used

    Serial.println(whatevergoeshere)
    

    instead of

    Serial.print(whatevergoeshere)
    

    So the arduino was sending out '\n' at the end of every serial line that was not being printed by either the arduino serial console and the python script. Updating my IF statements in python to

    if x == "11\n":
    

    Solves the issue and everything works as intended.