Raspberry Pi offers a wide variety of built-in modules that simplify programming and interacting with hardware components. These modules enable you to control GPIO pins, handle files and perform networking tasks, all while writing Python code.
What Are Built-in Modules?
Built-in modules are libraries and tools that come pre-installed with the Raspberry Pi OS. These modules are written in Python and can be imported directly into your Python scripts without needing to install anything extra. They help you perform various tasks like interacting with sensors, controlling hardware, and managing the file system.
Key Built-in Modules for Raspberry Pi
1. RPi.GPIO (General Purpose Input/Output)
The RPi.GPIO module is one of the most commonly used built-in modules for controlling the Raspberry Pi’s GPIO pins. It allows you to interact with external hardware, such as LEDs, buttons, motors, and sensors.
- Setup: You can configure pins as either input or output.
- Control: Use the module to turn devices on or off, read sensor data and create PWM signals.
Example: Controlling an LED with RPi.GPIO
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM) # Use Broadcom pin numbering
GPIO.setup(17, GPIO.OUT) # Set GPIO17 as output
# Blink LED
for _ in range(10):
GPIO.output(17, GPIO.HIGH) # Turn on LED
time.sleep(1)
GPIO.output(17, GPIO.LOW) # Turn off LED
time.sleep(1)
GPIO.cleanup() # Reset GPIO pins
2. time (Time-related Functions)
The time module provides various time-related functions, such as pausing the execution of your program, measuring execution time, and handling time intervals. It’s especially useful for projects where you need delays or timers.
- sleep(): Used to pause the execution for a specified number of seconds.
- time(): Returns the current time in seconds since the epoch.
Example: Using time.sleep() to pause execution
import time
print("Start")
time.sleep(3) # Pause for 3 seconds
print("End")
3. os (Operating System Interface)
The os module allows you to interact with the operating system in various ways. You can create or delete files, work with directories, and execute system commands from within your Python script.
- os.listdir(): Lists files in a directory.
- os.system(): Executes system commands.
- os.mkdir(): Creates a new directory.
Example: Working with files and directories
import os
# List files in the current directory
files = os.listdir(".")
print("Files in current directory:", files)
# Create a new directory
os.mkdir("new_folder")
4. socket (Networking)
The socket module provides access to network functionality, allowing you to set up a server and client for communication between devices. It is commonly used for creating networked applications, such as web servers and real-time messaging systems.
- socket.socket(): Creates a new socket object.
- bind(): Binds the server to a particular address and port.
- connect(): Connects the client to a server.
Example: Simple server and client using sockets
Server Code (server.py):
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("localhost", 12345)) # Bind to address and port
server_socket.listen(1)
print("Waiting for client connection...")
client_socket, client_address = server_socket.accept()
print(f"Client connected from {client_address}")
client_socket.send(b"Hello from Raspberry Pi server!")
client_socket.close()
Client Code (client.py):
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 12345))
response = client_socket.recv(1024) # Receive data from server
print(f"Received from server: {response.decode()}")
client_socket.close()
5. sys (System-specific Parameters and Functions)
The sys module provides access to some variables used or maintained by the interpreter and functions that interact with the Python runtime environment. It is useful for working with command-line arguments, handling exceptions, and managing Python paths.
- sys.argv: Lists command-line arguments.
- sys.exit(): Exits the program with a status code.
Example: Using sys.argv to get command-line arguments
import sys
if len(sys.argv) > 1:
print(f"Command-line argument received: {sys.argv[1]}")
else:
print("No command-line arguments provided.")
6. platform (Platform Information)
The platform module allows you to gather information about the system you are running your Python script on. You can use it to detect the operating system, version, and machine architecture, which is useful for cross-platform development.
- platform.system(): Returns the name of the operating system.
- platform.release(): Returns the OS version.
- platform.machine(): Returns the machine type.
Example: Checking the system platform
import platform
print("Operating System:", platform.system())
print("OS Release:", platform.release())
print("Machine Architecture:", platform.machine())
Real-World Applications
- Home Automation: Use the RPi.GPIO module to control lights, fans, or other appliances based on sensor data.
- Networking Projects: The socket module allows you to set up servers for real-time communication, such as live chat systems or remote control apps.
- System Monitoring: Use the os and sys modules to monitor system resources, manage files or automate system tasks on your Raspberry Pi.