Simulating traffic lights with Raspberry Pi and Windows 10 IoT Core

Most of beginner examples for Raspberry Pi introduce how to turn on and off LED lamp. I wrote a little bit more complex starting example but it has some touch from real life – my example simulates traffic lights. I’m IoT noobie but using Microsoft tools it was actually easy to build this little example. This blog post is short introduction about what I did.

Getting started

To get started we need some electronic parts (I expect you already have Raspberry Pi with Windows 10 IoT Core installed):

  • 3 LED lamps (green, orange, red),
  • 3 resistors,
  • jumper wires.

Source code for more advanced version of traffic lights simulator is available in my GitHub reposiotry
WindowsIotTrafficLights
.

NB! What resistors you need depends on what LED lamps you buy. Ask from electronics store appropriate ones if you are noobie like me.They need to know that you are using 3.3V power supply.

On wiring side things are actually so simple that even I was able to get it right with first shot.

Connecting traffic lights to Raspberry Pi

After wiring is done it’s time to write some code.

Writing UWP application

There are two options for UWP applications – blank UWP application and Background Application (IoT). What do you prefer depends on what do you want to do next. If you just want to try out things then blank UWP application is good starting point as you can later build UI for your application.

Here I’m using blank UWP application. After creating the project add reference to Windows IoT Extensions for the UWP. Open code-behind file of MainPage.xaml and add there the following code.

public sealed partial class MainPage : Page
{
    private IList<GpioPin> _pins = new List<GpioPin>();

    public MainPage()
    {
        InitializeComponent();

        Loaded += MainPage_Loaded;
    }

    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        Init();         foreach (var pin in _pins)
        {
            pin.Write(GpioPinValue.High);
        }         Task.Delay(10000).Wait();         Stop();
    }     private void Init()
    {
        var gpio = GpioController.GetDefault();

        if (gpio == null)
        {
            Debug.WriteLine("GPIO controller is missing!");
            return;
        }

        _pins.Add(gpio.OpenPin(17));
        _pins.Add(gpio.OpenPin(18));
        _pins.Add(gpio.OpenPin(27));

        foreach (var pin in _pins)
        {
            pin.Write(GpioPinValue.Low);
            pin.SetDriveMode(GpioPinDriveMode.Output);
        }
    }     private void Stop()
    {
        foreach (var pin in _pins)
        {
            pin.Write(GpioPinValue.Low);
        }
    } }

The code here is just for test that wiring went well and everything works. Init() method initializes GPIO pins and adds them to list. Stop() method turns off all LED-s. Foreach loop in MainPage_Loaded turns all LED-s on for ten seconds. If you we run the code and all LED-s show light for ten seconds then everything is okay.

The cryptic constants 17, 18 and 27 are actually GPIO pin numbers. Here is the reference image from Raspberry Pi 2 & 3 Pin Mappings page by Microsoft.

Raspberry Pi 2 and 3 GPIO pin mappings

If there are problems wiring things together then make sure you followed all the guidance accurately.

Simulating traffic lights

Let’s focus now on primitive code to mimic traffic lights. I’m using separate method for traffic lights cycle so I can add later another methods to blink the LED lights. Play() method runs ten traffic lights cycle.

public sealed partial class MainPage : Page
{
    private IList<GpioPin> _pins = new List<GpioPin>();

    public MainPage()
    {
        InitializeComponent();

        Loaded += MainPage_Loaded;
    }

    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        Init();
        Play();
        Stop();
    }

    private void Play()
    {
        for(var i = 0; i < 10; i++)
        {
            TrafficLights();
        }
    }

    private void TrafficLights()
    {
        var red = _pins[0];
        var yellow = _pins[1];
        var green = _pins[2];          // Start with red and process to green
        red.Write(GpioPinValue.High);
        Sleep(5000);
        yellow.Write(GpioPinValue.High);
        Sleep(2000);
        Stop();
        green.Write(GpioPinValue.High);
        Sleep(5000);          // Blink green and switch to yellow
        green.Write(GpioPinValue.Low);
        Sleep(500);
        green.Write(GpioPinValue.High);
        Sleep(500);
        green.Write(GpioPinValue.Low);
        Sleep(500);
        green.Write(GpioPinValue.High);
        Sleep(500);
        green.Write(GpioPinValue.Low);
        Sleep(500);
        yellow.Write(GpioPinValue.High);
        Sleep(2000);         Stop();
    }

    private void Sleep(int milliseconds)
    {
        Task.Delay(milliseconds).Wait();
    }

    private void Init()
    {
        var gpio = GpioController.GetDefault();

        if (gpio == null)
        {
            Debug.WriteLine("GPIO controller is missing!");
            return;
        }

        _pins.Add(gpio.OpenPin(17));
        _pins.Add(gpio.OpenPin(18));
        _pins.Add(gpio.OpenPin(27));

        foreach (var pin in _pins)
        {
            pin.Write(GpioPinValue.Low);
            pin.SetDriveMode(GpioPinDriveMode.Output);
        }
    }

    private void Stop()
    {
        foreach(var pin in _pins)
        {
            pin.Write(GpioPinValue.Low);
        }
    }
}

This is how it looks in real life.

Almost like real, isn’t it?

Wrapping up

Using Windows 10 IoT Core and Visual Studio it is easy to control LED lights connected to Raspberry Pi. Also connecting everything together on electronics side was very simple. Although the code here is primitive and noobish it still works and is easy enough to our simple solution. Of course, when looking at code above I detected one repeating pattern that helps to generalize this solution. It will be the topic of my next posting about Raspberry Pi and LED lamps.

Liked this post? Empower your friends by sharing it!

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    4 thoughts on “Simulating traffic lights with Raspberry Pi and Windows 10 IoT Core

    • Pingback:The Morning Brew - Chris Alcock » The Morning Brew #2575

    • May 1, 2018 at 9:25 pm
      Permalink

      You’ve provided some fantastic coding for simulating traffic lights with Raspberry Pi. I love challenging myself with fun coding projects, and hopefully I’ll be able to upgrade my system soon, so I can take on simultaneous projects. As soon as I diagnose and fix my slow internet, I am going to be having a blast with this coding. I don’t mind the noobish coding, because it provides so much room to play around with it.

    • April 6, 2019 at 2:08 am
      Permalink

      is possible get into real traffic monitoring ?

    • April 6, 2019 at 9:05 am
      Permalink

      Real traffic control is more complex thing to do but you can start with my soution in some safe neighborhood :)

    Leave a Reply

    Your email address will not be published. Required fields are marked *