En v1.0 LW Programming Microcontroller
En v1.0 LW Programming Microcontroller
TP 1015/1016
Workbook
Festo Didactic
8094009 en
Order no. 8094009
Edition: 06/2018
Author: Matrix Technology Solution Limited
Layout: Frank Ebel
The purchaser shall receive a single right of use which is non-exclusive, non-time-limited and limited
geographically to use at the purchaser's site/location as follows.
The purchaser shall be entitled to use the work to train his/her staff at the purchaser's site/location and
shall also be entitled to use parts of the copyright material as the basis for the production of his/her
own training documentation for the training of his/her staff at the purchaser's site/location with
acknowledgement of source and to make copies for this purpose. In the case of schools/technical
colleges and training centres, the right of use shall also include use by school and college students and
trainees at the purchaser's site/location for teaching purposes.
The right of use shall in all cases exclude the right to publish the copyright material or to make this
available for use on intranet, Internet and LMS platforms and databases such as Moodle, which allow
access by a wide variety of users, including those outside of the purchaser's site/location.
Entitlement to other rights relating to reproductions, copies, adaptations, translations, microfilming and
transfer to and storage and processing in electronic systems, no matter whether in whole or in part,
shall require the prior consent of Festo Didactic.
Table of contents
Use for intended purpose __________________________________________________________________ IV
Preface _________________________________________________________________________________ IV
Work and safety instructions ________________________________________________________________ VI
Information for trainers/instructors and apprentices/students ___________________________________ VIII
Required components _____________________________________________________________________ IX
Learning objectives ________________________________________________________________________X
Practical exercises
The products included in the learning system for microcontroller systems may only be used:
For their intended use in teaching and training applications
When their safety functions are in perfect condition
The products included in Festo Didactic’s learning system for microcontroller systems are designed in
accordance with the latest technology and recognized safety rules.
The learning system from Festo Didactic has been developed and produced exclusively for basic and further
training in the field of microcontroller systems. The training company and/or trainers must ensure that all
apprentices observe the safety precautions described in this workbook.
Festo Didactic hereby excludes any and all liability for damages suffered by apprentices, the training
company and/or any third parties, which occur during use of the equipment sets in situations that serve any
purpose other than training and/or vocational education, unless such damages have been caused by Festo
Didactic due to malicious intent or gross negligence.
Preface
Festo Didactic’s learning system for microcontroller systems is geared towards various educational
backgrounds and vocational requirements.
The training system is continuously updated and expanded in accordance with developments in the field of
education, as well as actual professional practice.
These learning solutions encompass a wide range of topics which are directly related to microcontrollers
and the integration and study of additional components and topics including inpuit/output devices, use of
sensors, actuators and motors, relays and more. Instructors can easily expand the scope of learning by
selecting other components available.
All of the systems are modular, thus permitting expansion and flexibility.
Hardware
The hardware included is comprised of rugged, industrial components and systems that are specially
designed for training purposes. The components are specifically designed and matched to the projects in
the accompanying media.
The workbook is available in English. Software is available in several languages. They are intended for use in
classroom instruction, but are also suitable for self-study.
Note
The full rights of use are in compliance with the stipulations included in the legal notice of the
purchased workbook.
General
Apprentices should only work with the circuits under the supervision of an instructor.
Observe the specifications included in the data sheets and operating instructions for the individual
components and, in particular, all safety instructions!
Faults which may impair safety should not be generated.
Wear personal safety equipment (safety glasses, hearing protection, safety shoes) when working on
circuits.
Provide the trainer/instructor with confirmation that you have read and understood the safety
instructions and warnings by affixing your signature. You are only authorized to participate in the
laboratory event after appending your signature.
Mechanical safety
Switch off the power supply.
– Switch off working and control power before working on the circuit.
– Only reach into the setup when it’s at a complete standstill.
– Be aware of potential overtravel times for the drives.
Mount all of the components securely on the profile plate.
Make sure that limit valves are not actuated from the front.
Risk of injury during troubleshooting.
Use a tool such as a screwdriver to actuate limit switches.
Set all components up so that it’s easy to activate the switches and interrupters.
Follow the instructions about positioning the components.
Electrical safety
Disconnect from all sources of electrical power.
– Switch off the power supply before working on the circuit.
– Please note that electrical energy may be stored in individual components. Further information on
this issue is available in the data sheets and operating instructions included with the components.
Use protective extra-low voltage only: max. 24 V dc.
Establishing and disconnecting electrical connections
– Electrical connections may only be established in the absence of voltage.
– Electrical connections may only be disconnected in the absence of voltage.
Use only connecting cables with safety plugs for electrical connections.
When laying connecting cables, make sure they’re not kinked or pinched.
Do not lay cables over hot surfaces.
– Hot surfaces are identified with a corresponding warning symbol.
Make sure that connecting cables are not subjected to continuous tensile loads.
Devices with an earth terminal must always be grounded.
– If a ground connection (green-yellow laboratory socket) is available, it must always be connected to
protective earth. Protective earth must always be connected first (before voltage), and must always
be disconnected last (after voltage).
– Some devices have high leakage current. These devices must be additionally grounded with a
protective earth conductor.
The device is not equipped with an integrated fuse unless specified otherwise in the technical data.
Always pull on the plug when disconnecting connecting cables – never pull the cable.
Workbook
This workbook is broken down into practical exercises, including numerous programming exercises.
Solutions section
Solutions in text passages appear in red.
Solutions and supplements in graphics or diagrams have a red or gray background.
Additional information for the trainer is identified as “Information for the trainer/instructor”. This
information is not included in the worksheets.
Prerequisites
Basic knowledge in the following areas is required in order to process the exercises in this workbook:
Microcontroller or microprocessors including PIC & Arduino
Understanding of a graphical programming paradigm
The components and software required for processing all of the work assignments are listed below:
After completion of the exercises in this workbook, the student should understand the basic of programming
micro controller
Addressing I/O
Stucture loops (while, )
Decision making ( If, case)
Compiling and downloading
Variable types
Instruction, calculation,
Communicating with devices
Information
Create a program that lights an LED attached to the microcontroller.
This program introduces the topic of how to control a digital output.
The tutorial provides a clear, step by step approach enabling you to create your first program using
Flowcode. It can be run in Flowcode’s simulation mode before compiling to the board for testing
and development.
Note: This tutorial refers to the port settings (ports A and B) as used with PIC. For Arduino users,
please use ports C and D as appropriate. (Port C on the Arduino ’Maps’ to Port A of the Combo
board).
TIP
This can be changed later if you get it wrong.
Goto > Build > Project Options > Choose a Target
and select a target microcontroller from the list
that appears as before.
Outputs
Goto > Component Toolbar > Outputs > LED Array (PCB) > Add to 3D system panel
Create a Flowchart
Move the cursor over the Loop icon, in the Icon toolbar. Click and drag it over to the work area. While
dragging it, the normal cursor changes into a small icon. Move it in between the 'BEGIN' and 'END' icons. As
you do so, an arrow appears showing you where the Loop icon will be placed. Release the mouse button to
drop the icon in between the 'BEGIN' and 'END' boxes.
Output
Loop
– Add an Output icon between the loop on your flowchart in the same way.
– Select Port B.
Input a value of 1.
(You have done this because the LEDs in your 3D system panel are currently attached to port B, so we
are sending the Output to the same port).
Run (F5)
Simulation mode
Stop (Shift+F5)
TIP
Remember to stop your simulation before doing anything else.
(If Flowcode isn’t doing as you expect, check that you haven’t accidentally left your simulation
running).
Save your program and then Compile to chip to test on the board. You should see the first LED light up.
Select the Compile to chip image from the menu as shown, or Goto > Build > Compile to chip
Save (Control+S)
Compile to chip
Lower row LEDs
Select the Compile to chip image from the menu as shown, or Goto > Build > Compile to chip
Upper row LEDs
Run in simulation mode and then compile to chip. You should see the first LED of the other row light up.
You can practise changing the ports by changing them back to port B.
Change the value from 1 to 255. Test in simulation mode and then compile to chip (all 8 LEDs light up).
Experiment using other values.
TIP
See Number Systems Worksheet.
9 1001
10 1010
Binary Value
16 8 4 2 1
In binary, the same thing happens, but a lot more often, because it uses only 0s and Decimal Same in
1s. Counting up starts with 0, then 1, then back to 0 with a 1 in front, making 10 (not binary
ten - it's two) Next comes 11 (three) and start again with two 0s but with a 1 in front,
1 1
to give 100 (four) and so on.
2 10
Notice that each time the binary 1 moves one place to the left, it doubles in value of 4 100
the number in decimal. 8 1000
TIP
In any binary number, the bit at the left-hand end, the Most Significant Bit (MSB), has the highest
value. The one at the right-hand end, the Least Significant Bit (LSB), is worth least.
Hex Numbers
Hexadecimal, 'hex' for short, is a another system for representing numbers.
A binary digit is either 0 or 1.
A decimal digit varies between 0 and 10.
Sixteen states is a problem, as we have only the digits from 0 to 9. To get round this, we use the letters A to
F to provide the additional six digits required.
Working with the binary number with eight digits is a handy convention as computers (and the PIC MCU)
store information in groups of eight bits.
A single memory cell inside the PIC MCU can store a number ranging from 0000 0000 and
1111 1111. In decimal this range is 0 to 255. The equivalent in hex is 0 to FF.
TIP
You can enter a hex number into Flowcode by preceding it with '0x' in any of the dialogue boxes.
A single memory cell inside a PIC device can store a number ranging from 0000 0000 and 1111 1111. In
decimal this range is 0 to 255. The equivalent in hex is 0 to FF.
Information
A large building has a number of heat sensors in
its fire alarm system. When there is a fire, the fire
brigade needs to know where the fire is. In other
words, they need to know which heat sensor has
triggered the alarm.
The system is controlled by a PIC MCU. There are
five heat sensors, connected as inputs to port A.
Port B is set up as the output port and connected
to a set of five LEDs. If a heat sensor detects a
fire, the corresponding LED lights up.
Drag the Loop icon, the Imput icon and the Output
icon into your Flowchart from the icon toolbar to
create a Flowchart as shown.
2. More on variables
In the previous section you added a variable to the
program using the variable dialogue box.
Computer signals consist of streams of binary 0s
and 1s on each wire. A group of eight wires can
carry eight bits, (binary digits) simultaneously. This
grouping of eight bits, known as a byte is used for
much of the internal wiring inside microcontrollers
and for the registers that hold and process data.
It is also used within memory subsystems. The
contents of a memory register having eight bits can
vary from 0 to 255.
A variable inside Flowcode can be configured to use
just one memory register or more than one.
3. Flowcode variables:
a) Flowcode offers eight different types of variables:
b) a Bool (Boolean) variable can either be 1 or 0 (true or false).
c) a single register, known as a Byte variable, can store numbers from 0 to 255.
d) a double register, known as an Int variable, can store numbers from -32768 to +32767.
e) a double register can also be unsigned, when it is known as a UInt variable, which can store numbers
from 0 to 65535.
f) a quad register, known as a Long variable, can store numbers from -2147483648 to 2147483647.
g) a quad register can also be unsigned, when it is known as a ULong variable, which can store numbers
from 0 to 4294967295.
TIP
Use a Byte variable for simple counters and for variables that will not go above the value 255. It is
the most economical in terms of memory space and also the fastest. Mathematical processes
involving two bytes (often referred to as 16 bit arithmetic) take longer to execute. A multiple
register, known as a String variable, can consist of a number of Byte variables - the default in
Flowcode is 20.
Finally an object handle is used to reference a more complicated piece of data (such as a file, component or
a block of text) whose internal format is not known.
2. Why worry?
The number of registers inside a microcontroller is limited, and in larger applications the number and types
of variables must be managed carefully to ensure that there are enough.
On downloading a program, the variables in Flowcode are implemented in the Random Access Memory
(RAM) Section of the PIC MCU. In the 16F18877 there are 4096 Bytes of memory. This means you can have
4096 Byte variables, 2048 Int variables or 204 Strings each consisting of twenty Bytes or characters.
The plan is straightforward - when a sheep passes through the gate, it breaks a light beam. This sends a
pulse to a counting system, which then adds one to the total stored in the system.
(Note that Flowcode has a Beam Breaker component, based on the Collision Detector. Although this would
do a far better job, for now we detect the light beam interruption using more basic methods).
Note
For Arduino users, please use ports C and D
as appropriate.
e) Hover over Variable in the project explorer panel and click on the arrow to Add new. You now see the
Create a New Variable dialogue box. Type in the name SHEEP and then click on ‘OK’. You can leave the
variable type as Byte as there will not be that many sheep.
f) Create a variable named TOTAL in the same way.
f) The Input properties are set up to store whatever number appears on port A in the variable called
SHEEP. Initially, that number is 0. When the switch is pressed, the number on port A and stored in the
variable SHEEP is 1 (with only one switch, the biggest number we can create on port A is 1).
g) When the Calculation icon is executed, the number stored in the variable SHEEP is added to the TOTAL
variable. Hence, when a sheep breaks the light beam, TOTAL is increased by 1. With no sheep present,
TOTAL remains unchanged.
h) Click on the ‘OK’ button, to close the dialogue box
5. When to test?
You can configure the properties to test the loop condition either at the start of the loop or at the end.
Understanding this option is important. It can affect the number of times that the program will loop.
Note
Arduino use PORTC.
Note
For Arduino users, please use ports C and D as appropriate.
Before we have time to release the switch, the program has run through several times, adding one to the
total each time. We need to slow it down by adding a delay.
Note
This program shows the total
number of sheep in binary format.
Layout
1. LCD displays
Flowcode comes with a number of components that add commonly used subsystems to Flowcode, such as
the LCD display, 7-segment display, and analogue inputs devices.
Here, we look at the LCD display, the basic text display subsystem on a range of electronics devices, from
calculators to mobile phones. It can display text or numbers on one or more rows of the display.
In most programming languages, the LCD is one of the last things you learn, as it is quite a complicated
device to program. However, Flowcode takes care of the complexities, making the LCD simple to use. The
LCD display referred to here is the one used on the E-Blocks Combo board and on the LCD display - a four
row, twenty character display.
At the top of the Properties pane, the Component section identifies the component you have just selected.
By default, the LCD is added to port B.
The LCD display requires five connections. It displays letters and numbers conveyed as serial data on this
five wire bus. The techniques involved go beyond this tutorial. Fortunately, Flowcode has some embedded
routines that take care of the complexities.
3. Writing messages
To display text on the LCD, simply type it in.
a) Add another Component Macro to the
flowchart and open the macro dialogue
box.
b) Select the LCD macro called PrintString.
This requires a single parameter (item of
data), 'Text' (the text to be printed).
c) Type the text into the parameter box
surrounded by quotation marks, e.g.
"Hello World"
d) Run the program and the text will be sent
to the LCD display.
5. Using PrintNumber
Altogether we will add four Component Macros to the flowchart.
a) To the first Component Macro add Start.
b) To the second select PrintString and add "Hello World" (with quotation marks).
c) To the third select Cursor and add 0,1 to the parameters.
d) To the fourth select PrintNumber with the parameter value as 123.
e) Click Run to simulate the program.
TIP
Try changing the values of the Cursor parameters and see where the numbers print.
The ‘y’ value needs to be between 0 and 3 and the ‘x’ value needs to be between 0 and 19
(between 3 and 17 to see all three figures 1 and 2 and 3).
Layout – overview
Work assignments
a) Expand the program from the previous example (Using PrintNumber) by dragging a Loop icon below the
PrintString Component Macro.
b) Change the text in the PrintString Component Macro to "Hundredths" (with quotation marks).
c) Drag a Calculation icon into the Loop.
d) Create a variable called Count as an Int type (Initial value 0).
e) Double-click on the Calculation icon. In the Calculations text box type Count = Count + 1
f) (This will add 1 to the value of variable count every time the icon is executed).
g) Next drag another Component Macro into the Loop.
h) Double-click the Component Macro and find Cursor under the LCD macros.
i) Enter 0,1 as parameters to position the cursor on the first character of the second line.
j) Next, drag another Component Macro onto the workspace.
k) Select PrintNumber and enter Count as the parameter.
l) Now, drag a Delay icon into the flowchart and set the delay to 10ms (which equals one hundredth of
a second).
m) The counter will count (approximately) the time elapsed in hundredths of seconds.
TIP
You can refine the program by clicking on each icon and entering comments to describe what the
icon does.
It may seem like a lot of effort, but it can help with more complex programs.
To see the result of the calculation, we will use an LED array, connected to the output port.
We need a microcontroller with three ports.
Layout – overview
Note
For Arduino users, these two Ports will need to be set as follows:
Input 1 set to PORTC (to use the Port A switches on the Combo board).
Input 2 set to PORTD (to use the Port B switches on the Combo board).
8. Slow simulation
As described earlier, Flowcode allows you to progress through the flowchart one step/icon at a time, to see
the effect of each on the variables and on the output.
a) There are three ways to simulate the program step-by-step:
1. Click on Run on the Main toolbar and on the Step Into button (Run > Step Into)
2. Press the F8 function key on the keyboard.
3. Click on the Step Into button on the main toolbar in the simulation section.
b) Set up the number 000 1111 (fifteen) on the switches connected to port C.
c) Now Step Into to the next icon in the program by, for example, pressing F8 once more.
d) The red rectangle moves on to the next icon, the Loop icon, but little else happens.
e) Press F8 once again. The red rectangle moves on to the first Input icon.
f) Press F8 again and the Variables box shows that the input1 variable now contains eleven (the result of
the Input instruction just carried out).
g) Press F8 again and the Variables section shows that input now contains fifteen.
h) Press F8 again and the calculation is carried out. The sum variable stores the result.
i) Press F8 again. The value stored in sum is transferred to the LED array.
j) It looks like:
k) Reading from the most significant bit (D6) to the least significant bit (D0), the LED array shows the
number 001 1010. In decimal, this is the number 26. No surprises there then.
l) Repeat the same procedure using different numbers and step through the program to check what the
sum of the numbers is.
TIP
TIP: Explore adding graphics to your binary calculator to make it easier to read.
Goto > Shapes > Labels to add digits above your LEDs.
Very often, these are of the form "If this AND this is true, then..." or "If this OR this is true, then...". They
rely on specific combinations of circumstances in order to take some particular action.
They are examples of using binary logic. The answer to the “If…” question is either “Yes” / “No”, or “True” /
“False”, i.e. one of two possibilities (a binary solution). This answer could be expressed as a logic 0 or a
logic 1 and electronically by a high voltage or a low voltage.
There is a class of digital electronic components, called logic gates, that perform exactly these decisions.
The inputs and output are logic 0 or logic 1.
For reasons of safety, a microwave oven has a door sensor to make sure that the microwave generator will
not operate if the door is open. Put another way, the generator operates if the door is closed AND one of the
heating control switches is pressed.
1. Setting up a flowchart
Launch Flowcode with a new flowchart.
Create the flowchart shown opposite. It uses:
a) a loop icon
b) two input icons
c) three output icons
d) two decision icons
e) two calculation icons
f) a delay icon.
Note
For Arduino users, the Ports need to be set to PORTC and PORTD (equivalent to A and B on the
Combo board).
Very often, these are of the form "If this AND this is true, then..." or "If this OR this is true, then...". They
rely on specific combinations of circumstances in order to take some particular action.
They are examples of using binary logic. The answer to the “If…” question is either “Yes” / “No”, or “True” /
“False”, i.e. one of two possibilities (a binary solution). This answer could be expressed as a logic 0 or a
logic 1 and electronically by a high voltage or a low voltage.
There is a class of digital electronic components, called logic gates, that perform exactly these decisions.
The inputs and output are logic 0 or logic 1.
Layout – overview
1. Setting up a flowchart
Launch Flowcode and start a new flowchart.
The calculation icon checks to see whether either door has been opened AND the ignition switch is NOT on.
Note
For Arduino users, please use ports C and D as appropriate.
Now simulate the program step-by-step, using the F8 function key repeatedly.
Check what happens for different combinations of open doors and ignition switch states.
Interpret the behaviour in terms of the behaviour of the interior light. What happens, for example, if the door
is opened and then closed shortly after? Is this behaviour correct?
Information
The Programming Exercises are presented here as flexible tasks suitable for further development.
Small, individual tasks can be developed into larger scale projects if desired. Try out the ideas, test them,
experiment, develop your skills and see what you can create.
The aim of the exercises is to develop experience in using Flowcode and in the process, develop
understanding of the programming terminology and techniques it embraces.
Programs can be tested by simulating them in Flowcode, but also downloaded to a microcontroller and
tested on hardware. It is generally assumed that the programmer is using a Microchip PIC MCU though the
exercises are equally applicable to other microcontrollers.
The section ends with further Challenges. These are even more open-ended and contain only a brief
specification.
Objectives
Change the logic level of a one single pin of a port.
Send different 8-bit codes to the port of a microcontroller.
Configure an Output icon.
Use binary code.
Manipulate logic output levels.
Use LEDs to display an output.
Compile a program to a microcontroller.
Tasks
2. Write a program that uses at least twenty Output icons to write different values to port B, one after
the other. Use all four methods in this exercise - hexadecimal, decimal, single bit and masking.
Simulate the program and review the results. (Save the program and download it to the
microcontroller).
TIP
Restart the program a number of times by pressing the Reset button on the programmer board.
Information
In this exercise, you learn how delays are used to slow down program execution. Microcontrollers work
extremely quickly - typically executing about 5,000,000 assembly instructions, every second.
A human can detect and understand only around three stable images per second.
To allow a high-speed microcontroller to communicate with ‘slow’ humans, we sometimes need
to slow it down by adding Delay instructions.
Objectives
Add a delay to slow down execution of a program.
Change the delay interval.
Configure a delay icon.
Control the speed of a microcontroller.
Use an oscilloscope to time events .
Tasks
1. Begin by opening the program created in the last exercise (Exercise 7-1).
a) Add Delay icons and configure them so that the output states can be viewed comfortably even at
‘HS oscillator’ speed.
b) Save the program and download it to the microcontroller, testing the program on the E-blocks
boards.
TIP
Do not test this in simulation mode - simulation timing is not always accurate because it runs under
a Windows operating system and not in ‘real time’.
Information
A Connection Point, or ‘goto’ instruction, is often used to create an infinite loop - to repeat a set of
instructions over and over again (a better way to do this is to use a ‘Loop’ instruction). The advantage of a
Connection Point is that it can be used to jump out of a loop to a certain location in the program. The idea of
pulse-width modulation (PWM) is introduced as a means of controlling LED brightness.
Objectives
Use Connection Points to introduce unconditional branching in a program.
Introduce PWM as a means of controlling the brightness of LEDs.
Create an infinite loop.
Manipulate logic output levels.
Use LEDs to display an output.
Tasks
1. Write a program to see if you can
a) Use Delay, Output and Connection Point icons to light the even and odd LEDs of an array alternately
on and off. Use a 300ms interval between, in an infinite loop.
(Test the program at first ‘step-by-step’ and then continuously in the Flowcode simulator).
b) Use Delay, Output and Connection Point icons to flash the high nibble and low nibble LEDs
alternately on and off, with a 300ms interval between, in an infinite loop.
c) use Delay and Output icons to flash all the LEDs of the array on and off with a 500ms interval in
between, in an infinite loop.
d) Modify the program by changing the ‘on’ and ‘off’ times in such a way that the total
(‘on’ + ‘off’) time is unchanged, e.g. on for 12ms and off for 8ms. What is the difference?
(Download programs to the microcontroller and test them).
TIP
Make the last delays very short and make the on and off times asymmetrical,
(e.g. on for 8ms and off for 12ms).
This is a software PWM generator. When you run it, the intensity of the LEDs is lower.
They flash on and off too fast for our eyes to observe. Instead, we see the intensity change.
TIP
The MSB is the left-most bit and the LSB is the righ-most bit.
Information
Modern microcontrollers, like the PIC MCU or Arduino, are able to do simple mathematical tasks with 8-bit
numbers at very high speed. As the calculations get more complex or the numbers rise above an 8-bit value,
then the execution time lengthens dramatically. Flowcode allows complex calculations using up to 16-bit
numbers and takes care of all the complexities. However, these may slow down execution of the program.
Objectives
Create and use a variable.
Configure a calculation icon to perform arithmetic and logic calculations.
Create and manipulate variables.
Perform calculations.
Use LEDs with current limiting resistors.
Tasks
2. Modify your program to display the result of the following calculations on the LEDs of port B:
a) 45 + 52;
b) 45 AND 52;
c) 45 OR 52;
d) NOT 45;
e) (1+3)*(6/2);
f) VAR2 = VAR1 * 3 (where variable ‘VAR1’ stores the number 18).
(On paper, check if the results are correct).
Information
Objectives
Create and use a ‘running light’ program, using the ‘multiply-by-two’ method.
Create and use a ‘running light’ program, using the ‘shift-right’ method.
Create and populate an array.
Create a conditional loop.
Tasks
TIP
Use two loops inside an infinite loop so that the process repeats indefinitely.
(Download the program to the microcontroller and test it at full speed).
2. Do you know KITT From Knight Rider or the Cylon robots from Battlestar Galactica?
Write a program to make a simple ‘running light’ that runs from port B, bit 0 to port B bit 7 and then
back to port B bit 0, repeatedly.
a) Try using the ‘multiply-by-two’ method.
b) Try using the ‘shift right’ method.
Modify your program to create a 16-bit running light, using the LEDs from port A and B.
TIP
Use only loops, no decisions. (Download the program to the microcontroller and test it).
3. Create a flowchart that contains an array of four variables, called ‘Matrix[x]’ which stores the
following values: Matrix[0] =129 Matrix[1] =66 Matrix[2] =36 Matrix[3] =24 (Display the
outputs on the LEDs of port B).
a) Use two ‘do-while’ loops to create an infinite sequence:
b) Matrix[0]-Matrix[1]-Matrix[2]-Matrix[3]-Matrix[2]-Matrix[1]-Matrix[0]-Matrix[1]-..... ;
c) Refer to the four variables as ‘Matrix[x]’ where ‘x’ is a separate variable, known as the index of the
array.
(Download the program to the microcontroller and test it).
Information
Adding digital inputs to a microcontroller circuit is quite easy but is a big step forward. This allows external
signals to influence how the program reacts.
Objectives
Input data from switches.
Use loops to create LED sequences.
Configure an input icon.
Tasks
1. Write a program to show the status of the switches connected to a chosen port, on the LEDs
connected to a different port. eg. when a switch is pressed connected to port A, the corresponding LED
on port B lights.
Modify the program so that:
d) the LED stays lit for 2s.
e) when switch ‘0’ is pressed, LED 1 is lit.
f) when switch ‘1’ is pressed, LED 2 is lit and so on.
g) when switch ‘7’ is pressed, nothing happens.
Information
Earlier programs included simple decision-making, using loops and connection points. Now we look in detail
at the Decision icon, widely known as the ‘if…then…else’ structure, probably the most widely used command
line in any program.
Objectives
Configure Decision icons and hence add conditional branching to a program.
Control the frequency at which LEDs flash.
Use LEDs to display output logic levels.
Use temporary memory.
Tasks
1. Write a program that uses switches to produce a reversed sequence on the LEDs.
a) when switch ‘0’ is pressed, LED 7 lights up.
b) when switch ‘1’ is pressed, LED 6 lights up.
c) and so on…
2. Write a program that creates an 8-bit counter, counting from ‘0’ to ‘255’ and then back to ‘0’
repeatedly.
a) Use Decision icons instead of Loop icons.
b) Use two switches connected to a chosen port, bits 0 and 1.
c) Count up when switch ‘0’ is pressed.
d) Count down when switch ‘1’ is pressed.
e) Display the current count on the LEDs connected to a suitable port.
(Download the program to the microcontroller and test it).
3. Write a program that counts from 0 to a value stored in a variable called ‘count’ when switch ‘0’ is
pressed and then waits until switch ‘1’ is pressed before counting down to 0.
a) Use two switches connected to a chosen port, bits 0 and 1.
b) Use a different port for the LED array to display the current value of the count.
(Download the program to the microcontroller and test it).
4. Write a program that makes eight LEDs flash on and off at a frequency of 1Hz, i.e. taking one second
for an ‘on-and-off’ cycle. Use two switches connected to a suitable port, bits 0 and 1.
a) The LEDs should flash faster if switch ‘0’ is pressed.
b) The LEDs should flash more slowly if switch ‘1’ is pressed.
(Download the program to the microcontroller and test it).
5. Write a program that makes all eight LEDs in an array light when a switch is pressed the first time
and all go off when it is pressed again.
(Download the program to the microcontroller and test it).
6. A car has two interior lights. One is in the front of the car and one is in the rear.
Write a program to simulate this scenario using LEDs and five switches to control them.
a) Use switches 0, 1, 2, 3 to represent doors being open or closed.
b) Use switch 4 to represent the boot (trunk) being open or closed.
c) Light both LEDs when any door opens.
d) Light only the ‘rear’ LED when the boot (trunk) is opened.
(Download the program to the microcontroller and test it).
TIP
Assume that the switches are closed when the doors are open.
This may be easier to simulate with ‘push-to-make’ switches.
7. A car’s steering wheel has switches on it that control the external lights. Write a program to simulate
the control of the lights.
a) Use a switch to control the left direction-indicator (choose a relevant LED), which flashes on for
250ms and then off for 250ms repeatedly until the switch is released.
b) Use another switch to control the right direction-indicator (choose a relevant LED), in th e same
way.
c) Use two LEDs as brake lights controlled by a switch which light up for as long as it’s pressed.
d) Create headlights which light when a switch is pressed and stay on until it is pressed again.
e) Finish off with a pair of foglights in the same way.
TIP
Don’t attempt to write this program all at once. Divide it into subsections and solve each
separately before putting them all together.
To make it easier, use the labelling feature of Flowcode to label switches and LEDs.
8. Six sheep are allowed to wander between two fields. There are two sensors between the fields. Write
a program that counts and displays the number of sheep in each field. Simulate this scenario using
two switches to represent the sensors.
TIP
Assume that each sheep is longer than the gap between the sensors.
Think about the various scenarios that could happen. A sheep might trigger a sensor and then back
out. Can a sheep trigger both sensors and then back out? When does a sheep count as being in the
east field?
Information
Using LEDs to display outputs can be limiting.
The LCD is an alternative way to display data, both letters and numbers, for ‘non binary’ humans.
Objectives
Control the display of text and numbers on an LCD.
Use an LCD as an output device for the microcontroller.
Configure a Component macro for the LCD.
Tasks
1. Write a program that displays the text “Hello World” in the centre of the bottom line of the LCD.
2. Write a program that shows an increasing count (decimal) on the LCD screen. Modify the program so
that it counts up when a switch is pressed and counts down when a different switch is pressed (use
Loops or Decisions).
3. Write a program to show the status of the switches attached to the first port. Every time a switch is
pressed, the corresponding LED of the second port lights up and the value of the decimal equivalent
is displayed on the LCD.
4. Write a program to show the status of the switches attached to the first port on the LEDs of the
second port and on the top line of the LCD and then:
a) multiply this binary number by 100.
b) display the result on the bottom line of the LCD, with “[x 100 = ]” displayed in front of it.
5. Write a program that scrolls the lines of text given below, one line at a time. Initially, the text is
centred on the bottom line of the display for 2s. Then it moves up to be centred on the top line for 2s,
to be replaced on the bottom line by the next line of text, and so on.
Text:
“There are only”
”10 kinds”
”of people”
“Those who”
“understand”
“BINARY”
“and those who”
“DON’T.”
(Enclose the program in an infinite loop and test on the LCD).
Information
A numeric keypad is used in many electronic devices, and in some (eg. mobile phone), it is used as a
numeric keypad and also as a way to type text instead of numbers. There are twelve buttons on the keypad,
yet the keypad is connected to the microcontroller by only eight lines. This problem is solved by using
multiplexing.
Objectives
Input text and numbers from a keypad and display messages on the LCD.
Use ASCII code to transmit this data.
Use multiplexed inputs.
Configure a Component macro for the keypad.
Tasks
Extend this program so that the secret number is in the range ‘0’ to ‘255’.
Extend the program again so that the secret number is in the range ‘0’ to ‘9999’.
4. Write a program to use the keypad, as on a mobile phone, to input the text to the microcontroller
a) Use ASCII code to transmit the data.
b) Use the character ‘*’ for a space.
c) Clear the display when ‘#’ is pressed.
d) Display a message on the bottom row when the text has more than ten characters.
Information
The 16F18877 PIC MCU accepts 35 separate analogue inputs. Newer devices may have even more. An
analogue signal on one of these inputs can be translated into a 10-bit digital binary number. We can choose
to use only the eight most-significant-bits of this 10-bit number or to use the full 10-bit number.
Be aware that working with 10-bit numbers in an 8-bit microcontroller like the PIC MCU, needs careful
program writing.
Objectives
Create data loggers, using 8-bit and 10-bit data from the ADC.
Configure an analogue input.
Enter data via switches.
Enter information from light and temperature sensors.
Configure and use the EEPROM.
Scroll through EEPROM data.
Display text and numerical data on the LCD.
Use the E-blocks prototype board.
Tasks
1. Write a program to display an 8-bit number, equivalent to the analogue input voltage from the light
sensor on the Sensor board. Try connecting a voltmeter to measure the analogue input voltage.
(Save the following programs and download them to the microcontroller for testing).
2. Modify the program from Task 1 to display data from the ‘pot’ on the Sensor board.
Try to convert the ADC 8-bit output into a voltage reading between 0 and 5V, making it as accurate as
the 8-bit mode allows. Use a voltmeter to measure the analogue input voltage.
3. Modify program 2 to display, on the LCD, a 10-bit number equivalent to the analogue input voltage
from the ‘pot’ on the Sensor board. Use a voltmeter to measure the analogue input voltage.
Try to convert the ADC 10-bit output into a voltage reading between 0 and 5V, making it as accurate as
the 10-bit mode allows. Use a voltmeter to measure the analogue input voltage.
4. Write a program to monitor the lighting in the room over 24 hour period:
a) using the analogue signal from the light sensor on the Sensor board
b) storing light measurements on the EEPROM.
c) sampling at the highest rate possible, given that the PIC MCU has 256 bytes of EEPROM memory on
board.
d) and displaying each sample with its sample number, on the LCD.
e) by scrolling forwards through the samples by pressing switch ‘0’ or scrolling backwards by pressing
switch ‘1’.
TIP
Increase sampling rate so that you don’t have to spend 24 hours in testing
Information
In code-based programming languages, like C and BASIC, a software macro would be called a subroutine or
function or procedure. As programs get bigger, they use certain combinations of instructions over and over
again. These programs become harder to understand and read. Routines that are re-used can be put into a
software macro, which can be called whenever it is needed in the main program. Making use of these
software macros lightens up the main program and makes it much easier to read.
Objectives
Use software macros to simplify the structure of a program.
Create software macros.
Use closed loop control.
Use PWM to control the brightness of LEDs.
Tasks
1. Write a program that selects and runs one of three different programs by using two switches.
a) switch ‘0’ selects one of three programs (which you developed earlier).
1. ‘X’: an 8-bit binary up-counter, displayed on the LEDs.
2. ‘Y’: an 8-bit binary down-counter, displayed on the LEDs.
3. ‘Z’: an 8-bit bidirectional ‘running light’, displayed on the LEDs.
Information
In earlier exercises, the microcontroller did not necessarily react to inputs straight away because it was busy
doing something else. The external interrupt features of microcontrollers solve this problem. On a
16F18877, the external interrupts are on pin ‘RB0’ - a single pin interrupt and on port B as an ‘interrupt on
change (IOC)’. If these interrupts are initialized correctly, then a change on port B can cause the program to
stop execution immediately and switch to executing the appropriate interrupt macro. We then have what is
called a ‘real time’ execution.
Objectives
Create and use single-pin interrupts.
Create and use interrupt-on-change (IOC) interrupts.
Use real time operation of a microcontroller.
Tasks
1. Write a program to time how many seconds have passed since a program was reset and displays the
result on an LCD. Use a variable called count whose value is displayed on the LEDs (don’t use an
interrupt). Use a 1s delay. A rising edge on pin RB0 should call a macro that adds one to count.
Re-design this program using an interrupt (single-pin) on RB0.
Now re-design it using both kinds of external interrupt so that:
a) triggering the single-pin interrupt increments ‘count’ (count = count + 1)
b) triggering the IOC interrupt decrements ‘count’ (count = count - 1)
TIP
The LCD should display numbers from 1 to 12, one after the other, over and over again rapidly, at 20
ms intervals (much too fast to see with a human eye).
Modify program 3 to limit the time allowed to the size of the used variable and displays a message on
the LCD when this size is exceeded. (Include a trap to prevent cheating by simply holding down switch 0
continuously).
Information
The other type of interrupt function in Flowcode is the timer interrupt. These allow you to perform software
tasks at precisely predetermined time intervals - a really useful feature when developing time critical
applications and clocks.
Objectives
Create and use timer interrupt.
Use the prescaler to create accurate time intervals.
Trigger the timer using the crystal or an external event.
Timer arithmetic
The 16F18877 has several timers, but we look at only two: TMR0 (Timer 0) and TMR1 (Timer 0).
TMR0 can be triggered by the crystal or by a transition on the T0CKI pin RA4.
The internal clock has a frequency of crystal clock frequency/4, i.e. 19,660,800/4 = 4,915,200Hz.
The TMR0 prescaler can be set from 1:2 to 1:256. For this exercise, set it to 1:256, so that every
256 clock pulses cause the TMR0 to increase by 1.
This happens at a frequency of 4.915.200/256 = 19.200Hz.
Every time this 8-bit timer ‘overflows’ (reaches 256), it generates an interrupt. This happens with a
frequency of 19.200/256 = 75Hz, so that the main program is stopped 75 times per second and so
the timer interrupt macro is executed 75 times per second.
Instead of using the crystal, this timer can also be ‘clocked’ by an external event, as when
measuring motor speed etc.
TMR1 can be triggered by the crystal oscillator or by a transition on the T1CKI pin RC0.
(Its operation is similar to that of TMR0, except that it uses different prescaler values).
Tasks
1. Write a program to produce a precise ‘seconds’ timer that displays the result on the LCD and starts
when the microcontroller is reset. Use a 1s delay. Don’t use a timer interrupt.
(Download this program to the microcontroller and test it using your watch).
Rewrite the program using a timer interrupt.
2. Write a program to create a basketball timer that starts when switch 0 is pressed and displays the
time elapsed on the LCD. Make the LEDs flash on and off when 30s has elapsed (the time allowed for
the team with the ball to make a goal attempt).
TIP
Use a single-bit interrupt on pin RB0 to start the timing.
3. Write a program to produce a precise clock that displays the time elapsed since the last reset, in
hours, minutes and seconds on the LCD (test with a watch).
Modify this program so that:
a) switch ‘0’ stops the clock when pressed the first time.
b) switches ‘1’, ‘2’ and ‘3’ can be used to change the displayed time to the actual time.
c) switch ‘0’ restarts the clock when pressed a second time.
4. Write a program to produce a timer that counts down from 01:00:00 to 00:00:00 in seconds and then
lights all the LEDs.
(Download to the microcontroller and test it with your watch).
Information
To realize the following exercises, it is necessary to have the following accessories, which
are not included in the TP kits. Accessories for additional exercises:
1. Develop a dimmer for all the LEDs that reacts to measured light intensity.
a) The light sensor monitors the light intensity in a room. When this intensity drops, a control circuit
sends more power to the lights in that room and vice versa when the intensity increases.
b) Use the LEDs to simulate the dimmed lights. This is done by programming a software PWM output
to all LEDs on port B. When the PWM ‘on’ time increases, the LEDs get brighter, etc.
c) Put this program in a timer interrupt macro.
d) The main loop monitors the analogue input from the light sensor on the sensor board, on port C.
When the light sensor detects less light, the LEDs need to shine brighter. The opposite should
happen with the LEDs when the light level, measured by the light sensor, intensifies.
e) The period of the PWM signal stays a constant 20ms at all times, set using a timer interrupt.
f) Download this program to the microcontroller and test it. If you have a 2 channel oscilloscope,
measure the analogue input of the light sensor on one and the PWM output to one of the LEDs on
the other.
g) Using a similar approach, develop a temperature controller for an incubator. The Grove Sensor
board can be used with the Grove Temperature sensor module. Use the LEDs to simulate the action
of a heater.
2. Three judges vote on variety acts in a X-factor-like game show. When two or more judges vote ‘Yes’,
the act progresses to the next round.
a) Design a program to combine the judges’ votes into a pass/fail verdict.
b) Create two LED light sequences, one to indicate pass and the other fail.
3. Design an automatic watering system for a sealed terrarium (glass plant container). Use the Grove
Temperature and Humidity sensor module to sense when the terrarium needs watering.
a) The output device is a motor-driven pump that runs for a set period of time once triggered.
There should be a ‘rest’ period after watering before the system can operate again.
4. Create a combination lock, using the Keypad board to input a four-digit ‘PIN’.
a) Add a feature that ‘locks out’ a user after three unsuccessful attempts.
b) Modify it to prevent further access to the system for a period of time such as ten seconds.
c) Use the LCD display to show the numbers selected on the keypad and the number of attempts
made
5. Develop a proximity switch for a security light using the Grove Ultrasonic Ranger sensor module. The
system should switch on four lights (12V lamps) when a person approaches within one metre of the
sensor and so makes use of the Relay board.
6. Use the Grove Infrared Receiver sensor module to time the swing of a pendulum without impeding it.
7. Design a system to drive the DC motor (and sensor) on the Actuators training panel at a steady speed.
Add a feature to modify this set speed.
8. Design a system to drive the stepper motor on the Actuators training panel so that it rotates, in 150
steps, through one complete circle and then reverses back to its initial position in the same manner.