라즈베리 파이 코드 구조

준비물

1×라즈베리 파이 5 쿠팡 | 아마존
1×(추천) 라즈베리 파이용 스크루 터미널 블록 쉴드 쿠팡 | 아마존
1×(추천) 라즈베리 파이 프로토타이핑 베이스 플레이트 & 브레드보드 키트 아마존
1×(추천) 라즈베리 파이용 HDMI 터치 스크린 모니터 아마존
공개: 이 포스팅 에 제공된 일부 링크는 아마존 제휴 링크입니다. 이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

기본 구조

라즈베리 파이 코드는 다음과 같은 부분들로 구성됩니다:

  • 필요한 라이브러리 가져오기
  • 초기화 및 설정
  • 메인 루프: 무한히 반복 실행됨
  • 예외 처리 (선택 사항)
  • 프로그램 종료

두 개의 코드 스켈레톤이 있습니다:

  • 코드 스켈레톤 #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()