Bird
0
0
Raspberry Piprogramming~5 mins

Why serial communication connects to external devices in Raspberry Pi

Choose your learning style9 modes available
Introduction

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.

When you want to read data from a sensor like temperature or distance.
When you need to send commands to a motor controller or robot.
When connecting to a GPS module to get location data.
When you want to communicate with another microcontroller or computer.
When debugging or sending simple messages between devices.
Syntax
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.

Examples
This example opens the serial port at 115200 baud, sends 'Hi', reads 2 bytes back, then closes the connection.
Raspberry Pi
import serial

ser = serial.Serial('/dev/serial0', 115200)
ser.write(b'Hi')
response = ser.read(2)
ser.close()
This uses a USB serial adapter, sends 'Ping', reads a line response, and prints it.
Raspberry Pi
import serial

with serial.Serial('/dev/ttyUSB0', 9600, timeout=1) as ser:
    ser.write(b'Ping')
    reply = ser.readline()
    print(reply)
Sample Program

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.

Raspberry Pi
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()
OutputSuccess
Important Notes

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.

Summary

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.