Programming a Knight Rider LED light scanner
In this tutorial we extend the blinking LEDs to create a Knight Rider light scanner. Several concepts of the programming language C are applied in this tutorial. The project also provides the opportunity to review the concepts of the previous tutorial.
Requirements
- One Dwengo board
- One Dwengo programmer
- Enclosed USB cable
A Knight Rider
We start the program by adding the required libraries:
#include <dwengoConfig.h> #include <dwengoBoard.h> #include <dwengoDelay.h>
The dwengoConfig.h and the dwengoBoard.h header files contain the base functionality and settings for the Dwengo board. The dwengoDelay.h header provides the necessary functions to let the program wait for a certain time.
Next we write the main program loop. This loop contains the actual logic of the program:
void main(void) { unsigned char i; initBoard(); LEDS = 0b00000001; while (TRUE) { for (i=0; i<7; i++) { LEDS <<= 1; // Rotate to the right delay_ms(50); } for (i=0; i<7; i++) { LEDS >>= 1; // Rotate to the left delay_ms(50); } } }
The main loop of the program is immediately recognisable. In this loop we first declare the variable i which is used as a loop counter. We choose an unsigned char as data type for this variable. This is the smallest variable type in our processor. It can store all numbers between 0 and 255. In this example i only counts from 0 up to 6, so this is more than enough.
Next we call the function *initBoard() to setup the pins for the LEDs as digital outputs. This functions also initializes other functionality of the board such as the LCD display which is now not needed.
Next we initialise the LEDS variable to 0b00000001. This will turn on the LED0 on the Dwengo board.
Afterwards the while(TRUE) construct creates an infinite loop. The code in this loop will be repeated over and over again until the power of the board is turned off.
The infinite loop contains two for loops. The code in each of these loops is executed 7 times — from i=0 up to i=6 — before we jump to the next loop. In the first loop the contents of LEDS is shifted to the left by one bit by using the binary shift operator: <<. In the free spot that was created on the right of the bit array, a 0 is inserted. In mathematics this operation corresponds to multiplying by 2. Next we use the function delay_ms(50) to wait for 50 ms before we shift another bit to the left.
In the second loop we do the opposite from the first loop: every iteration we shift the contents of LEDS 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 LED7 to LED0).
Because the two for loops are repeated one after another, it seems that the LEDs are moving from one way to the other: just like a real Knight Rider as shown in the movie.

Your shopping cart