Manual FlowCode
Manual FlowCode
Manual FlowCode
CP4375-3
Contents
Sec on 1: Introduc on to microcontrollers
Sec on 2: Using E-blocks
Sec on 3: Introduc on to Flowcode
Sec on 4: Flowcode - first program
Sec on 5: Flowcode examples
Sec on 6: Programming exercises
Appendix 1: Arduino adjustments.
Appendix 2: BTEC Na onal level 3 unit 6 mapping
Introduc on Introduc on to microcontrollers
Introduc on
The aim of this course is to introduce you to the concepts of developing electronic systems using
microcontrollers.
In doing so, it offers substan al coverage of Unit 6 of the BTEC Level 3 Na onal Extended Diploma in
Engineering (the precise mapping of the course to this unit is given on page 9).
BL0011 programmer.
While most of the course is designed around the E-blocks2, we also recognise that some people may be
using either an Arduino device. So in this course, whenever there is change in the instruc ons for Arduino
changes, they will be displayed in the following colours:
Arduino users need an Arduino Uno and E-blocks Arduino Uno Shield (BL0055), as well as the Combo
board.
Introduc on Introduc on to microcontrollers
Ge ng more Informa on
Flowcode
h ps://www.flowcode.co.uk
From here you can access:
- Flowcode—Ge ng Started Guide
- Flowcode Wiki
- A wide range of Flowcode examples
E-blocks
h ps://www.matrixtsl.com/eblocks/resources
In the E-blocks sec on you can get the follow resources:
- E-blocks USB Drivers
- E-blocks example files
- E-blocks User Guide
h ps://www.matrixtsl.com/eblocks/boards
From the boards pages:
- Specific datasheets for the boards
- Specific board examples
Other Help
h ps://www.flowcode.co.uk/forums/
The Matrix forum provides an in-depth community of well established, long-term users of Flowcode and
new Flowcode users sharing ideas and solving problems and issues encountered whilst using the
so ware.
h ps://www.matrixtsl.com/learning/
The Matrix ‘Learning Centre’ contains many different resources including ar cles, drivers, curriculum.
Introduc on Introduc on to microcontrollers
The hardware:
Most exercises use the BL0011 / BL0080 Mul programmer and BL0114 Combo board.
Most of the exercises can also be completed using the Arduino Uno Shield (BL0055). However, these
require different PORT se ngs.
1. Send different 8-bit codes to ports of the 31. Control the frequency at which LEDs flash.
microcontroller. 32. Use LEDs to display output logic levels.
2. Change the logic level of a one single pin. 33. Use temporary memory.
3. Configure an output icon. 34. Create, populate and manipulate string
4. Use binary code. variables.
35. Control the display of text and numbers on a
5. Manipulate logic output levels. LCD.
6. Use LED’s to display an output. 36. Use a LCD as an output device for the PIC
7. Compile a program to the PIC MCU. MCU.
8. Add a delay to slow down execu on of a 37. Configure a Component macro for the LCD.
program. 38. Input text and numbers from a keypad and
9. Change the delay interval. display messages on the LCD.
10. Configure a delay icon. 39. Use ASCII code to transmit this data.
11. Control the speed of a microcontroller. 40. Use mul plexed inputs.
12. Use an oscilloscope to me events. 41. Configure a Component macro for the keypad.
13. Use Connec on Points to introduce 42. Create data loggers, using 8-bit and 10-bit
uncondi onal branching in a program. data from the ADC.
14. Introduce PWM as a means of controlling 43. Configure an analogue input.
the brightness of LEDs. 44. Enter data via switches.
15. Create an infinite loop. 45. Enter informa on from light and temperature
sensors.
16. Manipulate logic output levels.
46. Configure and use the EEPROM.
17. Use LEDs to display an output. 47. Scroll through EEPROM data.
18. Create and use a variable. 48. display text and numerical data on the LCD.
19. Configure a calcula on icon to perform 49. Use the E-blocks prototype board.
arithme c and logic calcula ons. 50. Use so ware macros to simplify the structure
20. Create and manipulate variables. of a program.
21. Perform calcula ons. 51. Create so ware macros.
22. Use LEDs with current limi ng resistors. 52. Use closed loop control.
23. Create and use a ‘running light’ program, 53. Use PWM to control the brightness of LEDs.
using the ‘mul ply-by-two’ method. 54. Create and use ‘single-pin’ interrupts.
24. Create and use a ‘running light’ program, 55. Create and use ‘interrupt-on-change’ (IOC)
using the ‘shi -right’ method. interrupts.
25. Create and populate an array. 56. Use real me opera on of a PIC MCU.
26. Create a condi onal loop. 57. Create and use mer interrupts.
27. Input data from switches. 58. Use the prescaler to create accurate me
28. Use loops to create LED sequences. intervals.
59. Trigger the mer using the crystal or an
29. Configure an input icon. external event.
30. Configure decision icons and hence add
condi onal branching to a program.
Introduc on to microcontrollers
Sec on 1: Introduc on to
Microcontrollers
Microcontrollers are ny devices used to control other electronic devices. They are found in a huge
range of products. In automo ve systems they can be found in engines, an -lock brakes and
climate control systems. In domes c electronics they can be found in TVs, VCRs, digital cameras,
mobile phones, printers, microwave ovens, dishwashers and washing machines.
At their heart (or is it brain?) there is a Central Processing Unit (CPU). This processes the digital signals, does
calcula ons and logic opera ons, creates me delays, sets up sequences of signals etc.
How does it know what to do? It is following a program of instruc ons, stored in part of the memory, called the
'program memory', inside the PIC.
From me to me, the CPU needs to store data, and then later retrieve it. It uses a different area of memory, called
the 'data memory' to do this.
The clock synchronises the ac vi es of the CPU. It sends a stream of voltage pulses into the CPU that controls when
data is moved around the system and when the instruc ons in the program are carried out. The faster the clock,
the quicker the microcontroller runs through the program. Typically, the clock will run at a frequency of 20MHz
(twenty million voltage pulses every second.)
To talk to the outside world, the microcontroller has 'ports' that input or output data in the form of binary
numbers. Each port has a number of connec ons - o en referred to as 'bits'. An 8-bit port handles an 8-bit (or one
byte) number.
Informa on from sensors is fed into the system through the input port(s). The microcontroller processes this data
and uses it to control devices that are connected to the output port(s). The ports themselves are complex
electronic circuits - not simply a bunch of terminals to hang components on.
What is a microcontroller? Introduc on to microcontrollers
Analogue Data
Many electronic sensors provide signals in analogue form. For example, a
microphone provides an electrical 'copy' of a sound wave.
Another - the temperature sensor!
Here is the circuit diagram for one type of temperature sensor.
The output voltage increases when the temperature increases.
It is an analogue signal because the voltage copies the behaviour
of the temperature.
An electrical analogue signal can have any voltage value,
limited only by the power supply used.
In this case, the output of the temperature sensor could, in
theory, go as high as 5V, or as low as 0V.
Over a period of me, the output voltage could change as
shown in the diagram. This is an analogue signal.
Digital Data
A digital signal carries its informa on in the form of a number. Electronic
systems usually employ the binary number system, which uses only the
numbers ‘0’ and ‘1’, coded as voltages. We could decide on the following code:
'0' = 0V, '1' = 5V, for example.
Digital signals, then, have only two possible voltage values, usually the power
supply voltage, or as close to it as the system can get, and 0V.
How can we enter these numbers into an electronic system?
One (very slow) way would be to use a switch (an example of a digital sensor.) The circuit diagram shows such a
digital sensor.
When the switch is open (not pressed,) the output is 'pulled down' to 0V by the resistor. This output could
represent the binary number '0'.
With the switch closed (pressed,) the output is connected to the posi ve supply, 5V in this case.
This could represent the binary number '1'.
(Note - if the posi ons of the switch and resistor were reversed, pressing the switch would put a
logic 0 signal on the pin etc.) The following diagram shows a more complex digital signal.
The nine bit binary number represented by the signal is given under the waveform.
Analogue to digital conversion Introduc on to microcontrollers
Much of our 'real world' data is analogue, but computers (including microcontrollers) can only process
digital data. Fortunately the microcontrollers o en contain a subsystem that can convert informa on
from analogue format to digital format. This is called an Analogue-to-Digital Converter - usually shortened
to 'ADC' or 'A/D'.
The ADC inside the a microcontroller divides the range of possible analogue voltages into equal steps.
The lowest step is given the number ‘0’, and the highest step is given the highest number that the A/D
converter can handle.
This highest number is determined by the resolu on of the ADC, which, in turn, depends on number of
'bits' the internal circuitry of the ADC can handle. The resolu on of PIC ADCs is 8, 10 or 12 bit.
For example, if the biggest analogue voltage is 5V, and the PIC has an 8-bit ADC:
the highest 8-bit number is 1111 1111 (= 255 in decimal);
so stepping from one level to the next involves a voltage jump of 5V/256, or about 20mV.
When this microcontroller processes an analogue signal, it first divides it by 20mV, to find out how many
steps the signal includes. This gives the digital equivalent of the analogue signal.
The next graph illustrates this process.
In our example, the converter outputs '0000 0000' for any analogue signal up to 20mV, outputs '0000
0001' for analogue signals between 20 and 40mV, and so on. The analogue signal shown in the graph
produces an output of '0000 0011'.
Inpu ng data into a microcontroller Introduc on to microcontrollers
Outpu ng data
The microcontroller is a digital device - we have said that several mes already! It outputs a digital signal.
In most cases, we use this to turn something on and off - '0' = 'off' and '1' = '0n', for example.
Suppose that we set up port B as the output port, (or let Flowcode do it for us). There are eight pins on
port B, so we can switch eight devices on and off. It is important to plan how we connect these devices,
as otherwise they might work the opposite way round!
Outpu ng data Introduc on to microcontrollers
The diagram shows eight LEDs connected to
port B of a PIC16F84 microcontroller:
The four red LEDs are connected between the
posi ve supply rail and the port B pins
For these LEDs, PIC is 'sinking' current.
Types of Memory
There are several types of electronic memory, each with a slightly different job to do.
We can divide them into two main groups, ROM and RAM,:
A PROM is a one-shot device, which arrives blank, ready to receive data. Data can then be 'burned' into it,
but only once. A er that it behaves like a ROM chip that can be read many mes but not altered.
With an EPROM, shining ultraviolet light through a window in the top of the chip erases the contents.
New data can then be 'burned' into the memory. Some older PIC devices operate in this way.
The EEPROM devices work in a similar way to an EPROM, except that the contents are erased by sending
in a special sequence of electrical signals to selected pins. 'Flash' memory is a form of EEPROM, widely
used as the storage medium in digital cameras, (the memory s ck) and in home video games consoles.
Microcontroller memory
PIC chips have three separate areas of memory:
program memory (Flash);
user variable memory (RAM);
EEPROM.
The names give strong hints as to the purpose of the areas!
For the eighteen pin PIC16F84 the graphic illustrates the
organisa on of the memory:
Programming
Microcontrollers are programmable devices. They do exactly what they are told to do by the program, and nothing
else! A program is a list of instruc ons, along with any data needed to carry them out.
The only thing microcontrollers understand is numbers. There's a problem! We don't speak in numbers, and they
don't understand English!
There are two solu ons, and both need some form of translator:
Write the program in english, or something close to it, and then have the result translated into numbers.
We can think through the program design in English and then translate it ourselves into a language that is
similar to numbers, known as 'assembler'. From there, it is a swi and simple step to convert into the numerical
code that the microcontroller understands.
These two extremes are known as programming in a high-level language (something close to English) or in a low-
level language (assembler).
The first is usually quicker and easier for the programmer, but takes longer to run the program, because of the
need to translate it for the microcontroller.
The second is much slower for the programmer, but ends up running very quickly on the microcontroller.
If you think that this sounds very complicated, you are right. It is! Fortunately, Flowcode works using flowcharts -
the easiest, and highest level, of programming and then takes care of all transla on needed.
The Flowcode process Introduc on to microcontrollers
The Hex code is then sent into the microcontroller, using a subsidiary program called 'Mloader'.
When you select Build > Project Op ons... Configure from the Flowcode menu, the program 'Mloader'
runs. It controls a number of op ons and configura ons by se ng the value of registers inside the device
when you download a program.
The Hex code is 'burned' into the microcontroller program memory. Since Flash memory is used to form
the program memory, the program is not lost when the microcontroller is removed from the
programmer. This allows you to use it in a circuit. Equally, use of Flash memory means that you can reuse
the microcontroller and overwrite the program memory with a new program.
Running the Program
As soon as the microcontroller is powered up and is supplied with clock pulses, it will start to run
whatever program is stored in program memory (Flash).
When you press the reset bu on on the microcontroller programming board, the program restarts from
the beginning.
During programming the microcontroller stops while the program is being loaded. When that is
completed, it then restarts and runs the downloaded program.
The PIC16F877 Introduc on to microcontrollers
PIC16F1877 Architecture
As this course uses the PIC16F18877 PIC, it is
important that you understand a li le more about
what it does and how to use it. This sec on details
the pins that are available on the 16F1877 and the
connectors they use on the programmer board.
(The sec on on 'Using E-blocks' looks at how these
connec ons are made).
Memory:
Flash
Flash memory is used to store the program you write.
This program is 'compiled' by the computer to binary code and then downloaded into the Flash memory of the
PIC.
You can read from, and write to it and it is retained, even a er a power cut.
The Flash memory contained in the 16F18877 can store up to 32768 program commands.
RAM
Data from inputs, outputs, analogue inputs, calcula ons etc. is typically stored in ‘variables’ (values in the
program that alter as it runs). RAM is where these are stored.
This memory is erased every me the power gets cut or a reset occurs.
It also contains system 'registers' which control and report the status of the device.
The RAM memory in the 16F18877 can store up to 4096 bytes of data.
EEPROM
EEPROM is where data can be permanently stored
This memory is of the PROM-type - preserved every me the power cuts or a reset occurs.
The EEPROM of the 16F18877 can store up to 256 bytes of data.
The PIC16F18877 Introduc on to microcontrollers
ALU:
The ALU (Arithme c Logic Unit) is at the heart of the PIC’s data processing.
All data passes through this unit.
The program in the Flash memory tells the ALU what to do.
The ALU can send data to, and fetch data from all the separate blocks and ports in the PIC using the 8-bit wide
data-bus.
The ALU needs four external oscillator clock pulses to execute one whole instruc on.
How the ALU works is very complicated. Fortunately Flowcode programmers do not need to know how it
works.
Timer 1 (TMR1):
This mer interrupt is used to provide the microcontroller with exact ming informa on.
It is ‘clocked’ either by the system clock or by an external clock on pin RC0.
Either clock can be divided by 1, 2, 4 or 8 by configuring the Prescaler of TMR1 in Flowcode. The resul ng
output triggers TMR1 and increments the TMR1 register.
TMR1 is a 16-bit register, which ‘overflows’ when it reaches ‘65536’.
At the instant it overflows, it generates an interrupt and the TMR1 register is reset to ‘0’.
This TMR1 Interrupt stops the main program immediately and makes it jump to the TMR1 macro.
A er this finishes, the main program con nues from where it le off just before the interrupt.
For example:
External clock oscillator frequency (crystal oscillator) 19 660 800 Hz
System Clock (four clock pulses per instruc on) 4 915 200 Hz
Set prescaler to ‘8’ (divides by 8) 614 400 Hz
Overflow frequency when TMR1 = ‘65536’ 9.375 Hz
Result: TMR1 interrupts the main program and execute the TMR1 macro 9.375 mes per second.
Timer 0 (TMR0):
This mer interrupt also provides the microcontroller with exact ming informa on.
It is ‘clocked’ either by the system clock or by an external clock on pin RA4.
This system clock runs exactly four mes slower than the external oscillator clock.
Either clock can be divided by 1, 2, 4 or 8, 16, 32, 64, 128, or 256 by configuring the Prescaler of TMR0 in
Flowcode. The result triggers TMR0 and increment the TMR0 register.
This TMR0 register is an 8-bit register, which overflows when it reaches 256.
At the instant it overflows, it generates an interrupt and the TMR0 register is reset to 0.
A TMR0 Interrupt stops the main program immediately and makes it jump to the TMR0 macro.
A er this finishes, the main program con nues from where it le off just before the interrupt.
For example: External clock oscillator frequency (crystal oscillator) 19 660 800 Hz
System Clock (4 clock pulses per instruc on) 4 915 200 Hz
Set prescaler to 256 (divides by 256) 19 200 Hz
Overflow when TMR0 = 256 75 Hz
Result: TMR0 interrupts the main program and execute the TMR0 macro 75 mes per second.
The PIC16F18877 Introduc on to microcontrollers
Busses:
PIC and AVR (Arduino) microcontroller uses Harvard architecture.
This means that there are separate busses for instruc ons and for data.
The data bus is 8-bits wide and connects every block and port together.
The instruc on bus is 14-bits wide and transports instruc ons, which are 14-bits long, from the program
memory to the ALU.
Introduc on to ‘clocks’
Every microcontroller needs a clock signal to operate. Internally, the clock signal controls the speed of
opera on and synchronises the opera on of the various internal hardware blocks.
In general, microcontrollers can be ‘clocked’ in several ways, using:
an external crystal oscillator;
‘RC’ mode, where the clock frequency depends on an external resistor and capacitor;
an internal oscillator.
The ‘RC’ mode exists partly historical and partly for reasons of economics. It was introduced as a low cost
alterna ve to a crystal oscillator. It is fine for applica ons that are not ming cri cal, but is not covered in
this course.
Using E-blocks Introduc on to microcontrollers
Sec on 2: Using
E-blocks
E-blocks are small circuit boards that can easily connect together to form an electronic system.
There are two kinds of E-Blocks. Upstream boards and Downstream boards.
A variety of boards can be combined to create a full system with downstream boards connected to
upstream boards.
E-blocks are ideal companions to Flowcode so ware, allowing users to test and develop their
Flowcode programs. Programs can be compiled directly to the boards, providing ideal development
environments.
Using E-blocks Introduc on to microcontrollers
Upstream boards
'Upstream' is a compu ng term indica ng a board that controls the flow of informa on in a system. They
are usually programmed in some way.
Any device which contains 'intelligence' and can dictate the direc on of flow of informa on on the bus
can be thought of as an 'upstream' device.
Downstream boards
‘Downstream’ boards are controlled by an ‘upstream’ board, but informa on can flow into or out of
them. Examples include LED boards, LCD boards, RS232 boards etc.
Upstream and downstream boards combined to form a full system, with the downstream boards plugging
into the upstream ‘intelligent’ boards:
Using E-blocks Introduc on to microcontrollers
For Arduino programmer overview please refer to Appendix 1, SECTION A (page 89).
Using E-blocks Introduc on to microcontrollers
The board provides a set of eight switches and eight LEDs for port A and the same for port B.
With the main switch in the DIG posi on, port A is routed to its push switches (SA0 to SA7), to LEDs (LA0 to LA7)
and to the quad 7-segment display.
With the main switch in the ANA posi on, port A is switched to the analogue sensor sec on of the board, so that
pin RA0 is connected to the on-board light sensor and pin RA1 is connected to the poten ometer to give a variable
output voltage, (simula ng the ac on of an analogue sensing subsystem).
Note: With the switch in the ANA posi on, the on-board switches and LEDs LA0 and LA1 will not operate.
Port B I/O pins are routed to its push switches (SB0 to SB7), to the LEDs (LB0 to LB7), to the quad 7-segment
displays and to the LCD display.
The quad 7-segment display is turned on by switch ‘7SEG’. It is connected to both port A and B.
Port B is used to control the LED segments and the decimal point).
Port A, bits 0 to 3, select which display is ac vated.
The LCD is a 20 character x 4 lines module, turned on by switch ‘LCD’. Normally a complex device to program,
Flowcode takes care of the complexi es, unseen by the user.
Using E-blocks Introduc on to microcontrollers
Sec on 3: Introduc on to
Flowcode
Embedded
Flowcode Embedded allows you to create microcontroller applica ons by dragging and dropping
icons on to a flowchart to create programs. These can control external devices a ached to the
microcontroller such as LEDs, LCD displays etc.
Once the flowchart has been designed, its behaviour can be simulated in Flowcode before the flowchart is
compiled, assembled and transferred to a microcontroller.
Introduc on to Flowcode Embedded Introduc on to microcontrollers
This sec on allows those who are new to Flowcode to understand how it can be used to develop
programs. It allows you to enter programs step-by-step to learn about how Flowcode works.
We advise that you work through every sec on to familiarise you with all of the op ons and features of
Flowcode and introduce you to a range of programming techniques. As you work through each part,
please also refer to the Flowcode help file. The main Flowcode icons are introduced in turn.
Specifically in this sec on you will learn:
how to use each Flowcode icon (except the C code icon);
how the fundamental Components in Flowcode work - the LED, LCD, ADC, switch, 7-segment display, 7-segment
quad display, keypad and EEPROM components.
The process:
1. Create a new flowchart, specifying the microcontroller that you wish to target.
2. Drag and drop icons from the toolbar onto the flowchart to program the applica on.
3. Add external devices by clicking on the bu ons in the components toolbar.
4. Edit their proper es, including how they are connected to the microcontroller, and configure any macros
they use.
5. Run the simula on to check that the applica on behaves as expected.
6. Transfer the applica on to the microcontroller by compiling the flowchart to C, then to assembler code and
finally to object code.
Command Icons
Drag-and-drop icons from this window onto the main flowchart window to create the
flowchart applica on. Alterna vely the icons are available in the Command Icons toolbar.
This is the first tab of the Project Explorer, here docked le , but it can be undocked.
Introduc on to Flowcode Embedded Introduc on to microcontrollers
The System Panel is the main 3D panel, offering many more features and
op ons:
full camera control;
editable background environments with default 'Sky Dome' and 'World
Dome' views;
the op on to use an image as the background;
'Shadow mode' offering both 'Tabletop' and 'Object' shadow op ons.
Project Explorer
The bu ons along the top of this panel allow you to select ‘Ports’, ‘Globals’,
‘Macros’ and ‘Components’.
The 'Ports' view shows variable names assigned to the microcontroller ports.
The 'Globals' view shows any constants and variables that have been defined
for use in the current project.
The 'Macros' view shows user-created macros in the current program and
allows the user to drag them into the current flowchart.
The 'Components' view is very similar except that it also lists components that
are present in the panel. (View > Project Explorer)
Introduc on to Flowcode Embedded Introduc on to microcontrollers
To undock a docked toolbar, simply click and hold on the toolbar 'grab bars' (the top of the toolbar). Drag the
toolbar to its new posi on. To dock it again, double-click on the grab bar.
Introduc on to Flowcode Embedded Introduc on to microcontrollers
Flowchart window
The icons that make up the flowchart are displayed in this main space.
The text will change depending on proper es selected,
component macros called etc, The display names can be
changed by the user to aid project organisa on.
Simula on
When simula ng a program in Flowcode a red
rectangle around an icon indicates the icon to be
executed next.
Simula on Debugger
When simula ng a flowchart, the
current values of any variables used in
the program can be seen in this
window. These are updated a er a
command is simulated unless the
simula on is running at full speed - ('As
fast as possible').
If you simulate a flowchart and then press the pause bu on, you can click on variables in this window to change
their value. This allows you to test your flowchart under known condi ons.
The window also shows the current macro being simulated under the 'Macro Calls' sec on, useful when one macro
calls another during the simula on process.
Introduc on to Flowcode Embedded Introduc on to microcontrollers
Saving a Flowchart
To save a flowchart, select either the ‘Save’ or ‘Save As’ op ons from the File menu (File > Save / Save As).
Flowcharts must be saved before they can be compiled to C or transferred to a microcontroller.
From the 'Save Image' menu, you also have the op on to save the current image of either the 'Dashboard Panel' or
the 'System Panel' (File > Export > Save Dashboard image... / Save System image...).
These images can be saved to any file format chosen from the list:
Model (*.mesh)
Bitmap (*.bmp)
JPEG (*.jpg;*.jpeg)
GIF (*.gif)
PNG (*.png)Model (*.mesh)
Introduc on to Flowcode Embedded Introduc on to microcontrollers
The current zoom se ng is displayed on the Zoom sub menu, and on the right hand side of the status bar, at the
bo om of the Flowcode window.
The size of each icon is dictated by the zoom level - for larger icons, zoom in - for smaller icons, zoom out.
Use the Print Preview func on to op mise the appearance of your flowchart on the paper.
The Zoom menu can also be accessed by right-clicking on the flowchart workspace.
Global Se ngs
The View menu also includes a Global Se ngs for configura on of applica on and flowchart
(View > Global Se ngs) Then select the appropriate Tab.
Applica on Tab
his tab enable se ng of general applica on
se ngs, such as language, document
appearance, autosave
feature, code genera on op ons and web
access.
Flowchart Tab
Scheme Tab
Addi onally every single component within Flowcode has a page on the wiki which explains all the
macros within it, and usually includes some examples as well.
To access the component help simply right-click your mouse on any component in either the 2D or 3D
panel and select Help.
Library Updates
Flowcode components and target device informa on is keep up to date via an online system accessed
from the Help menu (Help > Library Updates)
Introduc on to microcontrollers
Sec on 4: Flowcode
First Program
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 simula on mode before compiling to the board for tes ng
and development.
Note: This tutorial refers to the port se ngs (ports A and B) as used with PIC.
Select 'New Project’ at the welcome screen, or via the menu (File > New Project)
On the “Embedded” tab choose a target device or development board.
You will no ce that the selec on list includes details of the features and peripherals of each target.
This is useful when selec ng a device for a par cular project.
For our new project, if we are using for example the MatrixTSL E-blocks2 PIC development board,
choose the BL0011 target from the “Free targets” list.
In this case the target choice also selects the correct 16F18877 device
and presets the correct values for clock oscillator frequency and other se ngs.
TIP: The project target device can be changed later via the menu (Build > Project Op ons)
Flowcode first program Introduc on to microcontrollers
Create a Flowchart.
Add an Output icon within the
Move the cursor over the Loop icon, in the Icon
loop on the flowchart in the same
toolbar. Click and drag it over to the work area. way.
While dragging it, the normal cursor changes into a
small icon. Move it in between the 'BEGIN' and TIP: The colours of the icons on
your system my be different.
'END' icons. As you do so, an arrow appears
showing you where the Loop icon will be placed.
Release the mouse bu on to drop the icon in
between the 'BEGIN' and 'END' boxes.
Flowcode first program Introduc on to microcontrollers
Go (F5)
Simula on mode.
TIP: Remember to stop your simula on before doing anything else. (If Flowcode isn’t
doing as you expect, check that you haven’t accidentally le your simula on running).
Flowcode first program Introduc on to microcontrollers
Run in simula on
mode and then
compile to chip.
You should see
the first LED of
the other row
light up.
You can prac se changing the ports by changing them back to port B. Change the value from 1 to 255.
Test in simula on mode and then compile to chip (all 8 LEDs light up). Experiment using other values.
(TIP: See Number Systems Worksheet).
Flowcode first program Introduc on to microcontrollers
Binary Numbers
Digital electronic devices can't cope with decimal numbers (0, 1, 2, ..9 Decimal Same in binary
etc.). Instead, they use the binary system, which uses only two numbers
0 0
0 and 1. The number 1 could be represented by a high voltage signal,
1 1
while number 0 could be a low voltage.
2 10
The table opposite shows how the two number systems compare: 3 11
The decimal system uses ten numbers, 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. On 4 100
reaching the last of these, ‘9’, we start again with '0', but add another 5 101
number in front. For example, a er '8' and '9' comes '10', and a er '18' 6 110
and '19' comes '20' and so on. When we reach '99', both of these go
7 111
back to '0''s but with a '1' in front, to make '100'.
8 1000
9 1001
16 8 4 2 1
Decimal Same in binary
1 1
In binary, the same thing happens, but a lot more o en, because it uses only 2 10
'0''s and '1''s. Coun ng up starts with '0', then '1', then back to '0' with a '1' in 4 100
front, making '10' (not ten - it's two!) Next comes '11' (three) and start again 8 1000
with two '0's but with a '1' in front, to give '100' (four) and so on.
No ce that each me the binary '1' moves one place to the le , it doubles in value of the number in
decimal, as the second table shows. We can use this idea to convert between number systems.
TIP: In any binary number, the bit at the le -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 more convenient form than binary (for humans) for represen ng
numbers.
A binary digit is either 0 or 1.
A decimal digit varies between 0 and 10.
A hex digit has sixteen possible states.
Clearly sixteen states is a problem, as we have only the digits from 0 to 9. To get round this, we use the
le ers A to F to provide the addi onal six digits required.
Working with the binary number with eight digits is a handy conven on as computers (and the
PIC MCU) store informa on in groups of eight bits.
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.
TIP: You can enter a hex number into Flowcode by preceding it with '0x' in any of the dialogue
boxes.
Flowcode first program Introduc on to microcontrollers
Tasks
Sec on 5: Flowcode
Examples
All of these examples can be tried out using either a PIC or an Arduino microcontroller.
Arduino users should familiarise themselves with Arduino Adjustments in Appendix 1, and adjust
any port se ngs accordingly.
Flowcode examples Introduc on to microcontrollers
The scenario!
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 device. 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.
Se ng up the flowchart
Open Flowcode and create a new project suitable for For Arduino users, please use ports C and
the board you are using. D as appropriate.
(Port C on the Arduino ’Maps’ to Port A of the
Drag the Loop icon, the Input icon and the Output icon
Combo board).
into your Flowchart from
the icon toolbar to create a Flowchart as shown.
Set Input to port A and Output to port B.
Flowcode examples Introduc on to microcontrollers
Now hover over the word 'Variables' and the arrow appears. Click on it and select
'Add new'.
Another dialogue box, shown opposite, appears, offering a large choice of variable
types. For now, accept the default type of 'Byte', a variable which can store numbers
from '0' to '255'.
Type the name "SENSOR" (without quota on marks) as the name of
the new variable and click on the ‘OK’ bu on. It now appears in the
list of variables that the flowchart can use.
More on variables
In the previous sec on you added a variable to the
program using the variable dialogue box:
Computer signals consist of streams of binary '0's and
'1's 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 Flowcodecan be configured to use just
one memory register or more than one.
Flowcode variables:
Flowcode offers eight different types of variables:
a 'Bool' (Boolean) variable can either be '1' or
'0' (true or false);
a single register, known as a 'Byte' variable, can
store numbers from '0' to '255';
a double register, known as an 'Int' variable, can store numbers from '-32768' to '+32767';
a double register can also be unsigned, when it is known as a 'UInt' variable, which can store numbers from '0'
to '65535';
a quad register, known as a 'Long' variable, can store numbers from '-2147483648' to '2147483647';
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. Mathema cal processes involving two bytes (o en
referred to as '16 bit arithme c') take longer to execute. A mul ple register, known as a 'String' variable, can
consist of a number of ‘Byte’ variables - the default in Flowcode is 20.
Why worry?:
The number of registers inside a microcontroller is limited, and in larger applica ons 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) part of the PIC device. In the 16F1937 there are
512 Bytes of memory. This means you can have 512 ‘Byte’ variables, 265 ‘Int’ variables or 25 ‘Strings’ each
consis ng of twenty ‘Bytes’ or characters.
Flowcode examples Introduc on to microcontrollers
Se ng up the outputs
Next, right-click on the Output icon, and select 'Proper es' or
just double-click on it. The Output Proper es box appears.
Click on the arrow, , next to the 'Variable:' box. You will see
the 'SENSOR' variable listed.
Double-click on the word 'SENSOR' or click and drag it to the
'Variable:' box.
The Output Proper es box now shows that the system is set to
output whatever data is stored in the 'SENSOR' variable. Change
the port used to port B, by clicking on the arrow, ,
in the port window, and then clicking on 'PORTB' in the menu
that opens.
Click on ‘OK’ to close the Output Proper es box.
The flowchart should now look like this:
No ce the arrows in the icon annota ons. They show that
informa on will flow from port A into the flowchart, via
‘SENSOR’, (Input icon) and from the flowchart, via ‘SENSOR’, out
to port B (Output icon).
The program is finished, and working. You have just detected a fire, which turned on a heat sensor. The LED array
tells you, or the fire brigade, which sensor detected the fire.
Flowcode examples Introduc on to microcontrollers
Se ng up the flowchart
Launch Flowcodeand start a new flowchart.
Create the flowchart shown opposite.
It contains a 'Loop' icon and a 'Calcula on' icon which you have not used
before.
It contains an Input icon and an Output icon.
Se ng up the calcula on
Double-click on the 'Calcula on' icon to
open the 'Proper es' dialogue box.
Change the 'Display name' to "New total".
Create the calcula on by typing the
following in the 'Calcula ons' window:
TOTAL = TOTAL + SHEEP
We will simulate breaking the light beam
using a push switch marked 'SW0' on port A
bit 0.
The 'Input' proper es are set up to store
whatever number appears on port A in the
variable called 'SHEEP'. Ini ally, 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.)
When the 'Calcula on' 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.
Click on the ‘OK’ bu on, to close the dialogue box.
In all of these, looping con nues as long as the condi on in the 'Loop while' text box is 'true'.
In programming 'true' has a special meaning. It is assigned a numerical value of ‘1’ so that a test can determine if
something is ‘true’. Similarly 'false' is assigned the numerical value '0'.
The default condi on in the 'Loop while:' text box is '1' - this condi on is always 'true' and so with this value, the
loop will run forever. Programs usually contain a ‘loop forever’ structure. If they do not, the program will end
suddenly and the computer will just sit there doing nothing.
When to test?
You can configure the proper es to test the loop condi on either at the start of the loop or at the end.
Understanding this op on is important. It can affect the number of mes that the program will loop.
Se ng up the input
Right-click on the 'Input' icon, and select 'Proper es' from
the menu, to see the following dialogue box:
Change the display name. Double-click on 'Input' in the
'Display name:' box and type "Check the sensor".
Click on the next to the 'Variable:' box to open the
'Variable Manager'.
Double-click on the word 'SHEEP' to insert it into the
'Variable:' box.
By default, the input is port A, which is what we want. Click
on ‘OK’ to close the dialogue box.
Se ng up the output
Double-click on the 'Output' icon to open the output 'Proper es' dialogue box.
Click on the next to the 'Variable:' box.
Double-click on the word 'TOTAL' to insert it into the 'Variable:' box.
In the output' Proper es' box, change the port used to 'PORTB'.
Click on 'OK' to close the dialogue box.
You should now have a project that looks something like this:
What happens depends on how quickly you click, and how fast the PC works!
We want only the 'B0' LED to light, to show a total of 1 sheep. The program runs at high speed, however, and so
keeps cycling through the 'Input' and 'Calcula on' steps. As a result, before you have me to release the push
switch, the total has incremented (increased by one) several mes. This problem is explored in the next sec on.
Flowcode examples Introduc on to microcontrollers
Double-click on the 'Delay' icon to open the 'Proper es' dialogue box.
Change the value in the 'Delay value or variable:' box to '200' and then click on the ‘OK’ bu on. This causes a
200 millisecond (0.2 second) delay when the 'Delay' icon is ac vated. In other words, the system just sits there
and does nothing for 0.2 seconds.
Now run the simula on again. Providing you don't keep it pressed for too long, you should find that the LED
array shows an increase of 1 each me you press the switch.
The program now works sa sfactorily, providing the sheep rush through the light beam in less than 0.2
seconds. The delay could be increased to allow for slower sheep!
Note: This program shows the total number of sheep in binary format.
Flowcode examples Introduc on to microcontrollers
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 complexi es, 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 two row, sixteen character
display.
Wri ng Messages
Run the program and the text will be sent to the LCD
display.
'Clear' - Clears the display and resets the cursor posi on, (where the display prints next,) to '0,0' i.e. top le .
'Cursor' - Moves the cursor to the specified loca on. The two parameters, ‘X’ and ‘Y’ select the horizontal and
ver cal posi ons of the cell respec vely. ‘0,0’ is the top le cell, ‘0,1’ the first cell on the second line, ‘3,2’ the
fourth cell on the third line … .
'PrintNumber' Works like 'PrintString' but prints a number instead of a string. It can be used with variables, or
with actual numbers.
Flowcode examples Introduc on to microcontrollers
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).
Flowcode examples Introduc on to microcontrollers
Example 4: a stopwatch
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.
Flowcode examples Introduc on to microcontrollers
Se ng up the Flowchart
Launch ‘Flowcode’ and start a new flowchart.
This me we take no ce of this dialogue box:
We need a PIC with at least three ports.
Pull the slide bar down to find the 16F1937 PIC.
Click on it to select it and then click on ‘OK’.
Click-and-drag a Loop' icon between the 'BEGIN' and 'END'
boxes.
Click-and-drag an 'Input' icon and drop it between the ends
of the loop.
Click and drag a second 'Input' icon and drop it in between
the ends of the loop.
Click and drag an Output icon and drop it just below the
'Input' boxes.
Click and drag a Calcula on icon and place it in between the
second Input icon and the Output icon.
Your flowchart should now look like this:
Click 'View' on the menu bar and ensure that 'Project Explorer' is checked (View >
Project Explorer).
Click on the 'Globals' bu on at the top of the Project Explorer panel. We are going to
create three variables, called ‘input1’, ‘input2’nand ‘sum’. The first two store the
numbers fed in from the switches. The variable 'sum' stores the result of adding
them together.
Hover over 'Variables' in the 'Project Explorer' panel then click on the
that appears.
Click 'Add new' and the 'Create a New Variable' dialogue box appears. Type
in the name "input1", and click on the ‘OK’ bu on - leave the variable type
as 'Byte'.
Create variables, ‘input2’ and ‘sum’ in the same way.
Se ng up the inputs
Right-click on the top 'Input' icon, and select ‘Proper es’. The
‘Proper es: Input’ dialogue box appears.
Double-click on the word ‘Input’ in the 'Display name:' box to
highlight it.
Type "Input the first number" to replace it. This will appear alongside
the 'Input' icon in the flowchart. (Adding labels like this helps users to
understand what is happening.)
Click on the arrows next to the variable box to open the 'Variable
Manager'. This lists the three variables that you just created.
Double-click on 'input1' to use this variable in the input box.
Back in the 'Input Proper es' dialogue box, click on the down arrow
at the end of the port window, and select 'PORTB' to replace ‘PORTA’.
Click on ‘OK’ to close the dialogue box.
Double-click on the second 'Input' icon. (a quicker way to open the
'Proper es' box.)
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).
Introduc on to microcontrollers
Slow Simula on
As described earlier, Flowcode allows you to progress through the flowchart one step/icon at a me, to see the
effect of each on the variables and on the output.
There are three ways to simulate the program step-by-step:
Click on Go on the Debug toolbar and on the Step Into bu on (Debug > Step Into)
Press the F8 func on key on the keyboard.
Click on the 'Step Into' bu on on the main toolbar in the simula on sec on.
Do one of these!
Several things happen:
a red rectangle appears around the 'BEGIN' icon, showing that this is the current step;
the 'Simula on debugger' window appears - containing 'Variables' and 'Macro Calls';
the 'Variables' sec on lists the three variables that you
defined for this program, and shows their current values -
all zero at the moment.
Ignore the 'Macro Calls' sec on for the moment.
Now set up two numbers on the switch components.
Move the cursor over the switch box connected to port B.
Click on switches B0, B1, and B3, to ac vate them.
The switches now look like this:
You have set up the binary number 000 1011 (= eleven in decimal.)
(Switch 'B6' gives the most significant bit and 'B0' the least significant bit).
Set up the number 000 1111 (fi een) on the switches connected to port C.
Now ‘Step Into’ to the next icon in the program by, for example, pressing F8 once more.
The red rectangle moves on to the next icon, the 'Loop' icon, but li le else happens.
Press F8 once again. The red rectangle moves on to the first Input icon.
Press F8 again and the 'Variables' box shows that the 'input1' variable now contains eleven - the result of the
'Input' instruc on just carried out.
Press F8 again and the 'Variables' sec on shows that 'input2' now contains fi een.
Press F8 again and the calcula on is carried out. The 'sum' variable stores the result.
Press F8 again. The value stored in 'sum' is transferred to the LEDarray.
It looks like:
Reading from the most significant bit ('D7') to the least significant bit ('D0'), the LED array shows the number 0001
1010. In decimal, this is the number 26. No surprises there then!
Repeat the same procedure using different numbers and step through the
program to check what the sum of the numbers is.
Se ng up the flowchart
Launch Flowcode with a new flowchart.
Configure the other input icon to store the state of the control switch (on port A bit 1) in the variable ‘control’.
The upper calcula on icon checks to see whether the door AND the control switch have been pressed.
Configure it using the equa on output = control & door.
The & signifies the AND opera on.
The result of this opera on (0 or 1) is stored in the variable ‘output’.
The upper decision icon checks the value stored in ‘output’.
(If output? is shorthand for If output=1?)
Configure this decision icon.
When the result of the calcula on is 0, the program follows the ‘No’ route from the decision icon and the le -
hand output icon is executed. This sends a logic 0 to the LED, ensuring that it (and the microwave generator) is
switched off.
When the result of the calcula on is 1, the program follows the ‘Yes’ route. The ‘Turn on’ output icon sends a
logic 1 to the LED turning it on.
Configure both of these output icons.
The lower calcula on icon reduces the number stored in the variable ‘count’ by one.
Configure it using the equa on count = count - 1
The ini al value of ‘count’ is ten. Provided the number stored in ‘count’ has not reached zero, the program
follows the ‘No’ route. Eventually, a er looping enough mes, the number stored does reduce to zero. The
program then follows the ‘Yes’ route and executes the ‘Turn off’ output icon, which is configured in the same
way as the other ‘Turn off’ icon, to switch off the microwave generator.
Add a switch array to the System Panel. Configure it to have only two switches, one connected to port A, bit 0
and the other to port A, bit 1.
Add an LED connected to port B, bit 0 to represent the microwave generator.
Add labels to the System Panel to iden fy the components. Posi on them using the World coordinates under
the Posi on tab of the label proper es.
Now simulate the program step-by-step, using the F8 func on key repeatedly.
Check what happens for different combina ons of switch states and interpret this in terms of the behaviour of
the microwave oven. What happens, for example, if the door is opened while the microwave generator is
opera ng?
For Arduino the Ports need to be set to PORTC and PORTD (equivalent to A and B on the Combo board).
Flowcode examples Introduc on to microcontrollers
Se ng up the flowchart
Launch Flowcode and start a new flowchart. Create the
flowchart shown opposite, using:
a loop icon.
three input icons.
two output icons.
a decision icon.
a calcula on icon.
Now simulate the program step-by-step, using the F8 func on key repeatedly.
Check what happens for different combina ons of open doors and igni on 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 a er? Is this behaviour correct?
Introduc on to microcontrollers
Sec on 6: Programming
exercises
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 simula ng 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 sec on ends with further Challenges. These are even more open-ended and contain only a brief
specifica on.
Crea ng outputs Introduc on to microcontrollers
Introduc on
This exercise configures Flowcode to output specific digital signals to the LED array.
Background
Objec ves
Tasks
TIP: Restart the program a number of mes by pressing the Reset bu on on the programmer board.
Using delays Introduc on to microcontrollers
In this exercise, you learn how delays are used to slow down the PIC. Microcontrollers work
Introduc on
extremely quickly - a PIC can execute about 5,000,000 assembly instruc ons, every second. A
human can detect and understand only around three stable images per second. To allow the high-speed PIC to
communicate with ‘slow’ humans, we some mes need to slow it down by adding Delay instruc ons.
Background
Objec ves
Tasks
1. Begin by opening the program created in the last exercise (Exercise 1).
add Delay icons and configure them so that the output states can be viewed comfortably even at ‘HS oscillator’
speed;
save the program and download it to the PIC tes ng the program on the E-blocks boards.
TIP: Do not test this in simula on mode - simula on ming is not always accurate because it runs under a
Windows opera ng system and not in ‘real me’.
Using connec on points Introduc on to microcontrollers
A Connec on Point, or ‘goto’ instruc on, is o en used to create an infinite loop - to repeat a
Introduc on
set of instruc ons over and over again. (A be er way to do this is to use a ‘Loop’ instruc on.)
The advantage of a Connec on Point is that it can be used jump out of a loop to a certain loca on in the program.
The idea of pulse-width modula on (PWM) is introduced as a means of controlling LED brightness.
Background
Objec ves
Tasks
Modern microcontrollers, like the PIC, are able to do simple mathema cal tasks with 8-bit
Introduc on
numbers at very high speed. As the calcula ons get more complex or the numbers rise above
an 8-bit value, then the execu on me lengthens drama cally. Flowcode allows complex calcula ons using up to
16-bit numbers and takes care of all the complexi es. However, these may slow down execu on of the program.
Background
Variables - Example 1. Adding digital inputs - Where's the fire?
Flowcode Wiki - Crea ng variables.
Digital inputs - Example 1. Adding digital inputs - Where's the fire?
Flowcode Wiki - Calcula on icon proper es.
Sec on 1 - Introduc on to microcontrollers.
Objec ves
Tasks
Introduc on
Repea ng a set of instruc ons, for an exact number of mes, WHILE or UNTIL a
condi on is met is one of the most powerful programming opera ons.
TIP: The slow simula on or 'Step Over' func on in the Flowcode simulator is useful to debug complex
programs.
Create and use a ‘running light’ program, using the ‘mul ply-by-two’ method.
Objec ves
Create and use a ‘running light’ program, using the ‘shi -right’ method.
Create and populate an array.
Create a condi onal loop.
Tasks
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).
Use two ‘do-while’ loops to create an infinite sequence: Matrix[0]-Matrix[1]-Matrix[2]-Matrix[3]-
Matrix[2]-Matrix[1]-Matrix[0]-Matrix[1]-..... ;
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).
Inpu ng data Introduc on to microcontrollers
Introduc on
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.
Background
Objec ves
1. Write a program to show the status of the switches connected to a chosen port,
Tasks 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.
Introduc on
Earlier programs included simple decision-making, using loops and connec on 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.
Configure Decision icons and hence add condi onal branching to a program.
Objec ves
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:
when switch ‘0’ is pressed, ‘LB7’ lights;
when switch ‘1’ is pressed, ‘LB6’ lights;
and so on…
2. Write a program that creates an 8-bit counter, coun ng from ‘0’ to ‘255’ and then back to ‘0’ repeatedly:
using Decision icons instead of Loop icons.
using two switches connected to port B, bits 0 and 1;
coun ng up when switch ‘0’ is pressed;
coun ng down when switch ‘1’ is pressed;
displays the current count on the LEDs connected to Port A;
save this program, download it 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 un l switch ‘1’ is pressed before coun ng down to ‘0’:
using two switches connected to port B, bits 0 and 1;
displaying the current value of the count on the LEDs on Port A;
save this program, download it to the microcontroller and test it.
4. Write a program that makes all eight LEDs on port B flash on and off at a frequency of 1Hz, i.e. taking one second
for an ‘on-and-off’ cycle. In addi on:
the LEDs flash faster if switch ‘0’ is pressed;
they flash more slowly if switch ‘1’ is pressed;
save this program, download it to the microcontroller and test it.
Making decisions Introduc on to microcontrollers
Tasks
5. Write a program that makes all eight LEDs on port B light when switch ‘0’ is pressed the first me and go off
when it is pressed again:
Save this program, download it to the microcontroller and test it.
6. A car has two interior lights, one in the front of the car, the second in the rear.
Write a program to simulate this scenario using LEDs and five switches to control them.
Use switches ‘0’ to ‘3’ represent door switches that indicate if a door is open or not;
Use switch’4’ indicates that the boot (trunk) is open or not.
Light both LEDs when any door opens;
Light only the ‘rear’ LED when the boot is opened;
Save this program, download it 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.
Use a switch to control the le direc on-indicator (choose a relevant LED), which flashes on
for 250ms and then off for 250ms repeatedly un l the switch is released.
Use another switch to control the right direc on-indicator (choose a relevant LED), in the same way.
Use two LEDs as brake lights controlled by a switch which light up for as long as it’s pressed.
Create headlights which light when a switch is pressed and stay on un l it is pressed again.
Finish off with a pair of foglights in the same way.
TIP: Don’t a empt to write this program all at once. Divide it into subsec ons and solve each
separately before pu ng them all together.
To make it easier, use the labelling feature of Flowcode to label switches and LEDs.
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?
Programming LCDs Introduc on to microcontrollers
Introduc on
Background
Objec ves
Create, populate and manipulate string variables.
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 bo om 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 a ached to the first port. Every me 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 a ached to the first port on the LEDs of the second
port and on the top line of the LCD and then:
mul ply this binary number by 100.
display the result on the bo om line of the LCD, with “[x 100 = ]” displayed in front of it.
Programming LCDs Introduc on to microcontrollers
Tasks
5. Write a program that scrolls the lines of text given below, one line at a me. Ini ally, the text is
centred on the bo om line of the display for 2s. Then it moves up to be centred on the top line for 2s, to
be replaced on the bo om line by the next line of text, and so on.
Text:
Introduc on
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 bu ons on the
keypad, yet the keypad is connected to the microcontroller by only eight lines. This problem is solved by using
mul plexing.
Objec ves
Input text and numbers from a keypad and display messages on the LCD.
Use ASCII code to transmit this data.
Use mul plexed inputs.
Configure a Component macro for the keypad.
4. Write a program to use the keypad, as on a mobile phone, to input text to the microcontroller.
Use ASCII code to transmit the data.
Use the character ‘*’ for a space.
Clear the display when ‘#’ is pressed.
Display a message on the bo om row when the text has more than ten characters.
Analogue inputs and the EEPROM Introduc on to microcontrollers
Introduc on 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 wri ng.
Background
LCD - Exercise 8 - Programming LCDs.
Flowcode Wiki - String manipula on func ons.
Sec on 1 - Introduc on to microcontrollers.
Sec on 2 - Using E-blocks.
Objec ves
Create data loggers, using 8-bit and 10-bit data from the ADC.
Configure an analogue input.
Enter data via switches.
Enter informa on from light and temperature sensors.
Configure and use the EEPROM.
Scroll through EEPROM data.
Display text and numerical data on the LCD.
In code-based programming languages, like ‘C’ and ‘BASIC’, a so ware macro would be called
Introduc on
a ‘subrou ne’ or ‘func on’ or ‘procedure’. As programs get bigger, they use certain
combina ons of instruc ons over and over again. These programs become harder to understand and read.
Rou nes that are re-used can be put into a so ware macro, which can be called whenever it is needed in the main
program. Making use of these so ware macro’s ‘lightens up’ the main program and makes it much easier to read.
Background
Flowcode Wiki - So ware macro icon proper es
Sec on 2 - Using E-blocks
Objec ves
Use so ware macros to simplify the structure of a program.
Create so ware 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:
switch ‘0’ selects one of three programs (which you developed earlier);
‘X’: an 8-bit binary up-counter, displayed on the LEDs.
‘Y’: an 8-bit binary down-counter, displayed on the LEDs.
‘Z’: an 8-bit bidirec onal ‘running light’, displayed on the LEDs.
the LCD displays a text message iden fying the selected program;
switch ‘1’ ac vates the chosen program when pressed.
the three programs are placed in so ware macro’s.
In earlier exercises, the microcontroller did not necessarily react to inputs straight away
Introduc on
because it was busy doing something else. The external interrupt features of the PIC solve
this problem. On a 16F1937, 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 ini alized correctly, then a change on port B can cause the
program to stop execu on immediately and switch to execu ng the appropriate interrupt macro. We then have
what is called a ‘real me’ execu on.
Background
Sec on 2 - Using E-blocks.
Flowcode Wiki.
Objec ves
Create and use single-pin interrupts.
Create and use interrupt-on-change (IOC) interrupts.
Use real me opera on of a microcontroller.
Tasks
1. Write a program to me 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.
TIP: The LCD should display numbers from 1 to 12, one a er the other, over and over again rapidly, at 20 ms
intervals - much to fast to see with a human eye.
Tasks
modify program 3 to limit the me allowed to the size of the used variable and:
displays a message is displayed on the LCD when this size is exceeded;
includes a trap to prevent chea ng by simply holding down switch ‘0’ con nuously.
download this program to the microcontroller and test it.
Using mer interrupts Introduc on to microcontrollers
Introduc on
The other type of interrupt func on in Flowcode is the mer interrupt. These allow you to perform so ware tasks
at precisely predetermined me intervals - a really useful feature when developing me cri cal applica ons and
clocks.
Background
Flowcode Wiki - What is a 7-segment display?
Sec on 2 - Using E-blocks.
Objec ves
Create and use mer interrupt.
Use the prescaler to create accurate me intervals.
Trigger the mer using the crystal or an external event.
Timer arithme c
The 16F1937 has several mers, but we look at only two: ‘TMR0’ (Timer 0) and ‘TMR1’ (Timer 0).
TMR0 can be triggered by the crystal or by a transi on 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 me this 8-bit mer ‘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 mes per second and so the mer interrupt macro is
executed 75 mes per second.
Instead of using the crystal, this mer 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 transi on on the ‘T1CKI’ pin ‘RC0’.
Its opera on is similar to that of TMR0, except that it uses different prescaler values.
Tasks
1. Write a program to produce a precise ‘seconds’ mer that displays the result on the LCD and starts
when the microcontroller is reset. Use a 1s delay. Don’t use a mer interrupt.
(Download this program to the microcontroller and test it using your watch).
Rewrite the program using a mer interrupt.
2. Write a program to create a basketball mer that starts when switch 0 is pressed and displays the me
elapsed on the LCD. Make the LEDs flash on and off when 30s has elapsed (the me allowed for the team
with the ball to make a goal a empt).
TIP: Use a single-bit interrupt on pin RB0 to start the ming.)
Using mer interrupts Introduc on to microcontrollers
Tasks
3. Write a program to produce a precise clock that displays the me elapsed since the last reset, in hours,
minutes and seconds on the LCD (test with a watch).
Modify this program so that:
switch ‘0’ stops the clock when pressed the first me.
switches ‘1’, ‘2’ and ‘3’ can be used to change the displayed me to the actual me.
switch ‘0’ restarts the clock when pressed a second me.
4. Write a program to produce a mer that counts down from 01:00:00 to 00:00:00 in seconds and then
lights all the LEDs.
1. Develop a dimmer for all the LEDs that reacts to measured light intensity.
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.
Use the LEDs to simulate the dimmed lights. This is done by programming a so ware PWM output to all LEDs
on port B. When the PWM ‘on’ me increases, the LEDs get brighter, etc.
Put this program in a mer interrupt macro.
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.
The period of the PWM signal stays a constant 20ms at all mes, set using a mer interrupt.
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.
Using a similar approach, develop a temperature controller for an incubator. The BL0129 Grove
Sensor board can be used with the Grove Temperature sensor module. Use the LEDs to simulate the ac on 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.
Design a program to combine the judges’ votes into a pass/fail verdict.
Create two LED light sequences, one to indicate pass and the other fail.
3. Design an automa c watering system for a sealed terrarium (glass plant container). Use the Grove Temperature
and Humidity sensor module to sense when the terrarium needs watering.
The output device is a motor-driven pump that runs for a set period of me once triggered. There should be a
‘rest’ period a er watering before the system can operate again.
4. Create a combina on lock, using the BL0138 Keypad board to input a four-digit ‘PIN’.
Add a feature that ‘locks out’ a user a er three unsuccessful a empts.
Modify it to prevent further access to the system for a period of me such as ten seconds.
Use the LCD display to show the numbers selected on the keypad and the number of a empts 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 BL083 Relay board.
6. Use the Grove Infrared Receiver sensor module to me 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 15through one
complete circle and then reverses back to its ini al posi on in the same manner.
Introduc on to microcontrollers
Appendix 1: Arduino
adjustments
Appendix 1 Introduc on to microcontrollers
ARDUINO: SECTION A
The board has three ports, labelled A0-A5, D0-D7 and D8-D13.
Port D0-D7 offers full 8-bit func onality.
Port A0-A5 and D8-D13 has 6-bit func onality.
It can be powered from an external power supply, delivering 7.5V to 9V or from a USB supply.
If the Reset switch is pressed, the program stored in the Arduino will restart.
The board is USB programmable via a programming chip. This takes care of communica on
between Flowcode and the Arduino device.
The Arduino executes one instruc on for every clock pulse it receives.
(Note - a single instruc on is NOT the same as a single Flowcode symbol, which is compiled into C and
then into Assembly and probably results in a number of instruc ons).
This device uses a 16MHz crystal.
The board will detect whether External power supply or USB power supply should be used.
Use of the AVR ISP tool from Microchip via the ICSP header.
Usually supplied with an Arduino Uno device.
Provides power to the downstream E-blocks boards via the port connectors.
Contains the Matrix Ghost chip which allows for real me in-circuit debugging and pin monitoring
when combined with Flowcode.
Appendix 1 Introduc on to microcontrollers
ARDUINO: SECTION B
Selec ng Arduino in Flowcode
On opening Flowcode, you are presented with the ‘Welcome’ screen. Click on New Project.
Select Arduino Uno R3 PDIP from the Free targets list. Click “New <Arduino...” bu on above
This brings up the standard Flowcode environment. A flowchart can now be developed into a program
that can be tested within the Flowcode simula on mode, or saved and compiled to the Arduino board.
Follow the Examples and Exercises, taking Port changes into considera on where required.
E.g. Above is how Flowcode First Program (Page 42) would look to an Arduino user.
Here, Arduino users are using PORTC instead of PORTA.
(PORTC on the Arduino ’Maps’ to PORTA of the Combo board)
Appendix 1 Introduc on to microcontrollers
ARDUINO: SECTION DC
E-blocks2:
Eblocks2 uses the ‘Click’ boards for its SPI connec ons. Using the BL0106 ‘Click’ board E-block, you can
put the board into the (D8-D13) port as shown in the picture below:
Appendix 1 Introduc on to microcontrollers
ARDUINO: SECTION D
Se ng up the hardware:
This diagram shows you how to set up the E-blocks hardware with Arduino. Plug your Arduino into the
L0055 board as shown, then the combo board into the ports labelled (A0-A5) and (D0-D7).
Note: Despite having two hardware port connec ons between the EB0114 Development board and the
BL0055 Shield, the Arduino Uno can only provide 6 general purpose I/O connec ons on port C, (A0-A5).
Therefore, LEDs ‘6’ and ‘7’ and switches ‘6’ and ‘7’ on Port 1 of the Development board, cannot be used
with the Arduino Uno.
In order to program the Arduino Uno board directly from within Flowcode, you must ensure that the
appropriate drivers are installed. We recommend you visit the Arduino site and download the latest
drivers from there.
Appendix 2 Introduc on to microcontrollers
A1 Control hardware
I/O ca pa bi l i ti es – number, type (a na l ogue/di gi ta l ), ports
hardwa re speci fi ca ti on – bus wi dth, process or speed
memory – RAM, ROM
hardwa re fea tures – i nterrupts , s ta ck, PWM
re qui re d peri phera l s
cos t a nd a cce ss i bi l i ty
e ase of use
s oftware a nd progra mmi ng l a ngua ge
opera ti ng vol ta ges a nd power requi rements
A2 Input devices
Us er i nput:
di gi ta l – s wi tches a nd buttons
a na l ogue – control potenti ometer
Tempera ture
Thermi stor
tempe ra ture se ns ors
envi ronmenta l se ns or – tempera ture a nd humi di ty
Li ght
l i ght-dependent res i stor (LDR)
IR – phototrans i stor, photodi ode or IR recei ver
Movement/ori enta ti on
ti l t s wi tch
Pres ence
mi cro-swi tch
Ul tra soni c
Input i nterfa ci ng re qui re me nts
s i gna l condi ti oni ng
a na l ogue-to-di gi tal (ADC) convers i on
modul ar s ens or boa rds
PWM
s eri a l communi ca ti ons
Inte r-Integra ted Ci rcui t (I2C)
A3 Output devices
Optoel e ctroni c
l i ght-emi tti ng di ode (LED) – i ndi cator a nd IR
7-se gment di spl a y
l i qui d crysta l di s pl a y (LCD)
El ectromecha ni ca l
Rel ay
di re ct current motor
Servo
Audi o
buzzer or s i ren
s pea ker or pi ezo tra nsducer
Output i nterfa ci ng requi rements
power requi rements a nd dri vers
tra nsi stor output s ta ge
Rel ay
PWM
s eri a l communi ca ti ons
I2C devi ce i nterfa ci ng
A1 Control hardware
I/O ca pa bi l i ti es – number, type (a na l ogue/digi ta l), ports
ha rdwa re s peci fi ca tion – bus width, process or speed
memory – RAM, ROM
ha rdwa re fea ture s – i nterrupts , s ta ck, PWM
re qui red peri phera l s
cost a nd a cces s i bil i ty
ea se of us e
softwa re a nd progra mmi ng l a nguage
opera ting vol ta ges and power requi rements
A2 Input devices
Us er i nput:
di gi ta l – s wi tches a nd buttons
a na logue – control pote ntiometer
Tempera ture
The rmis tor
tempera ture s ensors
envi ronme nta l s ensor – tempera ture a nd humi dity
Li ght
l i ght-dependent resi s tor (LDR)
IR – phototra ns i s tor, photodiode or IR recei ver
Movement/ori entati on
ti lt switch
Pres ence
micro-swi tch
Ultras oni c
Input i nterfa cing requi rements
s i gna l condi ti oni ng
a na logue-to-di gi ta l (ADC) conversi on
modul a r s ensor boa rds
PWM
s eri a l communicati ons
Inte r-Integra te d Ci rcuit (I2C)
A3 Output devices
Optoel ectroni c
l i ght-emitting di ode (LED) – indi ca tor a nd IR
7-segme nt di s pl a y
l i quid crys ta l dis pl ay (LCD)
El ectromecha ni ca l
Rel ay
di re ct current motor
Servo
Audi o
buzzer or s iren
s pe aker or piezo transducer
Output i nterfa ci ng requi rements
power requi reme nts and dri vers
tra nsi stor output stage
Rel a y
PWM
s eri a l communicati ons
I2C devi ce interfa ci ng
C2 Documentation Project
A portfol io of evi dence produced
throughout the devel opment process .
Introduc on to microcontrollers
Version Control
29 11 21 Converted into Publisher and updated. Version 3.