.. note::
Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.
**Why Join?**
- **Expert Support**: Solve post-sale issues and technical challenges with help from our community and team.
- **Learn & Share**: Exchange tips and tutorials to enhance your skills.
- **Exclusive Previews**: Get early access to new product announcements and sneak peeks.
- **Special Discounts**: Enjoy exclusive discounts on our newest products.
- **Festive Promotions and Giveaways**: Take part in giveaways and holiday promotions.
👉 Ready to explore and create with us? Click [|link_sf_facebook|] and join today!
.. _4.1.12_py:
4.1.12 Traffic Light
========================
Introduction
---------------
In this project, we will use LED lights of three colors to realize the
change of traffic lights and a four-digit 7-segment display will be used
to display the timing of each traffic state.
Required Components
------------------------------
In this project, we need the following components.
.. image:: ../img/list_Traffic_Light.png
:align: center
It's definitely convenient to buy a whole kit, here's the link:
.. list-table::
:widths: 20 20 20
:header-rows: 1
* - Name
- ITEMS IN THIS KIT
- LINK
* - Raphael Kit
- 337
- |link_Raphael_kit|
You can also buy them separately from the links below.
.. list-table::
:widths: 30 20
:header-rows: 1
* - COMPONENT INTRODUCTION
- PURCHASE LINK
* - :ref:`cpn_gpio_board`
- |link_gpio_board_buy|
* - :ref:`cpn_breadboard`
- |link_breadboard_buy|
* - :ref:`cpn_wires`
- |link_wires_buy|
* - :ref:`cpn_resistor`
- |link_resistor_buy|
* - :ref:`cpn_led`
- |link_led_buy|
* - :ref:`cpn_4_digit`
- \-
* - :ref:`cpn_74hc595`
- |link_74hc595_buy|
Schematic Diagram
--------------------
============ ======== ======== ===
T-Board Name physical wiringPi BCM
GPIO17 Pin 11 0 17
GPIO27 Pin 13 2 27
GPIO22 Pin 15 3 22
SPIMOSI Pin 19 12 10
GPIO18 Pin 12 1 18
GPIO23 Pin 16 4 23
GPIO24 Pin 18 5 24
GPIO25 Pin 22 6 25
SPICE0 Pin 24 10 8
SPICE1 Pin 26 11 7
============ ======== ======== ===
.. image:: ../img/Schematic_three_one7.png
:align: center
Experimental Procedures
------------------------
**Step 1:** Build the circuit.
.. image:: ../img/image254.png
**Step 2:** Change directory.
.. raw:: html
.. code-block::
cd ~/raphael-kit/python/
**Step 3:** Run.
.. raw:: html
.. code-block::
sudo python3 4.1.12_TrafficLight.py
As the code runs, LEDs will simulate the color changing of traffic
lights. Firstly, the red LED lights up for 60s, then the green LED
lights up for 30s; next, the yellow LED lights up for 5s. After that,
the red LED lights up for 60s once again. In this way, this series of
actions will be executed repeatedly. Meanwhile, the 4-digit 7-segment
display displays the countdown time continuously.
Code
----------
.. note::
You can **Modify/Reset/Copy/Run/Stop** the code below. But before that, you need to go to source code path like ``raphael-kit/python``. After modifying the code, you can run it directly to see the effect.
.. raw:: html
.. code-block:: python
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
import threading
#define the pins connect to 74HC595
SDI = 24 #serial data input(DS)
RCLK = 23 #memory clock input(STCP)
SRCLK = 18 #shift register clock input(SHCP)
number = (0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90)
placePin = (10,22,27,17)
ledPin =(25,8,7)
greenLight = 30
yellowLight = 5
redLight = 60
lightColor=("Red","Green","Yellow")
colorState=0
counter = 60
timer1 = 0
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(SDI, GPIO.OUT)
GPIO.setup(RCLK, GPIO.OUT)
GPIO.setup(SRCLK, GPIO.OUT)
for pin in placePin:
GPIO.setup(pin,GPIO.OUT)
for pin in ledPin:
GPIO.setup(pin,GPIO.OUT)
global timer1
timer1 = threading.Timer(1.0,timer)
timer1.start()
def clearDisplay():
for i in range(8):
GPIO.output(SDI, 1)
GPIO.output(SRCLK, GPIO.HIGH)
GPIO.output(SRCLK, GPIO.LOW)
GPIO.output(RCLK, GPIO.HIGH)
GPIO.output(RCLK, GPIO.LOW)
def hc595_shift(data):
for i in range(8):
GPIO.output(SDI, 0x80 & (data << i))
GPIO.output(SRCLK, GPIO.HIGH)
GPIO.output(SRCLK, GPIO.LOW)
GPIO.output(RCLK, GPIO.HIGH)
GPIO.output(RCLK, GPIO.LOW)
def pickDigit(digit):
for i in placePin:
GPIO.output(i,GPIO.LOW)
GPIO.output(placePin[digit], GPIO.HIGH)
def timer(): #timer function
global counter
global colorState
global timer1
timer1 = threading.Timer(1.0,timer)
timer1.start()
counter-=1
if (counter is 0):
if(colorState is 0):
counter= greenLight
if(colorState is 1):
counter=yellowLight
if (colorState is 2):
counter=redLight
colorState=(colorState+1)%3
print ("counter : %d color: %s "%(counter,lightColor[colorState]))
def lightup():
global colorState
for i in range(0,3):
GPIO.output(ledPin[i], GPIO.HIGH)
GPIO.output(ledPin[colorState], GPIO.LOW)
def display():
global counter
a = counter % 10000//1000 + counter % 1000//100
b = counter % 10000//1000 + counter % 1000//100 + counter % 100//10
c = counter % 10000//1000 + counter % 1000//100 + counter % 100//10 + counter % 10
if (counter % 10000//1000 == 0):
clearDisplay()
else:
clearDisplay()
pickDigit(3)
hc595_shift(number[counter % 10000//1000])
if (a == 0):
clearDisplay()
else:
clearDisplay()
pickDigit(2)
hc595_shift(number[counter % 1000//100])
if (b == 0):
clearDisplay()
else:
clearDisplay()
pickDigit(1)
hc595_shift(number[counter % 100//10])
if(c == 0):
clearDisplay()
else:
clearDisplay()
pickDigit(0)
hc595_shift(number[counter % 10])
def loop():
while True:
display()
lightup()
def destroy(): # When "Ctrl+C" is pressed, the function is executed.
global timer1
GPIO.cleanup()
timer1.cancel() #cancel the timer
if __name__ == '__main__': # Program starting from here
setup()
try:
loop()
except KeyboardInterrupt:
destroy()
Code Explanation
--------------------
.. code-block:: python
SDI = 24 #serial data input(DS)
RCLK = 23 #memory clock input(STCP)
SRCLK = 18 #shift register clock input(SHCP)
number = (0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90)
placePin = (10,22,27,17)
def clearDisplay():
def hc595_shift(data):
def pickDigit(digit):
def display():
These codes are used to realize the function of number display of
4-Digit 7-Segment. Refer to chapter 1.1.5 of the document for more
details. Here, we use the codes to display countdown of traffic light
time.
.. code-block:: python
ledPin =(25,8,7)
colorState=0
def lightup():
global colorState
for i in range(0,3):
GPIO.output(ledPin[i], GPIO.HIGH)
GPIO.output(ledPin[colorState], GPIO.LOW)
The codes are used to switch the LED on and off.
.. code-block:: python
greenLight = 30
yellowLight = 5
redLight = 60
lightColor=("Red","Green","Yellow")
colorState=0
counter = 60
timer1 = 0
def timer(): #timer function
global counter
global colorState
global timer1
timer1 = threading.Timer(1.0,timer)
timer1.start()
counter-=1
if (counter is 0):
if(colorState is 0):
counter= greenLight
if(colorState is 1):
counter=yellowLight
if (colorState is 2):
counter=redLight
colorState=(colorState+1)%3
print ("counter : %d color: %s "%(counter,lightColor[colorState]))
The codes are used to switch the timer on and off. Refer to chapter
1.1.5 for more details. Here, when the timer returns to zero, colorState
will be switched so as to switch LED, and the timer will be assigned to
a new value.
.. code-block:: python
def setup():
# ...
global timer1
timer1 = threading.Timer(1.0,timer)
timer1.start()
def loop():
while True:
display()
lightup()
def destroy(): # When "Ctrl+C" is pressed, the function is executed.
global timer1
GPIO.cleanup()
timer1.cancel() #cancel the timer
if __name__ == '__main__': # Program starting from here
setup()
try:
loop()
except KeyboardInterrupt:
destroy()
In ``setup()`` function, start the timer. In ``loop()`` function, a **while
True** is used: call the relative functions of 4-Digit 7-Segment and LED
circularly.
Phenomenon Picture
-------------------
.. image:: ../img/IMG_8319.jpg
:align: center