본문 바로가기

라즈베리파이 5

라즈베리파이 python 7 - 교통 신호등

반응형

 

라즈베리파이 파이선 7 – 교통 신호등 Traffic Light

 

이번 튜토리얼에서는 Raspberry Pi를 사용하여 신호등 모듈을 제어하는 ​​방법을 알아 보겠습니다. 

  • 신호등 모듈을 Raspberry Pi에 연결하는 방법
  • RGB 신호등 모듈을 제어하도록 Raspberry Pi를 프로그래밍하는 방법
  • delay() 기능을 사용하지 않고 RGB 신호등 모듈을 제어하도록 Raspberry Pi를 프로그래밍하는 방법 

 

강의 순서

 

라즈베리파이 Python 9 - 버튼 채터링 방지

라즈베리파이 Python 8 - 버튼

라즈베리파이 python 7 - 교통 신호등

라즈베리파이 python 6 - RGB LED

라즈베리파이 Python 5 - LED Fade 구현

라즈베리파이 Python 4 - Delay 없는 LED Blink

라즈베리파이 Python 3 - LED Blink

라즈베리파이 Python 2 - 파이선 코드 템플릿

라즈베리파이 Python 1 - python 실행

 

 

 

교통 신호등 모듈

 

https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-traffic-light

 

 

연결도

 

 

 

 

 

1번 코드

 

"""
This Raspberry Pi code was developed by newbiely.com
This Raspberry Pi code is made available for public use without any restriction
For comprehensive instructions and wiring diagrams, please visit:
https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-traffic-light
"""


import RPi.GPIO as GPIO
import time

# Define GPIO pins
PIN_RED = 7     # The Raspberry Pi GPIO pin connected to the R pin of the traffic light module
PIN_YELLOW = 8  # The Raspberry Pi GPIO pin connected to the Y pin of the traffic light module
PIN_GREEN = 25  # The Raspberry Pi GPIO pin connected to the G pin of the traffic light module

# Define time durations
RED_TIME = 4     # RED time in seconds
YELLOW_TIME = 4  # YELLOW time in seconds
GREEN_TIME = 4   # GREEN time in seconds

# Set up GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN_RED, GPIO.OUT)
GPIO.setup(PIN_YELLOW, GPIO.OUT)
GPIO.setup(PIN_GREEN, GPIO.OUT)

try:
    while True:
        # Red light on
        GPIO.output(PIN_RED, GPIO.HIGH)
        GPIO.output(PIN_YELLOW, GPIO.LOW)
        GPIO.output(PIN_GREEN, GPIO.LOW)
        time.sleep(RED_TIME)

        # Yellow light on
        GPIO.output(PIN_RED, GPIO.LOW)
        GPIO.output(PIN_YELLOW, GPIO.HIGH)
        GPIO.output(PIN_GREEN, GPIO.LOW)
        time.sleep(YELLOW_TIME)

        # Green light on
        GPIO.output(PIN_RED, GPIO.LOW)
        GPIO.output(PIN_YELLOW, GPIO.LOW)
        GPIO.output(PIN_GREEN, GPIO.HIGH)
        time.sleep(GREEN_TIME)

except KeyboardInterrupt:
    # Clean up GPIO on exit
    GPIO.cleanup()

 

파일을 저장하고 터미널에서 다음 명령을 실행하여 Python 스크립트를 실행합니다.

 

python3 traffic_light.py

 

스크립트는 터미널에서 Ctrl + C를 누를 때까지 무한 루프로 계속 실행됩니다. - 신호등 모듈을 확인해보세요.

 

신호등의 정확한 작동은 다양한 지역과 교차로에서 사용되는 특정 디자인과 기술에 따라 달라질 수 있다는 점에 유의하는 것이 중요합니다. 위에서 설명한 원리는 신호등이 어떻게 작동하는지에 대한 일반적인 이해를 제공합니다. 교통을 관리하고 도로 안전을 강화하기 위해 운영됩니다. 위의 코드는 개별 조명 제어를 보여줍니다. 이제 더 나은 최적화를 위해 코드를 향상해 보겠습니다. 

 

라이트를 제어하는 동작을 함수로 만들어 코드를 개선합니다.

 

"""
This Raspberry Pi code was developed by newbiely.com
This Raspberry Pi code is made available for public use without any restriction
For comprehensive instructions and wiring diagrams, please visit:
https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-traffic-light
"""


import RPi.GPIO as GPIO
import time

# Define GPIO pins
PIN_RED = 7     # The Raspberry Pi GPIO pin connected to the R pin of the traffic light module
PIN_YELLOW = 8  # The Raspberry Pi GPIO pin connected to the Y pin of the traffic light module
PIN_GREEN = 25  # The Raspberry Pi GPIO pin connected to the G pin of the traffic light module

# Define time durations in seconds
RED_TIME = 2     # RED time in seconds
YELLOW_TIME = 1  # YELLOW time in seconds
GREEN_TIME = 2   # GREEN time in seconds

# Define indices for the light states
RED = 0
YELLOW = 1
GREEN = 2

# Create lists for pins and times
pins = [PIN_RED, PIN_YELLOW, PIN_GREEN]
times = [RED_TIME, YELLOW_TIME, GREEN_TIME]

# Set up GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN_RED, GPIO.OUT)
GPIO.setup(PIN_YELLOW, GPIO.OUT)
GPIO.setup(PIN_GREEN, GPIO.OUT)

def traffic_light_on(light):
    for i in range(len(pins)):
        if i == light:
            GPIO.output(pins[i], GPIO.HIGH)  # turn on
        else:
            GPIO.output(pins[i], GPIO.LOW)  # turn off

try:
    while True:
        # Red light on
        traffic_light_on(RED)
        time.sleep(times[RED])  # keep red light on during a period of time

        # Yellow light on
        traffic_light_on(YELLOW)
        time.sleep(times[YELLOW])  # keep yellow light on during a period of time

        # Green light on
        traffic_light_on(GREEN)
        time.sleep(times[GREEN])  # keep green light on during a period of time

except KeyboardInterrupt:
    # Clean up GPIO on exit
    GPIO.cleanup()

 

 

for 반복문을 사용하여 코드를 개선합니다.

 

 

"""
This Raspberry Pi code was developed by newbiely.com
This Raspberry Pi code is made available for public use without any restriction
For comprehensive instructions and wiring diagrams, please visit:
https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-traffic-light
"""


import RPi.GPIO as GPIO
import time

# Define GPIO pins
PIN_RED = 7     # The Raspberry Pi GPIO pin connected to the R pin of the traffic light module
PIN_YELLOW = 8  # The Raspberry Pi GPIO pin connected to the Y pin of the traffic light module
PIN_GREEN = 25  # The Raspberry Pi GPIO pin connected to the G pin of the traffic light module

# Define time durations in seconds
RED_TIME = 2     # RED time in seconds
YELLOW_TIME = 1  # YELLOW time in seconds
GREEN_TIME = 2   # GREEN time in seconds

# Define indices for the light states
RED = 0
YELLOW = 1
GREEN = 2

# Create lists for pins and times
pins = [PIN_RED, PIN_YELLOW, PIN_GREEN]
times = [RED_TIME, YELLOW_TIME, GREEN_TIME]

# Set up GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN_RED, GPIO.OUT)
GPIO.setup(PIN_YELLOW, GPIO.OUT)
GPIO.setup(PIN_GREEN, GPIO.OUT)

def traffic_light_on(light):
    for i in range(len(pins)):
        if i == light:
            GPIO.output(pins[i], GPIO.HIGH)  # turn on
        else:
            GPIO.output(pins[i], GPIO.LOW)   # turn off

try:
    while True:
        for light in range(RED, GREEN + 1):
            traffic_light_on(light)
            time.sleep(times[light])  # keep light on during a period of time

except KeyboardInterrupt:
    # Clean up GPIO on exit
    GPIO.cleanup()

 

 

delay() 를 사용하는 대신 millis() 함수를 사용하여 코드를 개선합니다.

 

"""
This Raspberry Pi code was developed by newbiely.com
This Raspberry Pi code is made available for public use without any restriction
For comprehensive instructions and wiring diagrams, please visit:
https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-traffic-light
"""


import RPi.GPIO as GPIO
import time

# Define GPIO pins
PIN_RED = 7     # The Raspberry Pi GPIO pin connected to the R pin of the traffic light module
PIN_YELLOW = 8  # The Raspberry Pi GPIO pin connected to the Y pin of the traffic light module
PIN_GREEN = 25  # The Raspberry Pi GPIO pin connected to the G pin of the traffic light module

# Define time durations in seconds
RED_TIME = 2     # RED time in seconds
YELLOW_TIME = 1  # YELLOW time in seconds
GREEN_TIME = 2   # GREEN time in seconds

# Define indices for the light states
RED = 0
YELLOW = 1
GREEN = 2

# Create lists for pins and times
pins = [PIN_RED, PIN_YELLOW, PIN_GREEN]
times = [RED_TIME, YELLOW_TIME, GREEN_TIME]

# Set up GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN_RED, GPIO.OUT)
GPIO.setup(PIN_YELLOW, GPIO.OUT)
GPIO.setup(PIN_GREEN, GPIO.OUT)

light = RED  # start with RED light
last_time = time.time()

def traffic_light_on(light):
    for i in range(len(pins)):
        if i == light:
            GPIO.output(pins[i], GPIO.HIGH)  # turn on
        else:
            GPIO.output(pins[i], GPIO.LOW)   # turn off

try:
    while True:
        if (time.time() - last_time) > times[light]:
            light += 1
            if light >= 3:
                light = RED  # new circle

            traffic_light_on(light)
            last_time = time.time()

        # TO DO: your other code

except KeyboardInterrupt:
    # Clean up GPIO on exit
    GPIO.cleanup()

 

 

 

반응형

더욱 좋은 정보를 제공하겠습니다.~ ^^