You are on page 1of 60

T276 Engineering: professions, Practical engineering

practice and skills 2 Student notes

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

Copyright 2022 The Open University v1.0


T276 PE1 Microcontrollers Introduction

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.

I am going to show you how to write programs using a tool called


‘MakeCode’, which is a platform that provides a Graphical Programming
interface. Using MakeCode you create a program by selecting and joining
colourful blocks that represent different actions. This is a method of
programming that can be learned by a wide range of people from school
children to adults. Part of its appeal is that you don’t have to worry about
some of the details that you get with programming, like getting the spacing
right or the brackets or the semi-colons.

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:

Part 1 Getting to know the Express

Task 1.1 Getting started

Task 1.2 Creating a MakeCode program

Task 1.3 Downloading to the Express

Task 1.4 Programming a car alarm

Task 1.5 Programming an advanced car alarm

Task 1.6 An additional task

Part 2 Using the microcontroller

Task 2.1 Digital inputs and outputs

Task 2.2 Pulsed outputs

Task 2.3 Sampling rate

Task 2.4 Make a pendulum

Task 2.5 Datalogging

Task 2.6 The MakeCode app

Task 2.7.4 Programming a step counter

Part 3 Analysing data

Task 3.1 Analysing the frequency spectrum

Aims
After carrying out the tasks in PE1 you will be able to:

▪ write programs using the MakeCode programming environment


▪ program the Adafruit Circuit Playground Express to respond to various
input signals from its sensors

▪ program the Adafruit Circuit Playground Express to output signals


▪ program the Adafruit Circuit Playground Express to log data from its
sensors and create files to store the data

▪ conduct Fourier analysis to interrogate data from oscillations


3
T276 PE1 Microcontrollers Introduction

Health and safety


You should conduct PE1 only in the way described and with equipment
provided and wash your hands before and after any experimentation.

The complete risk assessment for the T276 practical engineering


component is available in the ‘Resources’ section of the T276 module
website. In summary, the hazards identified for PE1 are listed below:

▪ small components, which if swallowed can damage internally


▪ plastic packaging, which if swallowed could lead to asphyxiation
▪ weights, which if dropped may cause injury
▪ USB cable, which if used improperly or if the device is damaged there is
a risk of electric shock, overheating/fire

▪ USB cable, which is a possible trip and strangulation hazard


▪ crocodile clips, which have sharp edges which may result in cuts
You should use this list to complete a personalised risk assessment, taking
into account the environment you will be working in and anybody that you
share space with, including pets. You can find a copy of the personalised
risk assessment table below. It is also available as an editable document in
the ‘Resources’ section of the T276 module website.

Hazards Risk level


Control measures Action
What Who How Likelihood Consequences Level

Check the kit


Before starting, check the contents of the PE1 mailing against the Contents
Checklist; if there is anything missing or damaged, then follow the
instructions given. Ensure that you can identify each item. Also, be aware
that you will reuse this equipment throughout the module so when you
have completed PE1 you should store it in a safe place.

4
T276 PE1: Microcontrollers 1 Getting to know the express

1 Getting to know the express


For this part you will require the following equipment:

▪ Adafruit circuit playground express (WIM code: T276-09)


▪ USB cable (WIM code: T276-10)
Getting started
As well as the Express, you should also have received a USB cable. One end
of the cable connects to your computer and the other to the connector at
the top of the Express, as shown in Figure 1.1.

Don’t plug it in yet!! Wait until I tell you.

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.

Figure 1.2 Sensors, buttons and pins of the Express

Starting with the outputs, there is:

▪ 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 speaker which can produce sounds

▪ a green LED marked ON which shows when the Express is being


powered

And the inputs include:

▪ a motion sensor. This is an accelerometer which measures the


acceleration of the Express in three directions labelled X (left and
right), Y (forwards and backwards) and Z (up and down)

▪ a temperature sensor that uses a heat-sensitive resistor called a


thermistor to measure temperature

▪ 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 slide switch that slides from left to right

▪ a microphone that can detect sound

▪ 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

Figure 1.3 The Express power pads

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

▪ A4 and A5: These pins can be digital I/O, or analogue input

▪ 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.

That’s a brief introduction to the hardware. In the next task I want to


introduce the software i.e. the programming environment that we will use.

Creating a MakeCode program


At the heart of the Express is the microcontroller chip, which is an
ATSAMD21G18-AU, manufactured by Microchip Technology. Generally,
computers are defined by their clock speed (how fast they run), which is
measured in Hertz, Hz, which you’ll learn more about later. The clock isn’t
something that tells the time. It is essentially a square wave that changes
from 0 to 1 to 0 to 1 and so on. The clock speed refers to how often the
square wave changes from 0 to 1. A 48 MHz clock means that the square

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 microcontroller is a digital device, so all the information is in the form


of 1s and 0s. At one level, the MakeCode level for example, the program
can be described by a set of blocks, where each block is a separate
instruction. This is convenient for us as humans because we can see these
blocks and read the instructions. At the other end, the microcontroller end,
the instructions have to be represented in some kind of binary code that
the machine understands; and this is called machine code. Converting the
MakeCode instruction into a machine code instruction is called compiling
the program, as illustrated in Figure 1.4. The details of how the MakeCode
program is converted to machine code are not important here. All you need
to know is that the program you create in MakeCode has to be converted to
something the microcontroller understands, and that process is
compilation.

Figure 1.4 Compiling a program

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.

Figure 1.5 Opening screen for MakeCode

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.

Figure 1.6 The MakeCode editor screen

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

When a program is running, the instructions, which we will construct using


blocks, get executed. That doesn’t mean get killed, it means whatever the
instruction is supposed to do, it will get done. The program steps through
the instructions one at a time, to carry out a specific operation.

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.

Figure 1.7 All the blocks in ‘LOOPS’

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.

(a) outside a loop (b) inside a loop


Figure 1.8 Using the ‘pause’ block

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

Figure 1.9 All the blocks in ‘LIGHT’

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.

Figure 1.10 Set all pixels to red then pause

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.

Figure 1.11 Selecting the colour of the neopixels

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’.

Downloading to the Express


Before you can download the program to the Express you must make sure
that the Express is connected to your computer via the USB cable. If it isn’t
already connected, do that now.

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.

Let’s go through the process of downloading your program in steps.

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.

Figure 1.12 The CPLAYBOOT folder in Windows Explorer

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.

Figure 1.13 The download screen

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.

2. On my computer I have it set up so that every time it downloads a file it


asks me where I want to download to. In this case, when I click
download a window pops up with all my folders and I click on the
CPLAYBOOT folder so that my program is downloaded to CPLAYBOOT.

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

Figure 1.14 Download error message

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.

Occasionally, when I try to download a program to the Express I get the


message illustrated in Figure 1.15.

Figure 1.15 An express error message

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.

Figure 1.16 A second express error message

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 neopixels go off.

Now try plugging it in again. 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.

Go back to MakeCode, and hopefully your program is still there. At the


bottom of the screen there is a blue box that says untitled and shows a
computer disk, the icon for Save. Give your program a name, ‘Program 1’
say, since it’s your first program. You have to delete the word ‘untitled’ and
then type your program name in, as illustrated in Figure 1.17. Then click on
the Save icon.

Figure 1.17 Giving your program a name

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

Programming a car alarm


If you still have MakeCode open, click on ‘HOME’ in the top-left of the
screen and then select ‘New Project’. Alternatively, if you closed
MakeCode, on the opening screen select ‘New Project’. You should then see
a screen with just the ‘forever’ block in the editor screen.

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.

Figure 1.18 A program with three blocks

The ‘on shake’ block uses the accelerometer on the Express to detect any
abrupt motion. Shaking the Express will cause this block to start.

Next, we are going to need a variable. This is like a mathematical variable,


and can be assigned different values, and has to have a name. It’s
important to adopt meaningful names for variables when writing software
because it makes it easier for you, and for others, to follow and alter if
needed. For reasons that will become apparent later, I will call it ‘counter’.
Click on ‘VARIABLES’, and a new window opens asking you to ‘Make a
Variable…’. Click in the box that says ‘Make a Variable…’, as illustrated in
Figure 1.19(a).

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

Figure 1.19 Creating a new variable

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.

Figure 1.20 Changing the number assigned to a variable

This program is supposed to simulate a simple car alarm. When the


program starts, the variable ‘counter’ is set to 0. If, at some point, the car is
shaken, the then ‘counter’ is set to 1. So, we want the program to do
nothing if the counter is 0 and to sound an alarm if the counter is 1. To do

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.

Figure 1.21 Insert the comparison in the ‘if-then’ block

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.

Figure 1.22 Insert ‘counter’ in the comparison

What we now have is a forever loop that will do something if ‘counter’ is


equal to 1, otherwise it will do nothing. What we want it to do when
‘counter’ is 1 is sound the alarm. Let’s put in some flashing lights and a
noise.

First, add the flashing lights, as illustrated in Figure 1.23.

Figure 1.23 The car alarm program

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.

Figure 1.24 The simulator with the ‘SHAKE’ button

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.

Figure 1.25 Developing the car alarm program

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

If the program works as expected, download it to the Express. Remember,


press the reset button to put the Express into bootloader mode, then click
on download. Put the file into CPLAYBOOT and then it should run. Initially
nothing happens. Pick the Express up and give it a shake and this should set
the alarm off.

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?

The program is described as interrupt driven, which means that it will go


around the forever loop if there are no interruptions. If the Express gets
shaken, the forever loop is interrupted, it then follows the instructions in
the ‘on shake’ block, and then goes back to the ‘forever’ loop.

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.

Figure 1.26 Add the ‘on button A’ block

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

Figure 1.27 Set counter to 0 when Button A is pressed

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.

Save the program as ‘Car Alarm’.

Programming an advanced car alarm


There’s all sorts of additions we could make to the car alarm to make it
more sophisticated. However, my reason for using this example is to
demonstrate more of the MakeCode blocks. You’ve seen how the
accelerometer can be used in the ‘on shake’ block, but there are other
sensors on the Express. There’s a light sensor, temperature sensor and a
microphone. If you go to the ‘INPUT’ blocks you will see other blocks that
make use of these sensors, as illustrated in Figure 1.28.

Figure 1.28 Some of the ‘INPUT’ blocks

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’.

Figure 1.29 The ‘repeat’ block

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.

What we have constructed is an IF-THEN-ELSE structure:

IF (counter = 1) THEN (do instruction A)

ELSE (do instruction B)

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.

Try simulating this program to see if it does what we want. If it works,


download it to your Express and see if it works there too. Also, give the
program a name, ‘Car Alarm 2’ for example, and save it.

26
T276 PE1: Microcontrollers 1 Getting to know the express

(a) An expanded ’if-then-else’ block (b) Figure caption label

Figure 1.32 Completing the program with an ‘if-then-else’ block

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.

Figure 1.33 The simulator control buttons

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 (counter = 1) THEN (sound alarm A)

ELSE IF (counter = 2) THEN (sound alarm B)

ELSE (turn neopixels off)

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:

IF (counter = 1) THEN (sound alarm A)

ELSE IF (counter > 1) THEN (sound alarm B)

ELSE (turn neopixels off)

In my solution I’ve increased the speed of the alarm when alarm B sounds
by reducing the pause to 250 ms.

Have a go yourself, and then compare your program to my solution.

Some helpful hints


Here are a couple of things to note. Firstly, to get another branch in the ‘if-
then-else’ block, click on the plus in a circle. Secondly, you can copy blocks,
sets of blocks or parts of blocks by right clicking on them and selecting
‘Duplicate’. A duplicate is formed which can be placed wherever you need
it.

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

Figure 1.34 The MakeCode help menu

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

Figure 1.35 Using the MakeCode 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

Figure 1.36 Information about a block is shown by hovering the mouse

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.

Figure 1.37 My solution showing the additional ‘else-if’ branch

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 been introduced to the Express microcontroller and seen that it


contains a number of input and output devices that you can use.

▪ you’ve been introduced to MakeCode which allows you to quickly


create programs that can run on the Express

▪ 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

2 Using the microcontroller


The next part of the activity involves connecting the microcontroller to the
outside world and collecting data. We start off by looking at the way we can
produce output voltages which can drive other devices such as motors and
receive data.

For this part you will require the following equipment:

▪ Adafruit circuit playground express (WIM code: T276-09)


▪ USB cable (WIM code: T276-10)
▪ Wire with crocodile clips (WIM code: T276-11)
▪ 100 g weight (WIM code: T276-08)
▪ M3 eye bolt (WIM code: T276-06)
▪ M3 nuts (WIM code: T276-05)
▪ A length of light cotton or thread (not included in kit)
2.1 Digital input and outputs
In programming, we use IF statements where we do one thing if a
statement is TRUE and another if the statement is FALSE. In MakeCode you
can see that the IF statement in the ‘if-then’ block contains a lozenge shape
with the word ‘true’, which can also be changed to ‘false’. In MakeCode, all
logical values are lozenge shaped, as illustrated in Figure 2.1.

(a) ‘if-the’ blocks (b) Boolean comparisons (c) Boolean operators

Figure 2.1 MakeCode ‘LOGIC’ blocks

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.

(a) Using comparioson (b) Using logical AND

Figure 2.2 Using Boolean comparisons and operators

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.

Finally, in terms of electronics, we interpret the 1 (TRUE) and 0 (FALSE) as a


voltage. In the Express we have a logic 1 which is around 3.3 Volts and a
logic 0 which is around 0 volts.

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.

We have to create a new program which is shown below. Start a new


project in MakeCode and create the program in Figure 2.3. The ‘forever’,
‘repeat’ and ‘pause’ blocks are all in the ‘LOOPS’ blocks. The ‘digital read’
and ‘digital write’ blocks are all in the ‘PINS’ blocks, which can be found by
clicking on ‘ADVANCED’ and then ‘PINS’. In MakeCode, ‘pins’ refer to the
input/output pads on the Express, and while ‘pins’ refers to the code, and
‘pads’ refers to the physical equipment, we will use the terms
interchangeably.

In the program we output a digital (logical) value of ‘LOW’ (which is


equivalent to FALSE) five times to Pin A1, separated by a pause of 100 ms.

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.

Figure 2.3 Program to monitor the digital output on pin A1

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.

As you can see from the photo:

▪ 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

Figure 2.4 Wiring up the Express

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

rotate continuously but can be set to rotate to a particular angle. For


example, a rotation of one quarter turn would be an angle of 90o. Although
we won’t be using a servomotor, this is the term that MakeCode uses for all
motors.

(a) ‘PINS’ blocks, showing ‘Servo’ (b) A section of a PWM waveform

Figure 2.5 Using MakeCode to produce a PWM waveform

The specific form of a PWM output is a pulse waveform, similar to the


graph plotted in Figure 2.5(b), which has a period of 20 ms divided into two
parts: for 1500 microseconds (or 1.5 ms), the value is 1; for the remaining
18.5 ms, the value is 0. And this waveform repeats over and over.

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

Figure 2.6 Reading and writing signals to the pads

Download the program. What you should see is the little red LED flashing a
few times, then stopping then flashing a few times again.

Is this what you expect to see?

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.

Figure 2.7 An oscilloscope trace showing the PWM waveform

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

Figure 2.8 A comparison of PWM waveform data and sampled data

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.

Figure 2.9 Adjusting the pulse width

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

Now, let’s look at sampling.

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.

Using the console


Let’s say that I want a program that captures the strength of the
acceleration of the Express, ten times a second, and displays that value. I
can start creating the program by creating a ‘forever’ loop. Inside that loop I
am going to use a block that you haven’t seen before. In the menu for
blocks there are several options, including ‘ADVANCED’. If you click on
‘ADVANCED’, more groups of blocks appear, including one called ‘CONSOLE’
When you select on ‘CONSOLE’ you should be presented with two new
console blocks, as illustrated in Figure 2.10(a). Select ‘console log value’
block and move it into the forever loop, as illustrated in Figure 2.10(b).

(a) The console blocks (b) Using the ‘console log value’ block

Figure 2.10 Using the console blocks

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

Figure 2.11 Writing acceleration data to the console

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

In the program, we have inserted a pause of 100 ms, so the acceleration is


only read at approximately every 100 ms. We call this process sampling,
and there is one particularly important point about sampling which is
summarised in a theorem called the Nyquist theorem. If we wish to
measure a signal that is oscillating at a particular frequency, 𝑓 say, then we
have to take samples at a frequency that is more than twice 𝑓. I want to
look at this in more detail and show you what happens if you don’t obey
this theorem.

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.

My attempt when I move the mouse is illustrated in Figure 2.13. After


trying different ways, I found that moving the mouse left to right and back
repeatedly gave the best results.

Figure 2.13 My attempt at creating an oscillating waveform on the graph

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.

Figure 2.14 The program with synchronising lights

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

sinusoidal waveform that repeats every second, so has a frequency of 1 Hz.


To do this move the mouse from one side when the lights are red to the
other side when the lights are green and back to the first side when the
lights are red and so on. This produces a waveform that is about 1 Hz, a
illustrated in Figure 2.15.

Figure 2.15 My attempt at a 1 Hz waveform

The waveform that you’ve produced is at around 1 Hz and it is being


sampled at around 4 Hz, so what is shown on the graph should be a
reasonably faithful reproduction of the movement of the simulated Express.
In the next task we will look at what happens when we don’t follow the
Nyquist theorem.

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?

The answer is aliasing, as we saw in Figure 2.8 when we under-sampled the


PWM waveform. This is a phenomenon where a signal with a specific
frequency appears to be a signal with a lower frequency. Let’s demonstrate
this. Let’s go back to the MakeCode program again and modify the code.
Create the program shown in Figure 2.16. The program has a ‘forever’
block, and inside the ‘forever’ block is a ‘repeat’ block, which is found in
‘LOOPS’.

Figure 2.16 Accelerometer data sampled at two different rates

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

approximate intervals of 100 ms it will take a sample of the acceleration.


After 8 times, so after 800 ms, it leaves the repeat loop and follows the next
instruction which is to take a reading of the acceleration again and display
this on the console as the trace 𝑦. This means that the trace 𝑦 shows the
same acceleration sampled every 800 ms.

Both 𝑥 and 𝑦 are recording the accelerometer: 𝑥 with a sampling period of


100 ms, so a sampling frequency of 10 Hz; 𝑦 with a sampling period of 800
ms, so a sampling frequency of 1.25 Hz. According to Nyquist theorem the
sample rate should be greater than 2 Hz if a signal of 1 Hz is going to be
faithfully recorded. Let’s see if that’s true. Run the simulation and look at
the console. Using the mouse, try to produce a waveform of a around 1 Hz
for about 10 seconds. My result is shown in Figure 2.17, where there are
two traces: one for 𝑥 and one for 𝑦.

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.

Figure 2.17 Plotting data collected at two sampling rates

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.

Figure 2.18 A simple pendulum

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.

Please note that, because the weight is brass, it is a good


conductor. If we place the Express directly onto the weight,
then it will short circuits the electronic components and the
Express will be damaged.

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

(a) Attach an M3 screw (b) Attach the 100 g weight

(c) Create a loop in the USB cable (d) Tighten around the eye bolt

Figure 2.19 Attach the Express to the pendulum bob

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.

Because we’ve made something that is more complicated than a simple


pendulum, now that we have the Express and the tether attached, the
equation is of no use for accurately predicting the length that is required. It
does, however, show us the relationship between the period and the
length. If we want the period to be longer, we have to use a longer string.

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

We are ready to record the motion. How we do it depends on what type of


computer you are using, what operating system and whether you have
permission to download and install software. At this point we divide you up,
depending on what hardware and software you have.

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

Figure 2.20 ‘Extensions’ options

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.

(a) ‘DATALOGGER’ blocks (b) ‘STORAGE’ blocks

Figure 2.21 The ‘DATALOGGER’ and ‘STORAGE’ blocks

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

Figure 2.22 A data logging program

‘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

▪ a100‘setmssampling interval’ block, which I’ve used to set a sampling rate of


▪ a ‘data logger’ block which I’ve use to initially turn the datalogger ‘OFF’

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:

▪ an ‘if-then’ block, which checks the value assigned to the variable


‘running’. If the variable ‘running’ is assigned the value FALSE, then
nothing happens, but if it is assigned the value TRUE, then the blocks
inside the ‘if-then’ block are run. These are:

▫ athe‘data logger add’ block, which creates a data entry to be added to


log file, specifying the value of the acceleration in the 𝑥-
direction

▫ 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’

▪ an ‘if-then-else’ block, that checks the value assigned to the variable


’running’. If ‘running’ is assigned the value TRUE, then the blocks inside
the ‘if-then’ block are run. These are:

▫ 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

Now, download the program to your Express. After downloading, the


program runs, but appears to do nothing, this is because it is waiting for

48
T276 PE1: Microcontrollers 2 Using the microcontroller

Button A to be pressed. Once Button A is pressed it starts collecting data,


and then saving the data to the file ‘log.csv’ every 100 milliseconds.

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.

When your Express is running a program, a new drive called MAKECODE


should appear in your list of memory devices on your computer. This is the
flash memory of the Express, and it should include a sub-folder called
SPIFLASH. When you open SPIFLASH you should find your file ‘log.csv’ as
illustrated in Figure 2.23(a).

(a) The SPIFLASH folder (b) The contents of ‘log.csv’

Figure 2.23 Extracting data from the Express

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

Figure 2.24 Creating a graph of the acceleration data

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.

The MakeCode app


This task shows how we can capture data using the MakeCode app. You can
then open the data using Excel and copy it to your computer. For this task
we will need to download the MakeCode app which currently is only
supported on Windows 10. So, if you do not have Windows10, or do not
have permission to download and install software, you should instead do
Task 2.5.

Download the app


Up to now you have been using MakeCode via an Internet site. MakeCode
is also available as a piece of software or as an app in its own right. The
reason I want you to download the app is because it has some extra
features that are currently not available on the online version of MakeCode.

Note that things change quickly, and this includes the


software that is available for the Express. At the time that
I’m writing this activity, the features I want you to use are
only available on the App version of MakeCode. By the time
you carry out this activity that might have changed.

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.

Figure 2.25 Download the MakeCode app

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.

Figure 2.26 Writing acceleration data to console

Download the program to your Express


I now want you to download the program to the Express. You’ll see that
there is a difference between the web-based software and the app. Unlike
the web-based version, to get your program into the Express you just have
to click on the large button labelled ‘Download’. You don’t have to reset the
Express (usually!). Try it now.

After downloading the program, another button appears under the


simulator. The new button says, ‘Show console Device’. Try clicking on it
and you’ll see the plotter and the screen again, but this time it is showing
data from the Express and not the Simulator. So, if you shake the Express
(which should be attached to your pendulum), you can see the
accelerometer values change.

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

Figure 2.27 Console trace of accelerometer data

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

Figure 2.28 Exporting data from the console to Excel

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:

▪ it is easier to download the program to the Express


▪ the console can be used to display and save data from the Express
You are now ready to put your learning into practice in Task 2.7.

Programming a step counter


This Task is not compulsory but is a useful way to consolidate your learning
so far. In other words, you don’t have to do it now or at all. You may like to
come back to this at the end if you have some free time and are interested
in doing more programming or come back to it at some time in the future
when you’re bored!

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.

Here’s some help:

When you are walking or jogging, the measurements from an


accelerometer should look roughly like a sinewave, certainly a periodic
wave that goes up and down. In previous activities where you’ve used the
accelerometer, you’ve always used the 𝑥 value. The accelerometer actually
produces three values 𝑥, 𝑦 and 𝑧. With the Express oriented so that it is flat
on the table with the USB port on the opposite side from you, the 𝑥
direction is left to right and the 𝑦 direction is forward and backward, and
the 𝑧 direction is vertically up and down.

There is also a fourth value that you can use which is called ‘strength’,
which is given by

strength = √𝑥 2 + 𝑦 2 + 𝑧 2

‘Strength’ doesn’t have direction, but it is a measure of the magnitude of


the total acceleration.

If you took measurements of the accelerations when the accelerometer is


not moving, you would find that the strength is not zero when the Express
is stationary. If you looked at the 𝑥, 𝑦 and 𝑧 values individually you would
find that:

𝑥=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

This means that using strength as a measure of motion requires


normalisation to take into account the effect of gravity. To avoid this I
suggest that you carry on using the 𝑥 value, and when you hold the Express
and jog on the spot you hold it such that the 𝑥-direction is vertical i.e. you
hold the Express on its side with the USB pointing either backwards or
frontwards.

Now to measure steps. If you think of the data as a sinewave, then it is


periodic. One period of that sinewave corresponds to one step, so you have
to be able to count the periods of the waveform.

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.

In a program, that means what we have to do is read the current value of


the acceleration and compare it to the previous value of acceleration.

Let’s call the current value of the acceleration ACC. Let’s call the previous
value of acceleration OLD_ACC.

In the program we want something like:

IF (ACC > 0 and OLD_ACC < 0) THEN (Add 1 to Steps)

ELSE (do nothing)

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:

IF (ACC > 30 and OLD_ACC < -30) THEN (Add 1 to Steps)

ELSE (do nothing)

This means that the acceleration has to have a significant change before a
step is counted.

54
T276 PE1: Microcontrollers 2 Using the microcontroller

In our program we need to do something like this:

On Start:

OLD_ACC = 0

Steps = 0

Forever:

Read in the value of the acceleration

IF (ACC > 30 and OLD_ACC < -30) THEN (Add 1 to Steps)

ELSE (do nothing)

OLD_ACC = ACC

So, we initialise the number of steps and the value of OLD_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.

Figure 2.29 Excel file showing the step count

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

3 Analysing the frequency spectrum


Using either the simulator or the actual device with a pause of 50 ms,
collect accelerometer data for a duration of about 80 seconds following
four different patterns:

▪ 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

▪ approximately 20 seconds of constant positive or negative values by


just holding the Express in one position

▪ about 20 seconds of erratic behaviour including slow variations and


high-frequency bursts

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.

Now, download the collected data and open it in an Excel spreadsheet,


making sure that there are more than 1024 samples, but not much more
than that. Ideally, it should not be more than about 1500 samples.

After downloading my data as a spreadsheet, I found that I have 1153


samples of data.

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.

Figure 3.1 Excel file showing the different patterns

The waveform clearly shows four distinct patterns: oscillation, oscillation


with increased frequency, constant value, and erratic behaviour. And there
are at least 256 samples in each of those patterns.

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:

▪ what are the most prominent frequency components in the spectra?


▪ how do the four spectra differ qualitatively from each other?
In the first spectrum the most prominent frequency components is
approximately 0.73 Hz, in the second spectrum the most prominent
frequency components is approximately 1.32 Hz, in the third spectrum the
most prominent frequency components is at the zero frequency, and in the
fourth spectrum there is a prominent frequency component around 0.14 Hz
and a broader frequency feature around 0.6 Hz, and an even broader but
weaker frequency features between 1.3 Hz and 2.6 Hz.

(a) spectrum of first waveform (b) spectrum of second waveform

(c) spectrum of third waveform (d) spectrum of fourth waveform

Figure 3.2 Spectra of the four separate waveform patterns

Comparing the spectra, the first two show a prominent frequency


component at different frequencies, the third spectrum has only a zero-
frequency component, while the fourth spectrum is more complicated
including broader frequency features.

It is also useful to compute and visualise the overall spectrum of the


waveform using 1024 samples. The overall spectrum from my data is
illustrated in Figure 3.3. The overall spectrum is computed over 1024
samples and has an increased frequency resolution. The peaks identified in

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?

Figure 3.3 The overall spectrum

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.

You will reuse your equipment; please be careful as you


disassemble your pendulum so that you do not lose any of
the nuts and bolts. When finished, put all the parts
somewhere safe for future use.

60

You might also like