Steun onze actie WeGoSTEM

Voor onze actie WeGoSTEM zoeken we nog vrijwilligers. Doe mee via WeGoSTEM.be/meedoen

Programming a Knight Rider LED light scanner

In this tutorial we extend the blinking LEDs tutorial to create a Knight Rider light scanner. Several concepts of C++ programming language are applied in this tutorial.


Requirements

  1. One Dwenguino board
  2. Enclosed USB cable

A Knight Rider

Start by making a new Arduino sketch and including the following libraries or take a look at the built-in Knight Rider example (Arduino IDE > File > Examples > Dwenguino):

  1. #include <LiquidCrystal.h>
  2. #include <Wire.h>
  3. #include <Dwenguino.h>

Start the code by initialising the pins in the setup function. This part of the code is only called once during the startup of the Dwenguino board:

  1. void setup() {
  2. // put your setup code here, to run once:
  3. initDwenguino();
  4. LEDS = 0b00000001;
  5. }

Call the function initDwengo() to setup the pins for the LEDs as digital outputs. This function also initialises other functionalities of the board such as the LCD display which is not used in this tutorial.

Next, initialise the LEDS variable to 0b00000001. This will turn on the LD0 on the Dwenguino board.

Afterwards, write the main program loop. This loop contains the actual logic of the program and runs repeatedly (unless you power off or reset the Dwenguino):

  1. void loop() {
  2. for (unsigned char i=0; i<7; i++) {
  3. LEDS <<= 1; // Rotate to the right
  4. delay(50);
  5. }
  6. for (unsigned char i=0; i<7; i++) {
  7. LEDS >>= 1; // Rotate to the left
  8. delay(50);
  9. }
  10. }

In this loop first declare the variable i which is used as a loop counter. Choose an unsigned char as data type for this variable. This is the smallest variable type in our microcontroller. It can store all numbers between 0 and 255. In this example i only counts from 0 up to 7, so this is more than sufficient.

The main loop contains two for loops. The code in each of these loops is executed 7 times — from i=0 up to i=6 — before continuing to the next loop. In the first loop the content of LEDs is shifted by one bit a time to the left by using the binary shift operator: <<. In the free spot, which was created on the right of the bit array, a 0 is inserted. This operation corresponds to multiplying by 2 in mathematics. Next, use the function delay(50) to wait for 50 milliseconds before shifting another bit to the left.

In the second loop, do the opposite of the first loop: every iteration the content of LEDs is shifted by 1 bit to the right. This corresponds with a division by 2. On the board this translates to the LEDs lighting up from right to left (from LD7 to LD0).

Because the two for loops are repeated one after another, it looks as if the LEDs are moving from one side to the other: just like the real Knight Rider shown in the movie.