Serial communication lets a Raspberry Pi talk to other devices by sending data one bit at a time. This helps connect sensors, screens, or other gadgets easily.
Why serial communication connects to external devices in Raspberry Pi
import serial ser = serial.Serial('/dev/ttyS0', 9600) ser.write(b'Hello') data = ser.read(5) ser.close()
Use the correct device name for your serial port (like '/dev/ttyS0' or '/dev/serial0').
Set the baud rate (speed) to match the device you connect to.
import serial ser = serial.Serial('/dev/serial0', 115200) ser.write(b'Hi') response = ser.read(2) ser.close()
import serial with serial.Serial('/dev/ttyUSB0', 9600, timeout=1) as ser: ser.write(b'Ping') reply = ser.readline() print(reply)
This program sends 'Hello device!' to an external device connected via serial. It waits a bit, reads a line back, and prints it. Finally, it closes the connection.
import serial import time # Open serial port ser = serial.Serial('/dev/serial0', 9600, timeout=1) # Send a message ser.write(b'Hello device!\n') # Wait a moment time.sleep(1) # Read response response = ser.readline().decode('utf-8').strip() print(f'Received: {response}') # Close port ser.close()
Always match baud rate and settings on both devices to communicate properly.
Use timeouts to avoid waiting forever if no data comes back.
Serial ports on Raspberry Pi may need enabling in settings before use.
Serial communication sends data bit by bit to connect Raspberry Pi with other devices.
It is useful for sensors, controllers, and other gadgets that need simple data exchange.
Correct setup of port and speed is key for successful communication.
