Professional Documents
Culture Documents
T276
Practical Engineering 1
Microcontrollers
Introduction 2
1 Getting to know the express 5
2 Using the microcontroller 31
3 Analysing the frequency spectrum 58
Introduction
Welcome to the first activity of the Practical Engineering component of
T276, which we will refer to as ‘PE1’. You will be using the Adafruit Circuit
Playground Express, shown below, which we will refer to it as the ‘Express’.
The Express is a single-board microcontroller, which means that on a single
circuit board you have a microprocessor, some memory and some sensors
and actuators. In other words, you have everything you need to sense the
world, reason about it, and then do something.
You are going to be using the microcontroller to collect data from sensors
and save that data in an Excel spreadsheet. In addition, you will look at how
the Express can create a PWM output which will be used in later Activities
to drive a motor.
You may have never written a computer program before or you may have
written a little bit, and, or you may be a professional software engineer
who writes programs for a living. But I am going to assume that you have
never written a program before. If you have, then you may be able to get
through this more quickly.
PE1 is split into three parts each involving separate tasks which will develop
your ability to program the Express using the MakeCode programming
environment. You will program the Express to respond to input signals and
produce output signals. You will also log data for analysis and then use
2
T276 PE1 Microcontrollers Introduction
Fourier analysis to gain insight into the data. The parts and tasks of PE1 are
summarised below:
Aims
After carrying out the tasks in PE1 you will be able to:
4
T276 PE1: Microcontrollers 1 Getting to know the express
Figure 1.1 The Express connected to my laptop with the USB cable
For those of you who like technical information, the USB cable is a male
USB-A at one end which connects to your computer through a standard USB
port, and male micro USB-B at the other end which connects to your
Express. Once the USB is connected to the Express it is quite hard to
physically disconnect. It can be done, but I suggest once you connected it
you leave it connected to the Express.
As I’ve already mentioned, don’t plug it into the computer yet!! Wait until I
tell you.
Figure 1.2 shows a picture of the Express indicating all the sensors, buttons,
and pins. The USB connector is at the top of the image, and that’s the best
5
T276 PE1: Microcontrollers 1 Getting to know the express
way to orientate the Express, so that if I say ‘the button on the right’ it
means, Button B, which is on the right when the Express is viewed this way.
▪ ten mini neopixels, each of which contains three light emitting diodes
or LEDs, coloured Red, Green and Blue, abbreviated to RGB. Each LED
can be set to 0 (minimum) or 255 (maximum). By combining the light
from these three LEDs, any colour can be produced by a neopixel. If all
three LEDs are on maximum, the light seen is white. If all three LEDs
are zero, the neopixel is off
▪ a single red LED labelled ‘D13’ which is used to indicate the status of
the Express. For example, when a program is being downloaded it
slowly flashes
▪ a light sensor which measures the intensity of the light that is shining
on the Express
6
T276 PE1: Microcontrollers 1 Getting to know the express
▪ two push button sensors labelled ‘A’ (left) and ‘B’ (right).
▪ a reset button that puts the Express into a state where it can receive a
downloaded program
There are also fourteen connection pads around the outside with labels like
A0, A1 etc. These can be connected to other devices using wires with
‘crocodile’ clips or screws. Of the fourteen pads, six are so-called power
pads, and are used to power the Express and connected sensors, and eight
are general purpose I/O pins (where I/O means input or output), which
either receive or output signals. The power pads, shown in Figure 1.3, are:
▪ GND: there are three Ground pads. They are all connected together,
and are all ground, earth or 0 V
▪ 3.3 V: there are two 3.3 Volt output pads. They are connected to the
output of the onboard regulator. (A regulator is an electronic device
that maintains a constant voltage.) The regulator can provide a
maximum current of about 500 mA
▪ VOUT: there is one Voltage Output pad. This is a special power pad; it will
be connected to either the USB power or the battery input, whichever
has the higher voltage. This output does not connect to the regulator,
so you can draw as much current as your USB port/battery can provide.
There is a resettable fuse on this pin, so you can draw about 500 mA of
continuous current, and 1 Amp peak before it will trip. If the fuse trips,
just wait a minute and it will automatically reset
The other pads are labelled A0 to A7, and are referred to as general
purpose I/O pins:
7
T276 PE1: Microcontrollers 1 Getting to know the express
▪ A0: This is a special pin that provides true analogue output so it's great
for playing audio clips. It can be digital I/O, or analogue I/O, but using it
in this way will interfere with the built-in speaker
▪ A1, A2 and A3: These pins can be digital I/O, or analogue input. They
have PWM output. PWM is described below
▪ A6 and A7: These pins can be digital I/O, or analogue input. They have
PWM output
There is a clear distinction here between input and output that is digital or
analogue, and output that is PWM. These indicate the different types of
signal discussed in the preparatory materials that are recognised by the
pins.
And, as we’ve already discussed, there is a USB connector. At the other end
is a battery connector, but you won’t be using that. There are some other
devices and features on the Express, but as we won’t be using them, I will
not say any more about them.
Now you can plug the Express into your computer using the USB cable.
What happens?
If the Express is still in its factory setting it should start flashing. This is
because the Express is running a program that was installed in the factory.
As soon as there is power in the Express it starts running. Try pressing the
buttons and sliding the slider to see how the Express responds.
The program is there to test if the neopixels are all working and if the
speaker is working. It doesn’t do anything else and gets quite annoying
after a while. You can always unplug it from your computer, and it will stop.
There is a possibility that your Express doesn’t do all of this. This doesn’t
necessarily mean that it is broken. It’s possible that you Express was used to
test the batch and the factory program has been replaced by some other
program that does something different. However, at the very least you
should see the little green LED showing that the Express has power.
8
T276 PE1: Microcontrollers 1 Getting to know the express
wave changes 48,000,000 times a second. When digital values are said to
be discrete and only change at regular intervals, those intervals are defined
by the clock.
The microcontroller chip on the express uses a 48 MHz clock and has 256
KB of flash memory. What these specifications show is that the clock speed,
48 Mega Hertz, is not particularly fast and the amount of memory that is
available, 256 Kilo Bytes, is quite small. Just for comparison, a laptop may
have a clock speed of 2.72 GHz (Giga Hertz), so 500 times faster, and 7.9 GB
(Giga bytes) of memory, about 30,000 times bigger! The flash memory on
the Express is more like a memory stick or USB stick, and when it is
connected to your computer via the USB drive, it appears as if it is a USB
memory stick, which is sometimes referred to as a flash drive.
To get the data you need from the Express, you are going to write programs
using a language called MakeCode. This is a graphical programming
language that uses blocks to build programs. A program is a set of
instructions that you want the microcontroller to carry out one after the
other.
The next complication is that after the program has been compiled into a
machine code program, it has to be put into a data file, and all data files
have a specific format. The format of a file is the way that the data is
9
T276 PE1: Microcontrollers 1 Getting to know the express
arranged in the file, usually with information about the file stored with it,
such as the amount of data in the file. For example, a Word document has a
particular format, and to indicate this, the file is called something like
‘name.doc’. The ‘.doc’ on the end indicates that it is the Word format.
The format that is used by the Express is called UF2, which stands for USB
flashing format. This means that any file in this format is saved as
something like ‘name.uf2’, where the ‘uf2’ shows that it is a UF2-formatted
file.
Finally, before you can download your program to the Express, the Express
has to be put into ‘Bootloader’ mode by pressing its reset button. This
mode is when the Express can appear on the computer as a flash drive, like
a USB stick. The ‘loader’ part of the description is probably fairly clear as
you are setting the Express up to download programs. The ‘Boot’ part might
seem a bit strange.
‘Booting’ your computer is a phrase you may have come across, usually
when you get a message saying that you have to ‘re-boot’ your computer.
This is a very old term used in computing which is short for ‘boot-strapping’
and refers to the phrase ‘picking yourself up by your own bootstraps’. Why?
As you know, computers run programs. Some of those programs, such as
Windows 10 or macOS are called operating systems. These operating
systems are the main programs that the computers run, which allow you to
then do whatever you want to do on the computer, such as load programs.
So, when a computer starts, the first program it has to load to get things
going is the operating system. But how can the computer load an operating
system if it needs an operating system to be able to load programs? This is
where the analogy to ‘picking yourself up by your own bootstraps’ comes
in. How it solves this problem is complicated and beyond the scope of this
brief introduction.
Now let’s take a look at MakeCode. At this point there is no need to install
any software to your computer as we are going to use a version of
MakeCode that is available as a web app on the Internet. It works with most
browsers so there shouldn’t be any issues. You can find the web app for
MakeCode at:
https://makecode.adafruit.com
You should see something like the screen shown in Figure 1.5.
10
T276 PE1: Microcontrollers 1 Getting to know the express
Once the web app has been started you will not need to be connected to
the Internet for MakeCode to work.
To get started, click on New Project, and after a moment you’ll see a screen
like the screen in Figure 1.6; this is known as the editor screen. From left to
right there are three distinct sections.
On the left is a graphical image of the Express. However, it’s more than
that. When you start writing programs, the Express on the left starts to
simulate them i.e. starts running the programs, so you can see what
happens. The Express simulation is interactive, so you can press buttons
and shake the Express with the mouse so that it can be made to respond to
interactions. This is very useful as it helps to see if the programs do what
you expect them to do before you download the program into the actual
Express, and it can save you a lot of time. We will make use of this
simulator.
On the right is the editor screen where you can place blocks to make a
program. At the moment, there is only one block on the screen and that
says ‘forever’. Its green colour indicates that it is a loop block and any other
blocks that are placed inside the Forever block will run repeatedly, forever
(or until the program is stopped).
The blocks that you will use can be found in the middle section. They are
grouped under different headings, such as ‘LOOPS’, ‘LIGHT’ and ‘LOGIC’,
and these groups have different colours. If you click on ‘LOOPS’, for
example, you will see all the green blocks that carry out loop operations, as
illustrated in Figure 1.7.
The first block, at the top, is the ‘forever’ block that is already on the
screen. Others include ‘on start’ which is included in a program when
instructions have to be performed as soon as the program starts. The next
block is ‘pause’ and this has a number in it. This essentially tells the
11
T276 PE1: Microcontrollers 1 Getting to know the express
program to take a rest for a fixed length of time. That length of time is the
number, in milli-seconds (ms), which can be changed.
If you want to use a block, click on it and it will appear in the editor screen
on the right. Try clicking on the ‘pause’ block to see what happens. It should
appear on the right in the editor screen. You will notice that it is a grey
colour with a yellow border. This is an indication that something is not right.
The ‘pause’ block shouldn’t be on its own like this, it should be inside a
loop. Try dragging it with the mouse to put it inside the ‘forever’ loop, as
illustrated in Figure 1.8.
When the ‘pause’ block is inside the ‘forever’ block it now appears green and
is functional. Now everything is alright. As a program it’s not very impressive.
The program goes round in a loop forever, repeatedly executing the pause
instruction. Not much use!
Now click on the set of blocks called ‘LIGHT’. You should see a set of blocks
that all make use of the neopixels in some way, as illustrated in Figure 1.9.
12
T276 PE1: Microcontrollers 1 Getting to know the express
Select the block that says, ‘Set all pixels to’, and this will appear on the
right-hand window.
Using the mouse, drag the block so that it is added to the ‘forever’ block,
above the ‘pause’ block, as illustrated in Figure 1.10. The program you have
now created sets all of the pixels to red, then pauses for 100 ms, then sets
all the pixels to red, then pauses for 100 ms and so on forever. You may
have noticed that the Express simulator is now showing all the pixels as red.
In other words, it’s running your program, and this is what you would see.
Now, select the block ‘Set all pixels’ again from the ‘LIGHT’ blocks, and this
time drag it with the mouse so that it is under the ‘pause’ block. Then, get
another ‘pause’ block from ‘LOOPS’ menu and insert it after the second ‘set
all pixels to’ block. Finally, click on the colour in the second ‘set all pixels to’
block. A colour palette appears from which you should select green by
clicking on the green square, as illustrated in Figure 1.11.
When you click on the green square, the colour in the block changes to
green. You now have a program that sets all the neopixels to red, pauses for
100 ms, then sets all the pixels to green and pauses for 100 ms, then goes
back to the beginning and does it all again, over and over.
13
T276 PE1: Microcontrollers 1 Getting to know the express
As soon as you make the change to the colour the program is ready to run
in the simulator. You should see it flashing red then green then red then
green, over, and over.
Now, make one last change. In both ‘pause’ blocks, change the time to 500
ms. To do this, click on the down arrow next to the number and select ‘500
ms’. The program you’ve produced now flashes red then green every half a
second. Again, you should be able to see the programme running in the
simulator.
The next step is to download the program to the Express, so that you can
see it running on the actual microcontroller.
At this point you probably haven’t saved the file. That’s ok, it means that
the file is called ‘untitled’, and when you download it will be saved in the
file ‘circuitplayground-Untitled.uf2’. However, there is a possibility that
you’ve thought ahead and saved the program, in which it will have the
name that you gave it, preceded by ‘circuitplayground’.
What you need to do next is compile and download the program into the
Express as a UF2 file. But first you need to get the Express ready to receive a
file. You can download a file to the Express when it is in Bootloader mode.
Step 1:
Put the Express into bootloader mode. You do this by pressing the Reset
button on the Express. Go back to Figure 1.2 for a reminder of where the
14
T276 PE1: Microcontrollers 1 Getting to know the express
reset button is; it is situated just below the microprocessor chip (the big
black square) on the Express. When you press the reset button all ten
neopixels turn red briefly, then turn green and stay green. This shows that
the Express is in Bootloader mode. The small red LED (D13) should also
flash slowly.
If this doesn’t happen either try pressing the reset button again, or even try
pressing it twice in quick succession. This is sometimes necessary to get it
into the right mode and it depends on what the microcontroller has
previously been used for.
Step 2:
When you are in bootloader mode, a new drive called CPLAYBOOT should
appear in your list of memory devices on your computer, as illustrated in
Figure 1.12.
Use whatever method you have on your computer to look at files. On mine I
double click on my documents folder. When this window opens, I can see
all my drives and folders down the left-hand side. One of those is called
CPLAYBOOT, and in my case it is also called drive E. When I click on it, it
opens up and shows three files.
The important file here is called CURRENT.UF2, since this is the program
that is running on the Express. When you download your program, no
matter you have called it, it will be saved on the Express as CURRENT.UF2.
That’s the only program that will ever be on the Express. This means that
you overwrite whatever the previous CURRENT.UF2 program was.
15
T276 PE1: Microcontrollers 1 Getting to know the express
Step 3:
Now you should compile and download your program. On the MakeCode
editor screen, there is a large clickable ‘Download’ button. When you click
on it you should see the download screen illustrated in Figure 1.13.
The download screen shows the three steps for downloading a file. In the
bottom-right corner there’s a green box which shows your file with the
name ‘circuitplayground-flashing.uf2’. Click on this box and it should
download the file.
What happens next depends very much on your computer and how you
have things set up. Essentially what you need to do is get the file that
you’ve downloaded into the CPLAYBOOT folder. Three possibilities are as
follows:
1. One possibility is that you are using Windows 10 and when you
download the file it is saved in the Download folder. If so, click on the
file and drag it into the CPLAYBOOT folder.
3. On an Apple Mac you use Finder to locate the file. Copy and paste it
into CPLAYBOOT.
As soon as you copy the file into the CPLAYBOOT drive the program should
start to run on the Express. The CPLAYBOOT drive should no longer be
accessible from your computer, and instead it should be replaced by the
MAKECODE drive.
However, it’s possible that you may get an error message. I do! On my
computer I get the error message illustrated in Figure 1.14.
16
T276 PE1: Microcontrollers 1 Getting to know the express
I can’t really explain why I get this, but I just ignore it. It’s clear that the
program has downloaded because I can see the neopixels flashing in the
correct way.
There are other possibilities of things going wrong at this point. For
example, when you look for CPLAYBOOT, sometimes it isn’t there. This
means that the Express is no longer in Bootloader mode, and you need to
press the reset button again and go through the downloading steps again.
Again, I don’t know why this happens, but I have found that unplugging the
USB, so the power goes off on the Express, then plugging it back in usually
solves the problem.
If you wait long enough with the first error message, you can get a second
error message, illustrated in Figure 1.16. Again, unplugging the USB cable
and plugging back in is needed.
However, if all goes well you have successfully written, compiled and
downloaded your first program on the Express. Congratulations!
17
T276 PE1: Microcontrollers 1 Getting to know the express
Before we finish this task, I just want to mention a couple of things. Firstly,
what happens when you turn off the power. As you know, the power is
being supplied to the Express by your computer, via the USB cable. So, to
cut the power you unplug the USB cable from the computer. Try it and see
what happens.
The Express starts up again in Bootloader mode, with all the neopixels set
to green. If you press the reset button your program should start running
again. What this shows is that your program stays in the Express memory
even when the power is turned off.
Earlier we saw that whatever name your program has when it’s in
MakeCode, it is always called CURRENT.UF2 on the Express. When you
download a program to the Express it will overwrite whatever program was
there before. For this, and many other reasons, it’s a good idea to save you
programs.
On my computer it asks me where I want to save the file and I can choose
the folder to put it in. The program has been given the name
‘circuitplayground-Program-1.uf2’. The file name has ‘circuitplayground’ in
front, any spaces are replaced with a dash, and ‘.uf2’ is added to the end. It
should be noted that you cannot read a UF2 file with a text editor because
it is just a load of 0s and 1s, binary instruction which can be understood by
the Express.
Find out where your program has been saved and make a note of its
location on your computer.
In the next task I want to show you some more of the blocks and I will use
the example of a simulated car alarm.
18
T276 PE1: Microcontrollers 1 Getting to know the express
First, I want you to drag the forever loop down the screen to about halfway.
Next, I want you to click on the ‘LOOPS’ set of blocks and select the ‘on
start’ block. Move this block to the top of the screen. Next go to the ‘INPUT’
blocks and select the ‘on shake’ and move this to the middle of the screen,
as illustrated in Figure 1.18.
The ‘on shake’ block uses the accelerometer on the Express to detect any
abrupt motion. Shaking the Express will cause this block to start.
19
T276 PE1: Microcontrollers 1 Getting to know the express
(a) Select ‘Make a Variable…’ (b) Insert the variable’s name (c) New variable blocks
A new window opens asking you for the name, as illustrated in Figure
1.19(b). Type in ‘counter’ then click ‘OK’. When you’ve created the new
variable, two new blocks become available, as illustrated in Figure 1.19(c):
▪ ‘set counter to’, which assigns a value to the variable. The default value
is 0, but this can be any value
▪ ‘change counter by’, which increments that value by a set number. The
default increment is 1, but this can be any value
There is also a rounded shape containing the variable ‘counter’ which you
can place inside other blocks to represent the value assigned to the variable
‘counter’. You’ll be doing this later.
Now, select the ‘set counter to’ block and move it into the ‘on start’ block.
Then, select the ‘set counter to’ block again, and move it into the ‘on shake’
block. In this second ‘set counter to’ block change the assigned value from 0
to a 1, as illustrated in Figure 1.20.
20
T276 PE1: Microcontrollers 1 Getting to know the express
this we can use an ‘IF’ statement from the ‘LOGIC’ blocks. Click on the
‘LOGIC’ blocks and select ‘if-then’ block and move this to the forever block.
The part of the block that says ‘true’ is a lozenge shape and represents
logical values, such as ‘true’ or ‘false’.
Go back to the ‘LOGIC’ blocks and under ‘Comparison’, select the lozenge
shape that says ‘0 = 0’ and move this into the lozenge shape in the ‘if-then’
block where it says ‘true’, as illustrated in Figure 1.21.
Next, go to the ‘VARIABLES’ blocks, and select the rounded shape with
‘counter’ in it and replace the first 0 with this variable. Change the second 0
to a 1, as illustrated in Figure 1.22.
21
T276 PE1: Microcontrollers 1 Getting to know the express
Click on the ‘LIGHT’ blocks and select ‘set all pixels to’ and put this in the ‘if-
then’ block. Then, add a pause of 500 ms (the ‘pause’ block is in ‘LOOPS’;
you’ll have to change the pause time from 200 to 500 ms). Then, add
another ‘set all pixels to’ block, and change the colour to white. Finally, add
another pause of 500 ms.
You may have noticed that after you added the ‘on shake’ block to your
program, the simulator changed so that a new ‘SHAKE’ button appeared
near the top of the simulator.
If the simulator isn’t already running, click on the ‘play’ arrow” to start it.
Once it’s running, click on the ‘SHAKE’ button to simulate shaking the
Express; this should set off the alarm.
Of course, no alarm is any good if it hasn’t got an irritating sound. From the
‘MUSIC’ blocks, select the ‘play sound’ block and move it so that it follows
after the first ‘set all pixels to’ block in the ‘if-then’ block, as illustrated in
Figure 1.25.
Try running the program on the simulator. Does it work? Don’t forget you
can stop the simulation by clicking on the ‘Play/Stop’ button below the
simulator (on the far left of the set of five buttons).
22
T276 PE1: Microcontrollers 1 Getting to know the express
It’s worth pausing here just to reflect on what the program is doing. By now
you’re probably getting irritated with the alarm going off so press the reset
button which will stop it. If you want to start it again, press the reset button
again. You may also want to give the program a name and save it.
The program has three separate blocks. When the program is running it
spends most of its time in the ‘forever’ loop, just going around and around
executing the instructions one after the other. At the start of the program it
executed the instructions in the ‘on start’ block, so when does the program
enter the ‘on shake’ block?
If this was a car alarm, you’d want some way of switching off the alarm. You
will use Button A to do this; let’s modify the program. Go to the ‘INPUT’
blocks and select the ‘on button A’ block. Put this block anywhere on the
editor screen, as illustrated in Figure 1.26.
From the ‘VARIABLES’ blocks, select the ‘set counter to’ block, and move
this into the ‘on button A’ block, as illustrated in Figure 1.27. Now, the
variable ‘counter’ is set to 0 when Button A is pressed.
23
T276 PE1: Microcontrollers 1 Getting to know the express
Now, run the simulator to see if it works. The program runs and nothing
happens. Click the ‘SHAKE’ button and the alarm goes off. If you then click
Button A, the alarm stops. Now, try downloading the program to see what
happens on the Express. The program should work in the same way:
shaking the Express activates the alarm, and the alarm stops when you
press Button A. The alarm can be started again by shaking the Express
again.
24
T276 PE1: Microcontrollers 1 Getting to know the express
We could change the car alarm so that it does one thing during the day and
another during the night. For example, we could switch the sound off if it is
night-time.
The blocks I’d like to introduce in the remainder of this task are the ‘repeat’
block and the ‘if-then-else’ block, which is an expansion of the ‘if-then’
block. First the ‘repeat’ block.
Let’s say that we want the alarm to sound five times and then be quiet for
five seconds, then repeat. To start off, we have a set of blocks that makes a
sound and flashes the neopixels once per second. I just want to repeat this
instruction five times. Fortunately, in the ‘LOOPS’ blocks there is a block
called ‘repeat’.
Click on this so that it appears on the editor screen. You’ll see that it is
greyed out which means that it has to be included inside one of the main
blocks. Now what I want you to do is quite fiddly. I want you to click on the
first ‘set all pixels to’ block and drag it out of the ‘if-then’ block; all the other
blocks below it should come with it, as illustrated in Figure 1.30(a). Let’s call
these the ‘alarm blocks’. Next, drag the ‘alarm blocks’ and put them inside
the ‘repeat’ block, as illustrated in Figure 1.30(b).
(a) Moving the ‘alarm blocks’ (b) Repeating the ‘alarm blocks’
Figure 1.30 Moving the ‘alarm blocks’ inside the ‘repeat’ block
Then, put the ‘repeat’ block inside the ‘if-then’ block, and edit the ‘repeat’
block so that it repeats five times instead of four, as illustrated in Figure
1.31.
25
T276 PE1: Microcontrollers 1 Getting to know the express
Figure 1.31 Moving the ‘repeat’ block inside the ‘if-then’ block
We now have a program that repeats the alarm five times, and this is all it
does: it sounds the alarm five times, then go around the ‘forever’ loop and
sounds the alarm five times again, and again, and again.
We need to add a pause, so that the alarm is more effective, say for five
seconds. This is simple enough. Just add a ‘pause’ block and specify a time
of 5 seconds (5000 ms) after the ‘repeat’ loop. You can enter this value by
typing, rather than using the drop-down menu. Now if you run this
program, it sounds the alarm five times, then it does nothing for five
seconds, then it sounds the alarm again, and repeats the ‘forever’ loop over
and over again. If you press Button A then the alarm stops. Is this
everything?
One thing I’ve noticed is that after pressing Button A the alarm stops, but all
the neopixels are white. I think we should turn them off. To do this I want
you to add another branch to the ‘if-then’ block. You do this by clicking on
the plus sign in a circle at the bottom of the ‘if-then’ block. When you click
on it another branch appears with the word ‘else’, as illustrated in Figure
1.32(a). This means that if counter equals 1 then it sets the alarm off, but if
counter doesn’t equal 1, then it does something else.
We want instruction B to turn the neopixels off, and we do this using the
‘set all pixels to’ block and the selecting the colour black, as illustrated in
Figure 1.32(b). Now when the program runs, shake the express and the
alarm goes off five times then waits five seconds and then repeats. If you
press Button A it finishes the current sequence of five and then stops for
five seconds before switching the neopixels off.
26
T276 PE1: Microcontrollers 1 Getting to know the express
There is a feature in the simulator which is very useful if you don’t know
what your program is doing or if it’s not doing what you expect it to do.
Under the image of the Express there are a row of five icons, the first of
which is the Play/Stop button, as illustrated in Figure 1.33.
If you hold your mouse over each button a description appears. Hold your
mouse over the third button from the left. The symbol on it is supposed to
be a snail. The words ‘Slow-Mo’ appear. In other words, if you click on this,
your program runs in slow motion. Not only that, each block lights up when
it is being executed, so you get a very good idea what your program is doing
because you can see the order in which it executes the blocks.
Try this now. You should see that various blocks light up and then it seems
to stop with the ‘if-then-else’ block lit up. This means that it is going around
the ‘forever’ loop testing the condition for ‘counter = 1’, but since counter
is assigned the value of 0 at the start, nothing else happens except that the
neopixels remain off. When you shake the Express (in the simulator), then
the variable ‘counter’ is reassigned the value of 1, and the alarm
instructions are executed.
27
T276 PE1: Microcontrollers 1 Getting to know the express
An additional task
Try applying what you have learned to expand the program. This is
something to try if you are feeling confident with your understanding of
how to use MakeCode to program the express. If you aren’t feeling quite so
confident, then just work through the solution.
The car alarm did all that we asked for. Obviously, you could add more
features. For example, you could change the program so that if it is shaken
again the alarm gets faster or louder or changes to a different colour. To do
this, in the ‘on-shake’ block instead of making ‘counter’ equal to 1, you
could add 1 to the counter using the ‘change counter by‘ block in
‘VARIABLE’. In the ‘if-then-else’ block you would have to add a second
branch using an ‘else-if’ structure:
If you shake the Express a third time, it will turn the pixels off because
counter would be equal to 3 and so the ELSE branch would be executed. So
perhaps you need to change the condition to:
In my solution I’ve increased the speed of the alarm when alarm B sounds
by reducing the pause to 250 ms.
Something that is worth mentioning here is that there is on-line help within
MakeCode. In the top-right of the screen, you will see a question mark in a
circle; this is a drop-down menu that has a list of options, as illustrated in
Figure 1.34.
28
T276 PE1: Microcontrollers 1 Getting to know the express
If you select ‘Blocks’, a window opens on the right-hand side which lists
most of the blocks with a short description of what each block does. For
example, in Figure 1.35(a) I’ve clicked on ‘Blocks’, selected the section
called ‘LOOPS’, and selected the first block in the list which is the ‘for’ block.
If I click on the question mark again, but this time select ‘Reference’, I can
find information about more of the blocks, as shown in Figure 1.35(b).
(a) Help entry for the ‘for’ block (b) The ‘Reference’ section of the help menu
One caution is that not all of the blocks are included in the help menu,
neither under ‘Blocks’ nor ‘Reference’.
A final tip is that if you let the mouse hover over a block, a brief description
of that block appears, as shown in Figure 1.36.
29
T276 PE1: Microcontrollers 1 Getting to know the express
My solution
I expanded the ‘if-then-else’ block to include an ‘else-if’ branch and copied
the blocks from Alarm A, but with the time in the ‘pause’ blocks shortened.
The new branch is shown in Figure 1.37.
That concludes Part 1, so I think you’ve earned a break. Before you go, let’s
consider what you’ve achieved so far:
▪ you’ve written and run your own programs, particularly in that last task.
Therefore, you’ve achieved a lot. What happens next is we start using the
Express to do experiments and to create programs from blocks that will be
useful later in the Practical Engineering component of T276.
30
T276 PE1: Microcontrollers 2 Using the microcontroller
31
T276 PE1: Microcontrollers 2 Using the microcontroller
Quite often the statement will be more mathematical. For example, we can
use a variable with a numerical value in an IF statement using one of the
Comparison blocks, as illustrated in Figure 2.2(a) In this example, if the
variable ‘number’ is assigned a value less than 5 then the comparison is
TRUE and the neopixels are turned red, otherwise the comparison is FALSE
and the neopixels are turned green.
We can also use the Boolean logic connectives such as AND, OR and NOT.
These were discussed in the preparatory materials.
The example in Figure 2.2(b) now shows that the neopixels are turned red
only if the variable ‘number’ is assigned a value that is greater than 0 AND
less than 5, in other words number is between 0 and 5.
When we say we have a digital output, this means that it accepts a value of
TRUE or FALSE, and outputs a voltage of 3.3 Volts or 0 Volts.
Now let’s look at digital inputs and outputs. On the Express the inputs and
outputs are the pads labelled A0, A1, A2 up to A7. Apart from A0 which can
produce an analogue output, all of the pads A1 to A7 can produce a digital
output or can be a digital or analogue input.
32
T276 PE1: Microcontrollers 2 Using the microcontroller
So, for 500 ms we output ‘LOW’ to Pin A1. Then we do the same again, only
this time the output is ‘HIGH’ (which is equivalent to TRUE). We are
therefore creating a digital output that is FALSE for 500 ms then TRUE for
500 ms. These instructions are contained in a ‘forever’ block so are
repeated forever.
Also, within the same loops, we read in the digital value from the Pin A2
and send the same digital value to the LED; this is the small red LED to the
right of the USB connection, labelled ‘D13’. When the program is running, if
the digital input is TRUE the LED is on, and if it is FALSE the LED is off. If the
value alternates between TRUE and FALSE then the LED should flash on and
off.
Before we run this program, we have to set up the Express. We need a wire
which is connected as shown in Figure 2.4. The colour of the wire is not
important, I’ve chosen green wire.
▪ one end of the wire is connected to the pad labelled A2; this is the third
pad counting clockwise from the USB connector
▪ the other end of the wire is connected to the pad labelled A1; this is the
fifth pin counting clockwise from the USB connector
We have therefore connected pad A1 to pad A2, so that Pad A1 has a digital
output, and pad A2 has a digital input (which is the output from A1).
Now download and run the program. When I did, the small red LED flashed.
33
T276 PE1: Microcontrollers 2 Using the microcontroller
This task may not seem like much, but what it shows is that we can produce
a digital signal as an output from the Express and read a digital signal as an
input into the Express. We will use such inputs and outputs in future tasks.
Pulsed outputs
Some of the input/output (I/O) pads on the Express are described as having
PWM output. This stands for Pulse Width Modulation and it is a way of
controlling motors, as described in the preparatory materials. Essentially
you produce a square wave voltage which has digital values, and you vary
the length of time that the pulse is high.
In the previous task we created output using ‘repeat’ loops and setting the
output to ‘HIGH’ for a time and then ‘LOW’ for a time. Imagine what this
would look like as a graph, plotting the voltage output against time; it is a
waveform which changes between two values, either ‘HIGH’ or ’LOW’, and
so it is a pulsed square waveform similar to PWM. But it is relatively slow
and to drive a motor we usually use a much higher frequency of pulsed
waveform, which means that the period is much shorter, typically 20 ms.
In MakeCode there are blocks which make use of the PWM capability of the
pads on the Express. You can find two blocks under the ‘PINS’ heading and
the sub-heading of ‘Servo’, as illustrated in Figure 2.5(a). These two blocks
are used to produce a PWM output.
The term ‘Servo’ is short for ‘Servomotor’. Very briefly, there are all sorts of
motors which can be driven by AC voltages or DC voltages. Typically, if you
apply a voltage to a DC motor then it rotates continuously. If you measure
the rotation and feed this information back to a controller, you can create a
servomotor. One of the features of a servomotor is that it doesn’t just
34
T276 PE1: Microcontrollers 2 Using the microcontroller
You will now create a program to produce a PWM output. We won’t attach
it to a motor at this point because that’s a little more complicated. The
motors that we are using in this kit require more current than the Express
can deliver, so we have to amplify the signal. We’ll do that in PE2. For now,
we’ll just look at the output.
Create a new project. From ‘LOOPS’, select the ‘on start’ block. Then from
‘PINS’, under ‘Servo’ you’ll find the two PWM blocks, which you should
select in turn to add to the program in the ‘on start’ block, as shown in
Figure 2.6.
Add a ‘digital write pin’ to a ‘forever’ loop and set it so that it writes the
digital input from pin A2 to the LED. The Express should be wired as before
in Figure 2.4, with a wire connecting pad A1 to pad A2.
35
T276 PE1: Microcontrollers 2 Using the microcontroller
Download the program. What you should see is the little red LED flashing a
few times, then stopping then flashing a few times again.
No. It’s not exactly showing the PWM waveform because of sampling, but it
gives an idea of what is happening. The samples are taken on average every
20 ms, but the actual timing can vary as it depends on how fast the
computer program runs. Figure 2.7 shows an image of the actual waveform
captured on an oscilloscope.
Compare this to graph of the waveform data given in Figure 2.8(a) and the
graph in Figure 2.8(b) of data that I’ve captured from the Express at a low
sample rate. The pulse waveform of the sampled data is very different from
the original, and this is caused by under-sampling which means that I need
to take more samples if I want to faithfully capture the original waveform.
So, what does this tell us. Firstly, we can produce a PWM output. Although
you couldn’t see it yourself, I have shown that the pulsed waveform was
produced by connecting an oscilloscope. Because of the slow sampling rate,
36
T276 PE1: Microcontrollers 2 Using the microcontroller
the flashing LED only showed samples of the waveform and these appeared
much slower because of aliasing.
(a) The original PWM waveform data (b) The sampled data taken of the waveform
In the next task we will look into sampling in more detail. But before we
leave PWM, I just want to show you some other blocks. As I’ve mentioned,
the Express assumes that we have a servo motor, but in fact we haven’t.
We just have a DC motor. To control the speed of the motor we are going
to have to vary the pulse width and the period. Fortunately, we can do that.
Figure 2.9 shows some block code that allows us to do this. We won’t use it
now, but this is similar to what will be used in PE2 and PE3.
The first block sets the pulse width, in this case to 10 ms (= 10000 μs). The
Express assumes that the period is 20 ms, so this sets the mark-space ratio
to 1 because the pulse width (or mark) is 10 ms and the space is 10 ms
giving a ratio of 10/10 = 1. The second block essentially changes the period.
In this example the period is changed to 150 ms (= 150000 μs).
37
T276 PE1: Microcontrollers 2 Using the microcontroller
Sampling rate
At the beginning of this part I said that you will be using the Express to
monitor values from a sensor such as the accelerometer. We already did
this in Part 1, where we used the ‘on shake’ block to respond to rapid
movement of the Express, since this block is activated when motion is
detected. What we want to do now is more specific in that we don’t just
want to detect when there is motion, but we want to record that motion.
That’s what I mean by monitoring. One important aspect of monitoring is
the question of whether you are collecting the data at a sufficient rate. The
collection of data is known as sampling, and how often you collect the data
is known as the sampling rate. We will look at this more closely next.
(a) The console blocks (b) Using the ‘console log value’ block
Next we want to go to the ‘INPUT’ blocks and select the ‘acceleration (mg)’
block and move it over the 0 in the ‘console log value’ block. Select the ‘x’ in
the ‘console log value’ block and replace it with ‘acceleration’ by editing the
text. Finally, add a ‘pause’ block into the loop after the ‘console log value’
block with a duration of 100 ms, as illustrated in Figure 2.11. You should
recall that the ‘pause’ block is in ‘LOOPS’.
38
T276 PE1: Microcontrollers 2 Using the microcontroller
On the left of the screen is the simulator, and it should already be running
the program. If not click on the ‘Play’ arrow under the simulated Express. If
you now click on the button that says ‘Show console Simulator’ you should
see something like Figure 2.12.
On the right-hand side you have a plotter that shows the data coming from
the accelerometer as a graph, and the measurement as text in the console
below it. You should see that when nothing is happening to the Express the
measured acceleration is 0.
Try moving the Express in the simulator by moving the mouse over it. You
should see the graph moving up and down and the numbers at the bottom
changing.
Figure 2.12 The console, showing the acceleration data as the Express simulator is moved
39
T276 PE1: Microcontrollers 2 Using the microcontroller
Continue to run the program with the accelerometer data being displayed
on the console. This time I want you to try to move the accelerometer in
such a way that we get something close to a sinewave with a frequency of
one cycle per second or 1 Hertz. (The unit of frequency is the Hertz which is
abbreviated to Hz.)
The way I want you to do this is to move the simulated Express with the
mouse, from side to side repeatedly. Try it and see what you get.
At this point I don’t really know what the frequency is. To try and make it
easier I am going to flash some lights at 500 ms intervals, in a sequence of
red, green, red, green repeatedly. So, it will flash from red to green and
back to red in one second. This will give me something to help me adjust
the speed that I’m moving the mouse. The modified program is in Figure
2.14. Click the ‘Go Back’ button to edit your code.
The samples are taken every 250 ms, so the sampling frequency is 4 Hz,
meaning there are four cycles per second. I want you to try to produce a
40
T276 PE1: Microcontrollers 2 Using the microcontroller
Aliasing
Having stated the Nyquist theorem, you may be wondering what happens
when you don’t obey the rule. Just out of interest, what do you think will
happen?
Inside the repeat block the ‘console log value’ block reads the acceleration
data in the 𝑥 direction and displays it in the console as the trace 𝑥, this is
preceded by a pause of 100 ms. These blocks are repeated 8 times. So, at
41
T276 PE1: Microcontrollers 2 Using the microcontroller
The second waveform clearly doesn’t look anything like the true waveform.
The trace of 𝑥 has a frequency of around 1 Hz. The trace of 𝑦 has a
frequency of around ⅓ or ¼ Hz. This waveform is known as an alias and has
a lower frequency than the original waveform.
Make a pendulum
So far, we’ve just looked at a simulation. When we do some real
experiments, we need to capture real data from the Express and store it. As
an example, I want you to create a pendulum and use the Express to
measure the acceleration when its swinging.
In the pack that was sent you should have a 100 g weight. If you have some
string or light cotton to hand, thread this through the weight to create a
simple pendulum with the weight as the ‘bob’, as illustrated in Figure 2.18.
If you can attach the other end of the thread to something that’s great, but
if not, just hold it in one hand.
Now, try to get your simple pendulum to oscillate with a period of about 1
second. The equation for the period of a simple pendulum:
𝑙
𝑇 = 2𝜋√
𝑔
42
T276 PE1: Microcontrollers 2 Using the microcontroller
suggests that you should be able to change the period 𝑇 by changing the
length 𝑙, since 𝑔 is constant with a value of 9.81 ms-2, to 3 significant
figures. And according to the equation you should find that if you have a
pendulum with a length of approximately 0.25 m (or 25 cm), this should
give you a period of approximately 1 second.
Hold the string so that the length from the pivot (or your hand if you are
holding the string) to the weight is about 25 cm. Let the weight swing back
and forth naturally and see if it takes about 1 second to swing back and
forth. Maybe count 10 swings and see how long that takes.
Next, I want you to fit the Express to the weight. To do this I want you to
push an M3 eye bolt through one of the GND pads on the Express and use
two M3 nuts to secure it in place, as illustrated in Figure 2.19(a). We use a
GND pad to ensure that there will be no current passing through the bolt.
Next screw a third M3 nut approximately 5mm onto the eye bolt, this is to
locate the weight.
Now, screw the 100 g weight onto the M3 screw, and screw a second M3
eyebolt into the weight, as illustrated in Figure 2.19(b). Use your 5.5 mm
spanner to tighten the nuts so that the weight is firmly attached to the
Express.
We will use the USB cable as the string of the pendulum, but need to avoid
damaging the USB port, so will use the eye bolt to take the weight. To do
this, create a loop in the USB cable, as illustrated in Figure 2.19(c), then
tighten the loop around the eye bolt, as illustrated in Figure 2.19(d).
43
T276 PE1: Microcontrollers 2 Using the microcontroller
(c) Create a loop in the USB cable (d) Tighten around the eye bolt
Now allow a length of 25cm of USB cable, and swing the pendulum, and
record the period of the swing. Is it still oscillating at 1 Hz?
No. Firstly because we have attached the Express and this has a USB cable
attached to the laptop. This causes some drag. I found that the pendulum
oscillated too quickly.
I lengthened the string until the pendulum was oscillating at about 1 Hz. I
found that with a length of string of about 0.5 meter I get a period of about
1 second. You may find a different length
If you have a PC/laptop, and are running Windows 10 and have permission
to download and install software, then you can skip Task 2.5 and jump to
Task 2.6.
44
T276 PE1: Microcontrollers 2 Using the microcontroller
If you don’t have a PC/laptop (e.g. you have an Apple mac), an older version
of Windows or you can’t download and install software, then do Task 2.5
instead and skip Task 2.6.
Datalogging
This task shows how we can store data in memory, called flash memory, on
the Express itself. You can then copy the data, which is stored in a file, to
your computer and open it using Excel. For this task we will continue using
the web version of MakeCode, which means it can be carried out on any
computer. If you have a computer running Windows 10 and you have
permission to download and install software, you should skip this section
and go straight to Task 2.6.
Extensions
In MakeCode there are a set of standard blocks. But it is also possible to
create your own block, to carry out a function not available in the standard
blocks. Some non-standard blocks that are useful for projects have been
created by members of the MakeCode community and made available to
other users. These other blocks are referred to as Extensions, and one of
these is the datalogger. The datalogger contains blocks that make it
possible to record data to a file, and it has online documentation that
explains its use, which is available via the link:
https://learn.adafruit.com/data-logging-and-file-storage-in-
makecode/datalogger-use
The documentation describes how to use the datalogger blocks, but it’s not
necessary for you to read it in detail (unless you chose to). However, the
datalogger blocks don’t quite work the way the documentation says they
should. Whether the Express has changed or MakeCode has changed I don’t
know, so what do we do? We’ll use the datalogger blocks, but we’ll have to
make some changes to create a datalogger that does work.
The datalogger
Open MakeCode and start a new project. Scroll to the bottom of the list of
blocks and click on the very last entry which says ‘Advanced’. In the list of
‘Advanced’ blocks, the last entry is ‘Extensions’. Click on ‘Extensions’, and
you should see a screen, similar to the one illustrated in Figure 2.20.
45
T276 PE1: Microcontrollers 2 Using the microcontroller
Within these extensions is ‘datalogger’. Click it, and when you return to
MakeCode you will find that you have an extra set of blocks in the menu
called ‘DATALOGGER’, which includes the new ‘datalogger’ blocks, as
illustrated in Figure 2.21(a). You also have another new set of blocks called
‘STORAGE’ which includes the blocks illustrated in Figure 2.21(b).
Using the ‘DATALOGGER’ and ‘STORAGE’ blocks, and other standard blocks,
create the program in Figure 2.22. The program has three sets of blocks,
each contained in either the ‘on start’ block, the ‘forever’ block or the ‘on
Button A click' block. The first block in the ‘on start’ block is the ‘remove
file’ block from ‘STORAGE’. Change the name of the file to ‘log.csv’, and this
will ensure that a new data file is created each time the program is run.
Also, in the ‘on start’ block are three ‘DATALOGGER’ configuration blocks:
the ‘data logger set separator’ block is used to format the data file; the ‘set
data logger sampling interval’ block is used to specify how often data is
collected; and the ‘data logger’ is used to turn the data logger ON or OFF.
46
T276 PE1: Microcontrollers 2 Using the microcontroller
‘DATALOGGER’ data blocks are used in the ‘forever’ loop: the ‘data logger
add’ creates a data entry to be added to the log file, which is called
‘log.csv’; and the ‘data logger add row’ adds the data to the file.
In summary, the instructions inside the ‘on start’ block are implemented
when the program starts, and we have:
▪ a ‘remove file’ block which deletes the file ‘log.csv’ (if it exists)
▪ aButton
‘set pixel color at’ block that sets the colour of the neopixel next to
A to green (each neopixels has a position specified by a value,
with 0 referring to the neopixel to the left of the USB port, 1 referring to
the next neopixel counter-clockwise and so on)
▪ adata
‘data logger set separator’ block which formats the data file so that
is separated by commas. This creates a ‘.csv’ file which stands for
‘Comma Separated Values’ and is a format that can be read by a
spreadsheet
47
T276 PE1: Microcontrollers 2 Using the microcontroller
▪ avariable
‘set variable’ block which I’ve used to assign the value of FALSE to a
called ‘running’. If you need to remind yourself how to create a
variable, revisit Task 1.4
The blocks inside the ‘forever’ block, repeat over and over again until the
program is stopped, and we have:
▫ arow,
‘data logger add row’ block, which adds the data entry, as a new
to the data file ‘log.csv’
Finally, the blocks inside the ‘on button A’ block, runs when Button A has
been clicked, and we have:
▪ aNOT
‘set variable’ block which assigns to the variable ‘running’ the value of
‘running’. So, if ‘running’ is TRUE it is assigned the value FALSE, and
if it is FALSE, it assigns the value TRUE. This makes Button A act like an
on/off switch, that is used to start or stop the Express from logging data
to the file ‘log.csv’
▫ ato‘set pixel color at’ block, that sets the colour of the neopixel next
Button A to red (to indicate that the Express is logging data)
▫ alogger
‘data logger’ block with the value set to ON. This starts the data
so that data can be written to the file’log.csv’
▪ Iftheinstead, ‘running’ is assigned the value FALSE, then the blocks inside
‘else’ block are run. These are:
▫ ato‘set pixel color at’ block, that sets the colour of the neopixel next
Button A to green (to indicate that the Express is not logging
data)
▫ alogger
‘data logger’ block with the value set to OFF. This stops the data
48
T276 PE1: Microcontrollers 2 Using the microcontroller
I want you to press Button A, then set the pendulum swinging. After about
10 seconds stop the pendulum and press Button A again. Once you press
Button A again, the lights should turn GREEN, and the Express has stopped
recording data, and we should now be able to see our log file.
It’s possible that when you look in the SPIFLASH folder there’s nothing
there. If this happens, press reset on the Express, download the program
again and repeat the experiment. This time there should be a file there
called ‘log.csv’.
Copy the file ‘log.csv’ to a folder on your computer, then double click on
‘log.csv’ and it should open in Excel, as illustrated in Figure 2.23(b). This
shows the data. You can also see that it automatically time stamps the data.
The two cells with NaN (Not A Number) are created for reasons which I
don’t know. You can either delete the or just ignore them.
Hold the mouse down and select both the time and the data, then click on
‘Insert’ at the top. In the ‘Charts’ box, select the graph called ‘Scatter’ and
you should create a chart similar to the chart in Figure 2.24. From this graph
you can identify the period of oscillation for the pendulum. How does it
compare to the period you estimated, and the period predicted by the
simple pendulum equation? What happens if you repeat the experiment
using a different length string? How well does the simple pendulum
equation model the behaviour of your pendulum?
49
T276 PE1: Microcontrollers 2 Using the microcontroller
The data logger allows you to build programs using blocks and it allows you
to save data into a file which can then be copied to your computer and
opened in Excel.
You are now ready to put your learning to practice in Task 2.7.
Go the website:
https://learn.adafruit.com/adafruit-circuit-playground-express/makecode-
and-windows-10
50
T276 PE1: Microcontrollers 2 Using the microcontroller
You should see a screen like in Figure 2.25. Follow the download and
installation instructions and launch the App. It should look just like the
MakeCode software that you already seen.
Once you’ve got the app and launched it, recreate the program from Task
2.3, which you used to collect data from the accelerometer and display it on
the console. The program is shown again in Figure 2.26.
Now try swinging the pendulum, which should oscillate at around 1 Hz (the
exact frequency doesn’t matter). Figure 2.27 shows the display on the
console in my attempt.
51
T276 PE1: Microcontrollers 2 Using the microcontroller
As you can see, the amplitude, the height of the peaks, is not very
consistent, but there are peaks at regular intervals.
The program will continue running. However, you can stop the recording.
To do so, click on the ‘Pause recording’ button, in the top-right of the
console screen, this is the button with the pause symbol, . Now click on
the ‘Export data’ button, . This exports the data to an Excel file. When I
did this, the Excel symbol at the bottom of my screen started flashing.
When I clicked on the symbol the Excel spreadsheet opened, showing the
acceleration data along with timestamp data, as illustrated in Figure
2.28(a).
(a) The exported data (b) Plotting the data in a scatter diagram
If I hold the mouse down and select both the time and the data, then click
on ‘Insert’ at the top. In the ‘Charts’ box, I select the graph called ‘Scatter’
and this produces a plot of the data, as illustrated in Figure 2.28(b). From
this graph you can identify the period of oscillation for the pendulum. How
does it compare to the period you estimated, and the period predicted by
the simple pendulum equation? What happens if you repeat the
52
T276 PE1: Microcontrollers 2 Using the microcontroller
experiment using a different length string? How well does the simple
pendulum equation model the behaviour of your pendulum?
To conclude, the MakeCode app allows you to create programs in the same
way as you created programs in the online version of MakeCode. It has two
additional features:
Let’s make a system that counts the number of steps when you are jogging
on the spot. You already have a program that takes measurements from the
accelerometer and you can save the data to an Excel file. I want you to edit
that program so that it counts steps.
There is also a fourth value that you can use which is called ‘strength’,
which is given by
strength = √𝑥 2 + 𝑦 2 + 𝑧 2
𝑥=0
𝑦=0
53
T276 PE1: Microcontrollers 2 Using the microcontroller
𝑧 = −1024
This is due to the effect of gravity which is always acting downwards with a
force of 9.81 ms-2, to 3 significant figures. A value of 1024 is equivalent to a
kilobyte, which is approximately 1000 bytes, and represents an acceleration
of 1000 mg or 1 g, which is equivalent to 9.81 ms-2. So, when the Express is
stationary the strength is given by
strength = √𝑥 2 + 𝑦 2 + 𝑧 2 = 1024
What we notice about one period of the wave is that it starts off at zero,
goes up, comes back down, goes negative, keeps going down, then comes
back up again. At the end of each period it crosses the zero line and goes
from negative to positive. If we could count the number of times the
waveform goes from negative to positive, this would give a measure of the
number of steps.
Let’s call the current value of the acceleration ACC. Let’s call the previous
value of acceleration OLD_ACC.
One last thing to take into account is that even when the Express is not
moving there is a small amount of noise. Noise is just a term we use for
random fluctuations. The noise can be positive or negative, so the
acceleration is jumping over the zero crossing and this gets counted as a
step. To avoid this problem, we change the test so that it is something like:
This means that the acceleration has to have a significant change before a
step is counted.
54
T276 PE1: Microcontrollers 2 Using the microcontroller
On Start:
OLD_ACC = 0
Steps = 0
Forever:
OLD_ACC = ACC
Then in the forever loop, we read in the value of the acceleration. We then
test to see if the value of acceleration is bigger than +30, and the old value
was less than -30. If that’s TRUE, then you increase the number of steps by
1. If it’s not TRUE, you do nothing. Before you go round the loop again you
make the current value of acceleration become the old value.
Try creating this program in MakeCode by editing the previous program for
storing the acceleration data. You should be able to produce an Excel file
where you can see the step count. Figure 2.29 shows my results in a graph.
For information, two programs are shown in Figure 2.30 and Figure 2.31.
The first program in Figure 2.30 uses the data logger from Task 3.2, so is
written for those who are using the web version of MakeCode. The second
program in Figure 2.31 is written for the MakeCode app from Task 3.3 and
uses the console.
55
T276 PE1: Microcontrollers 2 Using the microcontroller
Figure 2.30 The step counter program using the data logger
Figure 2.31 The step counter program using the MakeCode app
56
T276 PE1: Microcontrollers 2 Using the microcontroller
Your program may be different from both of these, but that doesn’t mean
your program is wrong, it’s just different. There are many ways to solve a
problem, and many ways to write a program.
This concludes the programming part of the activity. At this point you
should have all the skills that you need to collect data from the sensors,
either through the console or using the datalogger.
The final task looks at what you can do with the data once you have
collected it.
57
T276 PE1: Microcontrollers 3 Analysing the frequency spectrum
▪ approximately
second
20 seconds of periodic swing at about one cycle per
▪ approximately
frequency
20 seconds of periodic swing at twice to three times the
To do this, I used the simulator with the program from Task 2.3, which we
used to collect data from the accelerometer and display it on the console,
with an additional ‘pause’ block set to 50 ms.
Visualise the downloaded data using a scatter chart. You should be able to
recognise the four distinct waveform patterns. Also make sure that within
each of those four patterns there are at least 256 samples. My chart is
illustrated in Figure 3.1.
58
T276 PE1: Microcontrollers 3 Analysing the frequency spectrum
Now, using 256 samples from each of the four separate waveform patterns,
compute and visualise their corresponding spectra. To remind yourself how
to do this see the preparatory materials.
The four spectra I produced are shown in the Figure 3.2, and to explore
these it is useful to consider the following questions:
59
T276 PE1: Microcontrollers 3 Analysing the frequency spectrum
the individual spectra from Figure 3.2 are apparent, but timing of these is
lost. The spectral evolution cannot be traced in the overall spectrum
because it is a composite among all the four spectra, without being able to
show which spectral feature occurs at which time instant. Do you see the
same patterns in your spectra?
This concludes PE1, in which you have learned to program the Express to
collect data from its sensors, and to analyse the data to identify prominent
oscillations. You will apply what you have learned as you work through the
rest of the Practical Engineering component of T276.
60