본문 바로가기

라즈베리파이 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()

 

 

 

반응형

캐어랩 고객 지원

취업, 창업의 막막함, 외주 관리, 제품 부재!

당신의 고민은 무엇입니까? 현실과 동떨어진 교육, 실패만 반복하는 외주 계약, 아이디어는 있지만 구현할 기술이 없는 막막함.

우리는 알고 있습니다. 문제의 원인은 '명확한 학습, 실전 경험과 신뢰할 수 있는 기술력의 부재'에서 시작됩니다.

이제 고민을 멈추고, 캐어랩을 만나세요!

코딩(펌웨어), 전자부품과 디지털 회로설계, PCB 설계 제작, 고객(시장/수출) 발굴과 마케팅 전략으로 당신을 지원합니다.

제품 설계의 고수는 성공이 만든 게 아니라 실패가 만듭니다. 아이디어를 양산 가능한 제품으로!

귀사의 제품을 만드세요. 교육과 개발 실적으로 신뢰할 수 있는 파트너를 확보하세요.

지난 30년 여정, 캐어랩이 얻은 모든 것을 함께 나누고 싶습니다.

카카오 채널 추가하기

카톡 채팅방에서 무엇이든 물어보세요

귀사가 성공하기까지의 긴 고난의 시간을 캐어랩과 함께 하세요.

캐어랩 온라인 채널 바로가기

캐어랩