You can check whether the serial port connections are working correctly using a
serial loopback.
A simple loopback consists of connecting RXD and TXD together. These are pins 8 and 10 on the Raspberry Pi GPIO header, or pins 2 and 3 on the standard RS232 D9 connector on the USB-RS232 adapter:
An RS232 full loopback cable also connects pin 4 (DTR) and pin 6 (DSR) as well as pin 7 (RTS) and pin 8 (CTS) on the RS232 adapter. However, this is not required for most situations, unless these signals are used. By default, no pins are allocated on Raspberry Pi specifically for these additional signals:
Create the following serialTest.py script:
#!/usr/bin/python3 #serialTest.py import serial import time WAITTIME=1 serName="/dev/ttyAMA0" ser = serial.Serial(serName) print (ser.name) print (ser) if ser.isOpen(): try: print("For Serial Loopback - connect GPIO Pin8 and Pin10") print("[Type Message and Press Enter to continue]") print("#:") command=input() ser.write(bytearray(command+"rn","ascii")) time.sleep(WAITTIME) out="" while ser.inWaiting() > 0: out += bytes.decode(ser.read(1)) if out != "": print (">>" + out) else: print ("No data Received") except KeyboardInterrupt: ser.close() #End
When a loopback is connected, you will observe that the message is echoed back to the screen (when removed, No data Received will be displayed):
If we require non-default settings, they can be defined when the serial port is initialized (the pySerial documentation at https://pyserial.readthedocs.io/en/latest/ provides full details of all the options), as shown in the following code:
ser = serial.Serial(port=serName, baudrate= 115200, timeout=1, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_TWO, bytesize=serial.SEVENBITS)