Simple Traffic Lights using Python and Arduino


I am using The Most Complete Starter Kit UN0 R3 Project which is produced by Elegoo and contains and Arduino

Create your circuit

Each power supply is a pin on the Arduino

I have attached red to digital pin 9 on the Arduino, yellow to digital pin 10 and green to digital pin 11.

Create a circuit containing a 10Kohm resistor and 3 leds.

Download the Arduino IDE

Download the Arduino IDE from https://www.arduino.cc/en/Main/Software

Upload Firmata onto the Arduino

  • Open the Arduino IDE
  • Select File -> Examples -> Firmata -> StandardFirmata
  • Click the Green arrow to upload the code

Install Firmata1 Python Module

  • Open PyCharm
  • Open terminal inside PyCharm
pip3 install pyfirmata 
  • Pycharm -> Preferences -> Project: nnn -> Project Interpreter
  • click +
  • search for Pyfirmata1
  • click Install Package

Write the Code

from time import sleep
from pyfirmata2 import Arduino
board = Arduino(Arduino.AUTODETECT)
red = board.digital[9]
yellow = board.digital[10]
green = board.digital[11]
leds = red, yellow, green
def off():
    [led.write(0) for led in leds]
def on(*colors, time=0):
    off()
    [color.write(1) for color in colors]
    sleep(time)
on(red, time=3)
on(red, yellow, time=1.5)
on(green, time=3)
on(yellow, time=1.5)
on(red, time=3)
off()
board.exit()

Run your code

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s