Raspberry Pi Cấu Trúc Code
Phần cứng cần chuẩn bị
| 1 | × | Raspberry Pi 5 | ||
| 1 | × | (Khuyến nghị) Screw Terminal Block Shield for Raspberry Pi | ||
| 1 | × | (Khuyến nghị) Raspberry Pi Prototyping Base Plate & Breadboard Kit | ||
| 1 | × | (Khuyến nghị) HDMI Touch Screen Monitor for Raspberry Pi |
Or you can buy the following kits:
| 1 | × | DIYables Sensor Kit (30 sensors/displays) | ||
| 1 | × | DIYables Sensor Kit (18 sensors/displays) |
Cấu Trúc Cơ Bản
Code Raspberry Pi bao gồm các phần sau:
- Import các thư viện cần thiết
- Khởi tạo và thiết lập
- Vòng lặp chính: được thực thi lặp đi lặp lại, vô hạn
- Xử lý ngoại lệ (tùy chọn)
- Thoát chương trình
Có hai mẫu code cơ bản:
- Mẫu Code #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
- Mẫu Code #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
Phần dưới đây cung cấp code ví dụ để nhấp nháy LED
- Example Code cho Mẫu #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 cho Mẫu #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()