Translation missing: en.general.accessibility.skip_to_content

Lightino Lesson 2: Let's make hearts!

In the last lesson we used code to decide which LEDs to turn on or off to make a pattern. But what if we want to make it show a pattern such as a heart? If we draw the pattern out on squared paper we can take vertical slices, see which LEDs are to be lit for each slice, and tell the Arduino to light them in turn.

Here's the pattern I drew but you can change it if you think you can draw one you like better, or you could do a smiley face or anything else you like. It worked best for me with 7 columns plus a blank one to turn the LEDs off.

LED position table

The simplest way to do this is to code each column as a binary number, a 1 representing a LED on and a 0 for a LED off. (In C we write binary numbers starting "0b", so 3 in binary would be "0b11".)

So the first column will be 0b00011110, and the second will be 0b00100001. (We count the bits in a binary number from right to left, starting at zero, so bit 0, representing LED1, is 0 in the first column and 1 in the second.) Check you can see how I got that.

We store these binary numbers in an array called heart, which is simply a list of values. We declare it as having 8 elements and pre-set them like this:

int heart[8] = { 0b00011110, 0b00100001, … }

(We can put this before setup() after the other definitions, because we don't want it redefined every time loop() gets called.)

We can then refer to the first element as heart[0], the second as heart[1] and so on.

There's a function bitRead which extracts bit n (counting from zero at the right hand end) from a binary number. So bitRead(heart[0]) is 0, and bitRead(heart[1]) is 1.

Now HIGH and LOW as we usually write in digitalWrite are actually the same as 1 and 0, so we can directly use bitRead in a digitalWrite!

We're now ready to write our code. Let's display 3 hearts in red, green and blue. Here is the pseudocode:

For each colour:

Switch on the colour (cathode)
For each column 0 - 7:

For each row 0 - 7:

Turn the LED on or off according to the bit (row)
of the array element (column)

Wait a bit

Take the previous example (Pattern1), save it as Pattern2 and replace the code in loop() with your own. Now see if you can write the code.

Continue to Lesson 3 by clicking here!

If you're stuck try reading the Help Sheet!

Previous article Comparing the BBC Micro:Bit V1 and V2, what is different?