Raspberry Pi - Code Structure
Hardware Preparation
Or you can buy the following sensor kits:
1 | × | DIYables Sensor Kit (30 sensors/displays) | |
1 | × | DIYables Sensor Kit (18 sensors/displays) |
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables .
Additionally, some of these links are for products from our own brand, DIYables .
Basic Structure
The Raspberry Pi code consists of following parts:
- Import required libraries
- Initialization and setup
- Main loop: is executed repeatedly, infinitely
- Exception handling (optional)
- Program exit
The are two code skeletons:
- Code Skeleton #1
# Import Required Libraries
# Initialization and Setup
# Perform one-time setup tasks here
try:
# Main Loop
while True:
# Main code logic goes here
pass # Replace with your code
except KeyboardInterrupt:
# Handle Ctrl+C interruption
print("\nExiting the program.")
# Program Exit
# Add any cleanup tasks or final actions here
- Code Skeleton #2
# Import Required Libraries
# Initialization and Setup
# Perform one-time setup tasks here
try:
# Main Loop
while True:
# Main code logic goes here
pass # Replace with your code
except KeyboardInterrupt:
# Handle Ctrl+C interruption
print("\nExiting the program.")
finally:
# Program Exit
# Add any cleanup tasks or final actions here
Raspberry Pi Example Code
The below provides example codes that blink and LED
- Example Code for Skeleton #1
# IMPORT REQUIRED LIBRARIES
import RPi.GPIO as GPIO
import time
# INITIALIZATION AND SETUP
# Set the GPIO mode to BCM
GPIO.setmode(GPIO.BCM)
# Define the GPIO pin for the LED
LED_PIN = 17 # Use GPIO pin 17
# Set up the LED pin as an output
GPIO.setup(LED_PIN, GPIO.OUT)
try:
# MAIN LOOP
while True:
# Main code logic goes here
# Turn on the LED
GPIO.output(LED_PIN, GPIO.HIGH)
# Wait for a second
time.sleep(1)
# Turn off the LED
GPIO.output(LED_PIN, GPIO.LOW)
# Wait for a second
time.sleep(1)
except KeyboardInterrupt:
# Handle Ctrl+C interruption
print("\nExiting the program.")
GPIO.cleanup() # Clean up the GPIO
- Example Code for Skeleton #2
# IMPORT REQUIRED LIBRARIES
import RPi.GPIO as GPIO
import time
# INITIALIZATION AND SETUP
# Set the GPIO mode to BCM
GPIO.setmode(GPIO.BCM)
# Define the GPIO pin for the LED
LED_PIN = 17 # Use GPIO pin 17
# Set up the LED pin as an output
GPIO.setup(LED_PIN, GPIO.OUT)
try:
# MAIN LOOP
while True:
# Main code logic goes here
# Turn on the LED
GPIO.output(LED_PIN, GPIO.HIGH)
# Wait for a second
time.sleep(1)
# Turn off the LED
GPIO.output(LED_PIN, GPIO.LOW)
# Wait for a second
time.sleep(1)
except KeyboardInterrupt:
# Exception Handling (Optional)
# Handle Ctrl+C interruption
print("\nExiting the program.")
finally:
# Program Exit
# Cleanup GPIO on exit
GPIO.cleanup()