-
Book Overview & Buying
-
Table Of Contents
Creative DIY Microcontroller Projects with TinyGo and WebAssembly
By :
We know how to light up a single LED, and we also know how to light up an LED using a button input. The next step is to build a circuit using three LEDs and to write the code to light them up in the correct order.
To build the circuit, we need the following components:
We start by first setting up the components using the following steps:
Your circuit should now look similar to the following figure:
Figure 2.6 – The traffic lights circuit – image taken from Fritzing
We have now successfully set up the circuit. Now we can continue to write some code to control the LEDs.
We start off by creating a new folder named traffic-lights-simple inside the Chapter02 folder. Also, we create a main.go file inside the new folder and start off with an empty main function. Your project structure should now look like this:
Figure 2.7 - Folder structure for the circuit
We have successfully set up our project structure to continue. We are going to implement the following flow:
RED -> RED-YELLOW -> GREEN -> YELLOW -> RED
This is a typical flow for traffic lights with three bulbs.
We are going to configure three pins as output, and afterward, we want to endlessly loop and light up the LEDs in this flow.
Inside the main function, we write the following:
outputConfig as PinConfig using the PinOutPut mode:outputConfig := machine.PinConfig{Mode: machine.
PinOutput}redLED with the value machine.D13 and configure it as output:redLED := machine.D13 redLED.Configure(outputConfig)
yellowLED with the value machine.D12 and configure it as output:yellowLED := machine.D12 yellowLED.Configure(outputConfig)
greenLED with the value machine.D11 and configure it as output:greenLED := machine.D11 greenLED.Configure(outputConfig)
We have now initialized our variables to act as output pins. The next step is to light up the LEDs in the correct order. We basically have four phases, which just need to repeat in order to simulate a real traffic light. Let's go through these one by one:
for {redLED.High() time.Sleep(time.Second)
yellowLED.High() time.Sleep(time.Second)
redLED.Low() yellowLED.Low() greenLED.High() time.Sleep(time.Second)
greenLED.Low() yellowLED.High() time.Sleep(time.Second) yellowLED.Low() }
The complete content of the function is available at the following URL:
Note
Don't forget to import the time and machine packages.
We have now assembled and programmed a complete traffic lights flow. The next step is to combine everything we have built to complete our project.