2. Serial TTL
In this post, you will see how the TTL Serial protocol works, and you will go in-depth in how to configure this communication protocol in the most optimal way.
However, because it doesn't use differential signaling like RS-485 or RS-232, it should not be used in noisy environments or over large distances, due to faster signal degradation compared to these signaling protocols.
There are mainly two ways to use the serial communication in the Raspberry PLC. The Unix approach and the library approach:
Following the "Everything is a file" Unix approach, you can configure the "/dev/ttyS0" file (which represents the Raspberry serial port) with the stty command to be able to write and read the serial port like a normal file in the SD filesystem.
"/dev/ttyS0" is a pseudoterminal endpoint , which establishes an asynchronous, bidirectional communication between your read/write process and the serial port driver. In order to be able to communicate with the serial port, you need to configure things like baud rate, parity or event if the pseudoterminal has to interpret some of the characters received (like '\n', which indicates "newline").
stty -F /dev/ttyS0 raw speed 115200 -echo
This command sets raw mode (so it doesn't interpret received bytes), it sets baud rate to 115200 baud and disables echoing (re-writes in your screen the bytes you sent with the Raspberry). Once this command is successfully executed, commands like "cat" or "echo" will read and write respectively at the serial port. Also, programs can then interact with the serial port like it is a normal file. For instance, take this Python program:
with open("/dev/ttyS0", "rb") as f:
byte_s = f.read(1) # Read one byte at a time
if byte_s: print(byte_s)
This program will print all the characters available in the serial port's buffer until it's closed.
The Unix approach is very easy to setup and it doesn't need any extra dependencies. But, if you have to make multi-platform code, or you need the I/O tasks to be asynchronously handled, you will prefer libraries that can do all this work for you. Luckily, most programming languages have at least one (synchronous) library for serial port handling. For example, in Python you have pyserial, a module that encapsulates the serial port access across multiple operative systems.
If you want, you can check this code for Python that reads data from the serial port with the pyserial library:
port = "/dev/ttyACM0"
baudrate = 9600
serial_port = serial.Serial(port=port,baudrate=baudrate, bytesize=8, stopbits=1)
n = serial_port.read(1)
except KeyboardInterrupt: break;