Bird
0
0
Raspberry Piprogramming~5 mins

Enabling serial on Raspberry Pi

Choose your learning style9 modes available
Introduction

Enabling serial on Raspberry Pi lets you communicate with other devices using serial ports. This is useful for sending and receiving data through simple wires.

Connecting Raspberry Pi to a GPS module to get location data.
Communicating with a microcontroller like Arduino using serial messages.
Debugging Raspberry Pi by sending system messages over serial.
Controlling robots or sensors that use serial communication.
Setting up a console to access Raspberry Pi without a monitor.
Syntax
Raspberry Pi
sudo raspi-config
# Navigate to Interface Options > Serial Port
# Disable login shell over serial
# Enable serial hardware
# Finish and reboot

Use sudo raspi-config to open the Raspberry Pi configuration tool.

Disabling the login shell on serial frees the port for your own use.

Examples
This example shows the basic steps to enable serial hardware and disable the login shell, then reboot to apply changes.
Raspberry Pi
sudo raspi-config
# Enable serial hardware
# Disable serial login shell
sudo reboot
You can also enable UART by editing /boot/config.txt and adding enable_uart=1.
Raspberry Pi
sudo nano /boot/config.txt
# Add or ensure: enable_uart=1
sudo reboot
Sample Program

This Python program opens the serial port on Raspberry Pi, sends a message, waits for a response, and prints it. It assumes serial is enabled and connected to a device.

Raspberry Pi
#!/usr/bin/env python3
import serial
import time

# Open serial port
ser = serial.Serial('/dev/serial0', 9600, timeout=1)

# Send a message
ser.write(b'Hello from Raspberry Pi!\n')

# Wait and read response
time.sleep(1)
response = ser.readline().decode('utf-8').strip()
print(f'Received: {response}')

ser.close()
OutputSuccess
Important Notes

Make sure to disable the serial console login to use the serial port for your own data.

Use /dev/serial0 as the serial device for Raspberry Pi's primary UART.

Reboot is required after changing serial settings for them to take effect.

Summary

Enabling serial on Raspberry Pi allows communication with other devices using UART.

Use raspi-config to enable serial hardware and disable serial login shell.

After enabling, you can send and receive data through /dev/serial0 in your programs.