Featured Video Play Icon


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


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

#include <LiquidCrystal.h>
#include <Wire.h>
#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:

void setup() {
  // put your setup code here, to run once:
  LEDS = 0b00000001;

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

void loop() {
  for (unsigned char i=0; i<7; i++) {
    LEDS <<= 1;  // Rotate to the right
  for (unsigned char i=0; i<7; i++) {
    LEDS >>= 1;  // Rotate to the left

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.

Related Post