라즈베리 파이 코드 구조
Hardware Preparation
1 | × | Raspberry Pi 4 Model B | Amazon | |
1 | × | (추천) Screw Terminal Block Shield for Raspberry Pi | 쿠팡 | Amazon | |
1 | × | (추천) USB-C Power Cable with On/Off Switch for Raspberry Pi 4B | Amazon | |
1 | × | (추천) Plastic Case and Cooling Fan for Raspberry Pi 4B | Amazon | |
1 | × | (추천) HDMI Touch Screen Monitor for Raspberry Pi | Amazon |
공개: 이 섹션에서 제공된 링크 중 일부는 제휴 링크입니다. 이 링크를 통해 구매한 경우 추가 비용없이 수수료를 받을 수 있습니다. 지원해 주셔서 감사합니다.
기본 구조
라즈베리 파이 코드는 다음과 같은 부분들로 구성됩니다:
- 필요한 라이브러리 가져오기
- 초기화 및 설정
- 메인 루프: 무한히 반복 실행됨
- 예외 처리 (선택 사항)
- 프로그램 종료
두 개의 코드 스켈레톤이 있습니다:
- 코드 스켈레톤 #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
- 코드 스켈레톤 #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
라즈베리 파이 예제 코드
다음은 LED를 깜박이게 하는 예제 코드를 제공합니다.
- 스켈레톤 #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
- 스켈레톤 #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()