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.

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.

    5 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 :)

    • April 15, 2025 at 12:46 am
      Permalink

      In our opinion, the most effective Ukrainian dating site is the one that has plenty of single girls, an sufficient design and choice of features, and a spotless observe record and reputation. The popularity of online dating in Ukraine has drastically increased, so consumer penetration in this sphere has already reached 11.6% and is expected to hit 15.6% by 2027. No surprise trusted Ukraine dating sites have such an enormous number of Ukrainian ladies searching for the attention of Western males. Ukraine has experienced rapid social change in recent many years, with shifting dating and marriage customs that blend conventional Eastern European values with modern Western influences. Ask questions about their culture, traditions, and values. Ukrainian girls adore giant, boisterous weddings crammed with outdated traditions, attendees, and distant family members your bride has by no means met. While understanding cultural norms, traditions, and societal adjustments are vital, it’s crucial to recollect that each particular person is unique and will not match these generalizations perfectly. Dating a Ukrainian is usually a deeply enriching expertise that broadens your perspective and helps you develop as an individual. Family approval was valued above individual romantic preferences. Traditional Ukrainian culture places a powerful emphasis on family.

      In this article, we’ll discover the numbers of Ukrainian girls living in the USA, the explanations behind their migration, and shed mild on their lives in a new country. After i visited Ukraine a number of years in the past, I met loads of Ukrainian men in bed and i had some quite memorable and romantic moments in that lovely nation. The Lucky Date is a quick-growing Ukraine dating site known for its matchmaking system that pairs you with compatible profiles primarily based on your preferences. I registered at this courting site myself, and was simply checking it, ukrainian no plan to pursue a relationship, better one woman contacted me, and at the moment she is my wife. International dating is here to remain, and one of the niche markets is for Ukrainian brides on courting apps. Ukrainian women are rightfully happy with their culture and history and need to share it with you. Engage in conversations about these differences, ask questions, and most significantly, be respectful of your associate’s tradition and traditions.

      Most significantly, enjoy the journey. Indeed, whether or not you might be navigating the complexities of long-distance love or planning a life together in a new nation, the journey of dating a Ukrainian may be full of both challenges and unforgettable moments of joy. Embrace the journey with an open mind, and also you would possibly find that the challenges are indeed the pathways to essentially the most rewarding experiences. On this ebook, I describe my experiences dating Ukrainian women in Ukraine. Each of the Ukraine single ladies dating on-line may be very inventive. Ukraine is known for having some of one of the best ladies to marry, and whereas that is broadly recognized, many don’t know which cities are hotspots for meeting these superb ladies. To ensure your relationship with them works, it might help to know a thing or two in regards to the cons of dating one. Now let’s look at the features, professionals, and cons of every site in more detail. What ought to charmdate scam I consider before signing up for a Ukrainian dating site? Our experts analyzed hundreds of Ukrainian dating websites critiques and tested virtually each common Ukrainian dating site. Finally, courting a Ukrainian boils down to 1 essential element: authenticity. Their blessing and approval are thought-about important before a pair advances to engagement and marriage.

      Moreover, they’re sometimes respectful, caring, and understanding, that are important qualities for an extended-lasting and fulfilling marriage. Whether you are navigating cultural variations, planning a future together, or just attending to know each other, effective communication can improve understanding, foster intimacy, and prevent misunderstandings. Attributable to the fact that you simply did not have time to get to know one another for actual. And Ukrainian males have a repute for exhausting drinking and womanizing. Drinking is a giant subject in Ukraine, and women search for males who have that problem underneath management or don’t drink in any respect. So don’t rush, construct a relationship with a Ukrainian lady little by little. Keep these insights in thoughts, strategy your relationship with understanding and respect, and you will find that relationship a Ukrainian could be an unforgettable experience filled with love, joy, and private growth. Our crew has extensive expertise in this subject. Digital courting with Ukrainian girls provides more than just a chance for romantic connections; it gives a possibility for cultural alternate and mutual learning.

    Leave a Reply

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