Index
1. Introduction
2. Serial TTL
3. Configuration
Introduction
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.
Serial TTL
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.
Configuration
There are mainly two ways to use the serial communication in the Raspberry PLC. The Unix approach and the library approach:
Unix 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").
For example:
    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:
    while 1:
        byte_s = f.read(1) # Read one byte at a time
        if byte_s: print(byte_s)
        else: break;
This program will print all the characters available in the serial port's buffer until it's closed.
Library approach:
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:
import serial
port = "/dev/ttyACM0"
baudrate = 9600
serial_port = serial.Serial(port=port,baudrate=baudrate, bytesize=8, stopbits=1)
while 1:
    try:
        n = serial_port.read(1)
        print(n)
    except KeyboardInterrupt: break;
serial_port.close()
How to configure the TTL Serial Port on Industrial Raspberry PLC