Microcontroller Compete Course PDF
Microcontroller Compete Course PDF
com
Section: Contents
Introduction - p. 3
Section 1 - Intro to Microcontrollers - p. 12
Section 2 - Using E-blocks - p. 26
Section 3 - Intro to Flowcode - p. 31
Section 4 - Flowcode - First program - p. 42
Section 5 - Flowcode - Examples - p. 50
Section 6 - Programming Exercises - p. 72
Appendix 1 - Arduino adjustments - p. 88
Appendix 2 - E-blocks 1 adjustments - p. 93
Index - p. 98
In doing so, it offers substantial coverage of Unit 6 of the BTEC Level 3 National
Extended Diploma in Engineering (the precise mapping of the course to this
unit is given on page 9).
This course is mainly designed around the Matrix E-blocks 2 hardware platform, typically the
BL0011 programmer and the BL0114 Combo board, although separate E-blocks (LCD, switches,
LEDs, etc) can also be used.
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 or Eblocks1 devices. So in this course, whenever there is change in
the instructions for Eblocks1 or 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.
E-blocks1 users will need the EB006v9 Multiprogrammer and the EB083 Combo board plus
connecting wires.
Flowcode
http://www.matrixtsl.com/flowcode/support/
E-blocks
http://www.matrixtsl.com/eblocks/resources
http://www.matrixtsl.com/eblocks/boards
Other Help
http://www.matrixtsl.com/mmforums/index.php
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 software.
http://www.matrixtsl.com/learning/
The Matrix ‘Learning Centre’ contains many different resources including articles, drivers,
curriculum.
Course Conventions
The following abbreviations are used in the course:
Abbreviation Meaning
ADC Analogue to Digital Converter
ALU Arithmetic Logic Unit
ASCII American Standard Code for Information Interchange
CPU Central Processing Unit
EEPROM Electrically Erasable Programmable Read Only Memory
EPROM Erasable Programmable Read Only Memory
GND ground
Hex hexadecimal
IDC Insulation Displacement Connector
I/O Input / Output
ISP In-System Programming
JPEG Joint Picture Expert Group (standard for images)
LCD Liquid Crystal Display
LED Light Emitting Diode
LVP Low Voltage Programming
LDR Light Dependent Resistor
LSB Least Significant Bit
MSB Most Significant Bit
NVRAM Non-Volatile Random Access Memory
PIC Peripheral Interface Controller
PROM Programmable Read Only Memory
PSU Power Supply Unit
RAM Random Access Memory
RV1 Resistor-Variable 1
SPI Serial Programmable Interface
XTAL crystal
ZIF Zero Insertion Force
+V positive supply voltage
Most of the exercises can also be completed using the Arduino Uno Shield (BL0055). However,
these require different PORT settings.
01 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.
02 Change the logic level of a one single pin. 33 Use temporary memory.
03 Configure an output icon. 34 Create, populate and manipulate string variables.
04 Use binary code. 35 Control the display of text and numbers on a LCD.
05 Manipulate logic output levels. 36 Use a LCD as an output device for the PIC MCU.
06 Use LED’s to display an output. 37 Configure a Component macro for the LCD.
07 Compile a program to the PIC MCU. 38 Input text and numbers from a keypad and
08 Add a delay to slow down execution display messages on the LCD.
of a program. 39 Use ASCII code to transmit this data.
09 Change the delay interval. 40 Use multiplexed inputs.
10 Configure a delay icon. 41 Configure a Component macro for the keypad.
11 Control the speed of a microcontroller. 42 Create data loggers, using 8-bit and 10-bit data
12 Use an oscilloscope to time events. from the ADC.
13 Use Connection Points to introduce 43 Configure an analogue input.
unconditional branching in a program. 44 Enter data via switches.
14 Introduce PWM as a means of controlling the 45 Enter information from light and
brightness of LEDs. temperature sensors.
15 Create an infinite loop. 46 Configure and use the EEPROM.
16 Manipulate logic output levels. 47 Scroll through EEPROM data.
17 Use LEDs to display an output. 48 display text and numerical data on the LCD.
18 Create and use a variable. 49 Use the E-blocks prototype board.
19 Configure a calculation icon to perform 50 Use software macros to simplify the
arithmetic and logic calculations. structure of a program.
20 Create and manipulate variables. 51 Create software macros.
21 Perform calculations. 52 Use closed loop control.
22 Use LEDs with current limiting resistors. 53 Use PWM to control the brightness of LEDs.
23 Create and use a ‘running light’ program, 54 Create and use ‘single-pin’ interrupts.
using the ‘multiply-by-two’ method. 55 Create and use ‘interrupt-on-change’
24 Create and use a ‘running light’ program, (IOC) interrupts.
using the ‘shift-right’ method. 56 Use real time operation of a PIC MCU.
25 Create and populate an array. 57 Create and use timer interrupts.
26 Create a conditional loop. 58 Use the prescaler to create accurate
27 Input data from switches. time intervals.
28 Use loops to create LED sequences. 59 Trigger the timer using the crystal or an
29 Configure an input icon. external event.
30 Configure decision icons and hence add
conditional branching to a program.
(Mapping to Unit 6 of the BTEC Level 3 National Extended Diploma in Engineering is given on page 9).
A1 Control hardware
I/O capabilities – number, type (analogue/digital), ports
hardware specification – bus width, processor speed
memory – RAM, ROM
hardware features - interrupts, PWM
- stack
required peripherals
cost and accessibility
ease of use
software and programming language
operating voltages and power requirements
A2 Input devices
User input:
digital – switches and buttons
analogue – control potentiometer
Temperature
temperature sensors
environmental sensor – temperature and humidity
Light
light-dependent resistor (LDR)
IR – phototransistor, photodiode or IR receiver
Movement/orientation
tilt switch
Presence
micro-switch
ultrasonic
Input interfacing requirements
signal conditioning
analogue-to-digital (ADC) conversion
modular sensor boards
PWM
serial communications
Inter-Integrated Circuit (I2C)
A3 Output devices
Optoelectronic
light-emitting diode (LED) – indicator and IR
7-segment display
liquid crystal display (LCD)
Electromechanical
relay
direct current motor
servo
Audio
buzzer or siren
speaker or piezo transducer
Output interfacing requirements
power requirements and drivers
transistor output stage
relay
PWM
serial communications
I2C device interfacing
B1 Programming techniques
Use of a programming development environment
software operation
connecting to microcontroller hardware
creating and managing program files
syntax/error checking
simulation
compiling, downloading and live testing
monitoring/debugging
safe use of computer and display
Coding practices:
device set-up and program initiation
introductory comments
chip set-up
pin modes
Libraries
Declarations
efficient/effective code authoring
code syntax
in-line commenting
code organisation and structure
B2 Coding constructs
Input/output
digital – bit and port level read/write
analogue read/write, resolution, calibration
tone and sound generation
pulse and PWM
communication, including serial and I2C
Program flow and control:
calling libraries
subroutines and functions
control structure sequence iteration
– if, else, switch, case, for, do, while, until and end
delays and timing
Interrupts
Logic and arithmetic
variables – data types (Boolean,
character, byte, integer, word, float, long, double, string)
arrays
comparative operators:
=, not =, <, >, < or =, > or =.
Boolean operators – AND, OR, NOT
logic using input condition
– digital and analogue
arithmetic operations
B3 Number systems
bits, bytes
parallel and serial
binary to decimal conversion
C2 Documentation Project
A portfolio of evidence produced
throughout the development process.
Key
Symbol Meaning
Content covered by the course
Content partly covered by the course
Content not covered by the course
Project Content addressed through project work
Microcontrollers
At their heart (or is it brain?) there is a Central Processing Unit (CPU). This processes the digital
signals, does calculations and logic operations, creates time delays, and sets up sequences of
signals.
How does it know what to do? It is following a program of instructions, stored in Section of the
memory, called the program memory, inside the microcontroller.
From time to time, 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 activities 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 instructions 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 connections (often referred to as bits). An 8-bit port
handles an 8-bit (or one byte) number.
Information 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.
For example, the table shows how the speed of a car changes over a period of time.
Time in seconds Speed in kilometres per hour
0 0
10 15
20 21
However, you might wonder what
30 25
happened at time 35 seconds.
40 22
Was the car moving faster or slower
50 20 than 25 km/h at that moment?
60 16
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 time, the output voltage could change as
shown in the diagram. This is an analogue signal.
Digital Data
A digital signal carries its information 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 positive supply, 5V in this case.
This could represent the binary number 1.
(Note - if the positions 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.
For example, if the biggest analogue voltage is 5V, and a microcontroller has an 8-bit ADC:
• the highest 8-bit number is 1111 1111 (= 255 in decimal).
• the first step is 0000 0000 (= 0 in decimal).
• meaning that there are 256 voltage levels.
• 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.
Analogue sensors must be attached to the pins labelled with an 'ANx' (ANalogue) label. These,
found on ports A, B and E, can handle analogue signals between VDD (5V) and VSS (Gnd).
Most pins have alternative functions. For example pin 25 is labelled as 'RC6/TX/CK', meaning that it
can be Register C bit 6, or the transmit (TX) pin of the internal serial interface, or the ClocK pin of
the internal serial interface.
Fortunately Flowcode takes care of the internal settings that dictate pin functionality for you.
Outputting data
The microcontroller is a digital device - we have said that several times 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.
Storing Data
Electronic sub-systems that store data are known as
'memory'. They can store only digital data. Address
Data stored
One item of data is stored in one location in the memory. This In decimal In binary
data could be the correct combination to disarm a burglar 0 000 11101001
alarm, or the target temperature of a car engine block.
1 001 00100101
Each memory location has a unique address, a number used
2 010 10000101
to identify the particular location. This means that we can
draw up a map of the memory, showing what data is held in 3 011 11001101
each location (the decimal version of the address is included 4 100 01110100
to make the table easier to read). 5 101 00011011
6 110 11110011
7 111 10000101
Electronic systems only understand binary numbers. This very small memory has eight locations
(notice that numbering normally starts at 0). It needs a 3-bit binary number to create unique
addresses for each location. We can store items of data that are eight bits long (one byte - 1B).
Our example memory could be called a 8 x 1B memory. Memory systems used in computers are
much larger. Data is often stored as 32 bit numbers, allowing the use of much larger numbers.
There are many more locations, too. A typical computer memory now has millions of memory
locations.
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.
Read Only Memory (ROM)
These devices are normally only read (i.e. the contents are accessed but not changed / written,)
during the running of a program.
• The contents are not volatile (the data remains stored even when the power supply is switched
off).
• They are often used to store the basic programs, known as operating systems, needed by
computers.
• The group includes:
• PROM (Programmable Read Only Memory)
• EPROM (Erasable Programmable Read Only Memory)
• EEPROM (Electrically Erasable Programmable Read Only Memory)
A PROM is a one-shot device, which arrives blank, ready to receive data. Data can then be 'burned'
into it, but only once. After that it behaves like a ROM chip that can be read many times 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 microcontrollers 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 stick) and in home
video games consoles.
Microcontroller Memory
Microcontrollers 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
organisation 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 instructions, along with any data needed to carry
them out.
The only thing microprocessors understand is numbers. There's a problem because we don't speak
in numbers, and they don't understand English.
There are two solutions, 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 swift 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.
The Hex code is then sent into the microcontroller, using a subsidiary program called 'Mloader'.
When you select Build > Project Options... Configure from the Flowcode menu, you can control a
number of options and configurations by setting 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.
During programming the microcontroller stops while the program is being loaded. When that is
completed, it then restarts and runs the downloaded program.
Different types of Microcontroller
There are a large number of microcontroller devices available, from the humble 16F84 to larger
more complex microcontrollers such as the 40 pin 16F1937. Different microcontrollers have
different numbers of ports, or I/O pins, analogue inputs, larger memory, or advanced serial
communications capabilities such as RS232 or SPI bus.
PIC16F18877 Architecture
As an example we will use the 16F18877 microcontroller. It is important that you understand a
little more about what it does and how to use it. This section details the pins that are available on
the 16F18877 and the connectors they use on the E-blocks programmer board.
At this point in a traditional programming course, you would be introduced in some detail to the
various internal circuit blocks of the microcontroller. You would need this information to write
code for the microcontroller in C or assembly code.
No need - Flowcode takes care of these details.
16F18877 Microcontroller
Layout:
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 microcontroller.
• You can read from, and write to it and it is retained, even after a power cut.
• The Flash memory contained in the 16F18877 can store up to 32768 program
commands.
RAM
• Data from inputs, outputs, analogue inputs, calculations 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 time 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 time the power cuts or a reset
occurs.
• The EEPROM of the 16F18877 can store up to 256 bytes of data.
ALU
• The ALU (Arithmetic Logic Unit) is at the heart of the microcontroller’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
microcontroller using the 8-bit wide data-bus.
• The ALU needs four external oscillator clock pulses to execute one whole instruction.
• How the ALU works is very complicated. Fortunately Flowcode programmers do not need to
know how it works.
Timer 1 (TMR1)
• This timer interrupt is used to provide the microcontroller with exact timing information.
• 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 resulting 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.
• After this finishes, the main program continues from where it left off just before the interrupt.
For example:
External clock oscillator frequency (crystal oscillator) 19 660 800 Hz
System Clock (four clock pulses per instruction) 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 times per second.
Timer 0 (TMR0)
• This timer interrupt also provides the microcontroller with exact timing information.
• It is ‘clocked’ either by the system clock or by an external clock on pin RA4.
• This system clock runs exactly four times 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.
• After this finishes, the main program continues from where it left off just before the interrupt.
For example:
Result: TMR0 interrupts the main program and execute the TMR0 macro 75 times per second.
Introduction to ‘clocks’
Every microcontroller needs a clock signal to operate. Internally, the clock signal controls the speed
of operation and synchronises the operation 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 alternative to a crystal oscillator. It is fine for applications that are not timing critical, but is
not covered in this course.
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 software, allowing users to test and
develop their Flowcode programs. Programs can be compiled directly to the boards,
providing ideal development environments.
Upstream boards
'Upstream' is a computing term indicating a board that controls the flow of information in a
system. They are usually programmed in some way.
Any device which contains 'intelligence' and can dictate the direction of flow of information on the
bus can be thought of as an 'upstream' device.
Examples include microcontroller boards, and Programmable Logic Device boards.
Downstream boards
‘Downstream’ boards are controlled by an ‘upstream’ board, but information 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:
For Arduino programmer overview please refer to Appendix 1, SECTION A (page 89).
For E-blocks1 programmer overview please refer to Appendix 2, SECTION A (page 94).
• 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 position, 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 position, port A is switched to the analogue sensor section of
the board, so that pin RA0 is connected to the on-board light sensor and pin RA1 is connected
to the potentiometer to give a variable output voltage, (simulating the action of an analogue
sensing subsystem).
Note: With the switch in the ANA position, 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 activated.
• 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 complexities, unseen by the user.
For E-blocks1 combo board (EB083) overview please see Appendix 1, SECTION B (page 95).
xxxxxxxxxxxxxxxxxxxxxxxxxx
Flowcode allows you to create microcontroller applications by dragging and
dropping icons on to a flowchart to create programs. These can control external
devices attached 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.
Introduction to Flowcode
This section allows those who are new to Flowcode to understand how it can be used to develop
programs. It allows you to create programs step-by-step to learn about how Flowcode works.
We advise that you work through every section to familiarise you with all of the options and
features of Flowcode and introduce you to a range of programming techniques. As you work
through each Section, please also refer to the Flowcode help file. The main Flowcode icons are
introduced in turn.
What is Flowcode
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 and configure them to create the
program.
3. Add external devices by clicking on the buttons in the components toolbar.
4. Edit their properties, including how they are connected to the microcontroller, and configure
any macros they use.
5. Run the simulation to check that the program behaves as expected.
6. Transfer the program to the microcontroller by compiling the flowchart to C, then to assembler
code and finally to object code.
Flowcode overview
The Flowcode environment consists of:
• a main work area in which the flowchart windows are displayed.
• a number of toolbars that allow icons and components to be added to the flowchart.
• the System and Dashboard panels that display the attached components and provide basic
drawing capabilities.
• the Project Explorer panel that shows project variables, macros and component macros.
• the Icon List panel that shows bookmarks, breakpoints and search results.
• windows that allow the status of the microcontroller to be viewed.
• windows that display variables and macro calls when the flowchart is being simulated.
Flowcode can be used in a dark or light style Goto > View > Style > Light / Dark
Components toolbar
Connect external components to the microcontroller or use basic panel drawing
commands. Components are grouped in different categories that appear as drop down
menus. Click on a component and it will be added to the microcontroller and appear on
the panel. The pin connections and properties of the component can then be edited.
Normally positioned on the TOP left hand side of the screen next to the Icons toolbar
this toolbar, it can be undocked.
Menu and simulation toolbar
• Open and save files.
• Undo and redo actions.
• Print out your flowchart.
• Control the simulation and download functions.
More details on these panels are found in the 'Flowcode - Getting Started Guide’.
(View > 3D: System Panel) / (View > 2D: Dashboard Panel)
Properties panel
All items on the panel, including the panel itself, have associated properties
that are displayed in the Properties pane when the item is selected.
Some are read-only while others can be manipulated.
Some, like size and position, change as you interact with the item.
Others allow access to more advanced features of the selected item.
The Properties pane typically docks to the right hand side of the screen but
looks like this when undocked:
(View > Panel Properties)
Project explorer
The buttons along the top of this panel allow you to select Ports, Globals,
Macros and Components.
• Ports - variable names assigned to the microcontroller ports.
• Globals- any constants and variables that have been defined for use in the
current project.
• Macros - user-created macros in the current program and allows the user to
drag them into the current flowchart.
• Components - similar except that it also lists components that are present in
the panel.
(View > Project Explorer)
Icon list
All bookmarks, breakpoints and disabled icons are listed,
together with search and error results.
(View > Icon Lists)
Chip window
The pinout for the currently selected microcontroller chip is displayed.
When the flowchart is being simulated, the state of each
microcontroller I/O pin is shown as red or blue, for ‘high’ or ‘low’
outputs respectively.
(View > Chip)
To undock a docked toolbar, simply click and hold on the toolbar grab bars (the speckled area at
the top or side of the toolbar) and drag the toolbar to its new position.
A red star alongside an icon indicates that the flowchart has not
been saved in its current form.
Simulation
When simulating a program in Flowcode a red
rectangle around an icon indicates the icon to be
executed next.
Simulation debugger
When simulating a flowchart, the
current values of any variables used in
the program appear in this window.
These are updated after a command is
simulated (unless the simulation is
running at full speed - 'As fast as
possible').
If you press the pause button during simulation, you can click on a variable in this window to
change its value (allowing you to test the program under known conditions).
The window also shows the current macro being simulated under the Macro Calls section, useful
when one macro calls another during the simulation process.
Saving a Flowchart
To save a flowchart, select either the Save or Save As options from the File menu.
(File > Save / Save As).
Flowcharts must be saved before they can be compiled to C or transferred to a microcontroller.
Note that the current zoom rate is used to determine the resolution of the image saved. If you need
high quality images for printing then increase the zoom rate.
From the Save Image menu, you also have the option to save the current image of either the
Dashboard Panel or the System Panel
(File > Save Image > 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)
Global Options
The View menu also includes a Global Options area, offering a series of powerful tools to configure
the flowchart (Goto > View > Global Options) One open, select the appropriate Tab.
Flowchart Tab
This tab contains the settings for changing
font style and size and features of the icons.
Scheme Tab
This tab contains the settings for changing the
appearance of the flowchart, including icon colours
and graphics, background colours and patterns etc.
Annotation Tab
All the settings on this tab relate to manipulating
the annotations on the flowchart, including icon
text and descriptions as well as annotation and
tooltip styles.
It also the ability to add icon comments in C code.
Application Tab
These settings affect the look and ‘feel’ of the
overall program.
The skin pre-sets and tab options change the
general look of Flowcode. It also offers the ability
to print in colour and to change web access
settings.
The Override language option allows the user to
override the default Flowcode language settings
and to display Flowcode in a specified language.
To do this, select the language from those available
on the drop down list and restart Flowcode.
It will do so in the selected language, provided the
relevant language pack has been installed.
Editor Tab
Auto-edit new icons opens the Properties pane
when a new icon is added to the flowchart.
Use the Add icons comments to C code option to
include their associated comments when icons are
compiled to C code.
The Allow errors in flowcharts option allows you
to edit icon properties without triggering error
messages.
The Allow unconnected ports and pins option
allows you to change component connections to
unconnected without triggering an error message
(though these will still occur during simulation and
compilation).
Locations Tab
This allows you to choose the target directory that
Flowcode compiles to by default. It also allows you
to specify directories that Flowcode should search
when looking for components and dictionaries.
Scope Tab
The Data Scope allows the user to see the results
and values from raw data and from components
themselves. This data is displayed during
simulation and allows the user to monitor signals
selected on the various scope channels.
It can read and display data from a number of
different ports simultaneously. Adjusting the
timebase allows the user to view a small amount
of data at increased accuracy or larger amounts of
data.
http://www.matrixtsl.com/wiki/
You can also access the Flowcode wiki from inside the program
itself by going to the ‘Help’ section of the Main Toolbar and
clicking the Help… menu option from there. This will open up a
new internal window within Flowcode which will load the front
page of the Flowcode wiki.
http://www.matrixtsl.com/wiki/
You can also access the Flowcode wiki from inside the program
itself by going to the ‘Help’ section of the Main Toolbar and
clicking the Help... menu option from there. This will open up a
new internal window within Flowcode which will load the front
page of the Flowcode wiki.
xxxxxxxxxxxxxxxxxxxxxxxxxx
Adding digital outputs - Light the LED
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).
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 be-
tween the 'BEGIN' and 'END' boxes.
Output
Simulation mode
Stop (Shift+F5)
Save (Control+S)
Compile to chip
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).
In binary, the same thing happens, but a lot more often, because it
uses only 0s and 1s. Counting up starts with 0, then 1, then back to 0 Decimal Same in binary
with a 1 in front, making 10 (not ten - it's two) Next comes 11 (three) 1 1
and start again with two 0s but with a 1 in front, to give 100 (four) 2 10
and so on.
4 100
Notice that each time the binary 1 moves one place to the left, it 8 1000
doubles in value of the number in decimal.
We can use this idea to convert between number systems.
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.
• A hex digit has sixteen possible states.
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.
Tasks
All of these examples can be tried out using either a PIC or an Arduino
microcontroller.
The scenario
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.
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. 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.
Other variable issues
Floating point numbers (that contain a decimal point somewhere in them), can also be used,
although they represent a much wider range of values than an integer. They suffer a loss of
accuracy over large ranges.
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.
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.
• Change the value in the Delay value or variable box to 200 and then click on the ‘OK’ button.
This causes a 200 millisecond (0.2 second) delay when the Delay icon is activated. In other
words, the system just sits there and does nothing for 0.2 seconds.
• Now run the simulation again. Providing you don't keep it pressed for too long, you should find
that the LED array shows an increase of 1 each time you press the switch.
• The program now works satisfactorily, 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.
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.
Writing messages
• Run the program and the text will be sent to the LCD display.
There are a number of other useful functions in the LCD macro list:
Clear - Clears the display and resets the cursor position (where the display prints next,) to '0,0' i.e.
top left.
Cursor - Moves the cursor to the specified location. The two parameters, ‘X’ and ‘Y’ select the
horizontal and vertical positions of the cell respectively. ‘0,0’ is the top left cell, ‘0,1’ the first cell
on the second line, ‘3,2’ the fourth cell on the third line etc.
PrintNumber - Works like 'PrintString' but prints a number instead of a string. It can be used with
variables, or with actual numbers.
Using PrintNumber
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).
Example 4. Stopwatch
This example uses example 5 (Using PrintNumber) as a starting point.
• Expand the program from the previous example (Using PrintNumber) by dragging a Loop icon
below the PrintString Component Macro.
• Change the text in the PrintString Component Macro to "Hundredths" (with quotation marks).
• Drag a Calculation icon into the Loop.
• Create a variable called Count as an Int type (Initial value 0).
• Double-click on the Calculation icon. In the Calculations text box type Count = Count + 1
(This will add 1 to the value of variable count every time the icon is executed).
• Next drag another Component Macro into the Loop.
• Double-click the Component Macro and find Cursor under the LCD macros.
• Enter 0,1 as parameters to position the cursor on the first character of the second line.
• Next, drag another Component Macro onto the workspace.
• Select PrintNumber and enter Count as the parameter.
• Now, drag a Delay icon into the flowchart and set the delay to 10ms (which equals one
hundredth of a second).
• The counter will count (approximately) the time elapsed in hundredths of seconds.
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).
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.
• There are three ways to simulate the program step-by-step:
• Click on Run on the Main toolbar and on the Step Into button (Run > Step Into)
• Press the F8 function key on the keyboard.
• Click on the Step Into button on the main toolbar in the simulation section.
Several things happen:
• a red rectangle appears around the BEGIN icon, showing that this is the current step.
• the Simulation debugger window appears (containing Variables and Macro Calls).
• the Variables section lists the three variables that you defined for this program, and
shows their current values (all zero at the moment).
Ignore the Macro Calls section 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 activate them.
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 (fifteen) 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 little 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 instruction just carried out).
• Press F8 again and the Variables section shows that input now contains fifteen.
• Press F8 again and the calculation is carried out. The sum variable stores the result.
• Press F8 again. The value stored in sum is transferred to the LED array.
It looks like:
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.
• Repeat the same procedure using different numbers and step through the program to check
what the sum of the numbers is.
TIP: Explore adding graphics to your binary calculator to make it easier to read.
Goto > Shapes > Labels to add digits above your LEDs.
• Configure the other input icon to store the state of the control switch (on port A bit 1) in
the variable ‘control’.
• The upper calculation icon checks to see whether the door AND the control switch have
been pressed.
Configure it using the equation output = control & door.
The & signifies the AND operation.
The result of this operation (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 calculation is 0, the program follows the ‘No’ route from the decision
icon and the left-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 calculation 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 calculation icon reduces the number stored in the variable ‘count’ by one.
Configure it using the equation count = count - 1
• The initial value of ‘count’ is ten. Provided the number stored in ‘count’ has not reached zero,
the program follows the ‘No’ route. Eventually, after looping enough times, 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.
• Now simulate the program step-by-step, using the F8 function key repeatedly.
• Check what happens for different combinations 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 operating?
For Arduino the Ports need to be set to PORTC and PORTD (equivalent to A and B on the Combo board).
• When the result of the calculation 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.
• Add a switch array to the System Panel. Configure it to have three switches, one connected to
port A, bit 0, one to portA, bit 1 and the other to port A, bit 2.
• Add an LED connected to port B, bit 0 to represent the interior light in the car.
• Add labels to the System Panel to identify the components and position them as shown in the
diagram Goto > Shapes > Labels.
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?
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.
The section ends with further Challenges. These are even more open-ended and
contain only a brief specification.
This exercise configures Flowcode to output specific digital signals to the LED array.
Background
Objectives
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 mask-
ing. 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.
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.
Background
Objectives
Tasks
1 Begin by opening the program created in the last exercise (Exercise 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’.
Tasks
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.
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.
Background
Objectives
Tasks
Modify your program to display the result of the following calculations on the LEDs of port B:
2 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).
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
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:
Matrix[0]-Matrix[1]-Matrix[2]-Matrix[3]-Matrix[2]-Matrix[1]-Matrix[0]-Matrix[1]-..... ;
b) 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).
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
Objectives
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.
Objectives
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.
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).
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 the
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.
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?
Background
Objectives
Tasks
1 Write a program that displays the text “Hello World” in the centre of the bottom line of the LCD.
Write a program that shows an increasing count (decimal) on the LCD screen.
2 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).
Write a program to show the status of the switches attached to the first port. Every time
3 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.
Write a program to show the status of the switches attached to the first port on the LEDs of the
4 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.
Write a program that scrolls the lines of text given below, one line at a time. Initially, the text is
5 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).
• 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
Write a program to use the keypad, as on a mobile phone, to input text to the microcontroller.
4 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.
Background
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).
Modify the program from Task 1 to display data from the ‘pot’ on the Sensor board.
2 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.
TIP: Increase sampling rate so that you don’t have to spend 24 hours in testing.
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.
Background
Objectives
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).
• ‘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 bidirectional ‘running light’, displayed on the LEDs.
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.
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).
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 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.
• 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 BL0138 Keypad board to input a four-digit ‘PIN’.
• Add a feature that ‘locks out’ a user after three unsuccessful attempts.
• Modify it to prevent further access to the system for a period of time such as ten seconds.
• 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 BL083 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.
Design a system to drive the stepper motor on the Actuators training panel so that it rotates, in 150 steps,
8
through one complete circle and then reverses back to its initial position in the same manner.
• The board has three ports, labelled A0-A5, D0-D7 and D8-D13.
• Port D0-D7 offers full 8-bit functionality.
• Port A0-A5 and D8-D13 has 6-bit functionality.
• 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 communication
between Flowcode and the Arduino device.
• The Arduino executes one instruction for every clock pulse it receives.
• (Note - a single instruction 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 instructions).
• 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 time in-circuit debugging and pin monitoring
when combined with Flowcode.
This brings up the standard Flowcode environment. A flowchart can now be developed into a
program that can be tested within the Flowcode simulation mode, or saved and compiled to the
Arduino board.
Follow the Examples and Exercises, taking Port changes into consideration 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)
E-blocks2:
Eblocks2 uses the ‘Click’ boards for its SPI connections. Using the BL0106 ‘Click’ board E-block, you can
put the board into the (D8-D13) port as shown in the picture below:
E-blocks1:
On the SPI E-block move the “CHIP EN SELECTION” jumper to setting “2” and connect DAC_EN and
NVM_EN to the centre pins of the “PORT A MODE SELECT” jumper (J14) of the EB083 Combo Board:
Note: Despite having two hardware port connections between the EB0114 Development board
and the BL0055 Shield, the Arduino Uno can only provide 6 general purpose I/O connections 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.
E-BLOCKS1: SECTION A
EB006 Multiprogrammer
• The board has five ports, labelled ‘A’ to ‘E ‘.
• Ports ‘B’, ‘C’ and ‘D’ offer full 8-bit functionality.
• Port ‘A’ has 6-bit functionality, (8-bit if the internal oscillator is
selected).
• Port ‘E’ has 3-bit functionality.
• It can be powered from an external power supply, delivering
7.5V to 9V or from a USB supply.
• As pointed out elsewhere, no 5V connection is provided in
the D-type connector. This must be provided by an additional
connection to ‘downstream’ boards, using the screw
terminals on the Multiprogrammer board. The ground
connection is provided through pin 9 of the D-type connector.
IMPORTANT - DO NOT connect the 14V screw terminal to a 5V ‘downstream’ screw terminal.
• If the Reset switch is pressed, the program stored in the PIC MCU will restart.
• There is a 1:1 mapping between pins on the D-type connector and those on the ports, (e.g. Pin1
is connected to PB0, Pin 2 to PB1 etc.)
• The board is USB programmable via a programming chip. This takes care of communication
between Flowcode’ and the PIC MCU.
• The PIC MCU executes one instruction for every four clock pulses it receives.
• (Note - a single instruction 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 instructions.)
• This course uses a 19,660,800Hz crystal. The advantages of this frequency include:
• standard Baud rate (19200) is obtainable by dividing it by 1024;
• it can be further divided by 256 to give 75 Hz.
• Jumpers allow the user to select a number of options:
• external power supply or USB power supply;
• where the PIC MCU uses an internal oscillator, all eight bits of port A can be used for I/O
operation;
• use of an professional ICD2 (In-Circuit Debugger) tool from Microchip.
E-BLOCKS1: SECTION B
E-BLOCKS1: SECTION C
The diagrams show how the pins are numbered on the plugs and sockets. On
both plugs and sockets, bit 0 is delivered on pin 1, bit 7 on pin 8 and pin 9 is
designated 0V.
E-BLOCKS1: SECTION D
The next two diagrams show how to use the patch system on this board.
In the upper diagram, jumpers J12 and J13 are set to the ‘default’ position. This routes signals from
the light sensor and ‘pot’ to pins 1 and 2 of the D-type plug, respectively.
However, when using a different microcontroller, you might want the signal from the ‘pot’ to
appear on pin 5 of the D-type plug. To achieve this, move jumpers J12 and J13 to the 'patch'
position and add a wire from the ‘pot’ socket on ‘J11’ to pin 5 on J8, as shown in the lower
diagram.
Introduction
About this Course ................................................................................................................................. 3
What you will need ............................................................................................................................... 4
Course Conventions .............................................................................................................................. 6
Learning Objectives .............................................................................................................................. 8
Mapping to BTEC Level 3 National Extended Diploma in Engineering - Unit 6 ................................... 9
Section 1
What is a microcontroller? ....................................................................................................................12
Microcontrollers ....................................................................................................................................13
The Digital World ...................................................................................................................................14
The Analogue World ..............................................................................................................................14
Analogue Data .......................................................................................................................................15
Digital Data ............................................................................................................................................15
Analogue to Digital Conversion .............................................................................................................16
Inputting data into a microcontroller ....................................................................................................17
Outputting data .....................................................................................................................................17
Current Limits ........................................................................................................................................18
Storing Data ...........................................................................................................................................18
Types of Memory ...................................................................................................................................19
Read Only Memory (ROM) ....................................................................................................................19
Random Access Memory (RAM) ............................................................................................................19
PIC Memory ...........................................................................................................................................20
Programming .........................................................................................................................................20
The Flowcode Process ...........................................................................................................................21
Running the Program ............................................................................................................................21
Different types of Microcontroller ........................................................................................................22
PIC16F1887 Architecture .......................................................................................................................23
PORT A ...................................................................................................................................................22
PORT B ...................................................................................................................................................22
PORT C ...................................................................................................................................................22
PORT D ...................................................................................................................................................22
PORT E ...................................................................................................................................................22
Memory: ................................................................................................................................................23
ALU: .......................................................................................................................................................24
Timer 1 (TMR1): .....................................................................................................................................24
Timer 0 (TMR0): .....................................................................................................................................24
RBO External Interrupt: .........................................................................................................................25
PORT B External Interrupt: ....................................................................................................................25
A/D: ........................................................................................................................................................25
Busses: ...................................................................................................................................................25
Introduction to clocks ............................................................................................................................25
Section 2
Downstream boards ................................................................................................................................. 27
Upstream boards ..................................................................................................................................... 27
BL0011 PIC Programmer .......................................................................................................................... 28
BL0114 Combo Board .............................................................................................................................. 30
Connecting E-blocks together .................................................................................................................. 30
Using E-blocks on the bench .................................................................................................................... 30
Protecting E-blocks circuitry .................................................................................................................... 30
Section 3
Introduction to Flowcode ......................................................................................................................32
What is Flowcode ..................................................................................................................................32
Flowcode overview ................................................................................................................................32
The toolbars and panels .........................................................................................................................33
Icons toolbar .......................................................................................................................................... 33
Components toolbar .............................................................................................................................. 33
Menu and simulation toolbar ................................................................................................................ 33
Dashboard & System Panels .................................................................................................................. 34
Properties pane ..................................................................................................................................... 34
Project explorer .....................................................................................................................................34
Icon list ................................................................................................................................................... 34
Chip window .......................................................................................................................................... 35
Docking and undocking the toolbars and panes ................................................................................... 35
Flowchart window ................................................................................................................................. 36
Simulation Debugger window ............................................................................................................... 36
Starting a new Flowchart .......................................................................................................................37
Opening an existing Flowchart ..............................................................................................................37
Saving a Flowchart .................................................................................................................................37
Saving Flowchart Images .......................................................................................................................37
The View menu ......................................................................................................................................38
Global Options .......................................................................................................................................38
Flowchart Tab ........................................................................................................................................ 38
Scheme Tab ............................................................................................................................................39
Annotation Tab ...................................................................................................................................... 39
Application Tab ...................................................................................................................................... 39
Editor Tab ............................................................................................................................................... 39
Locations Tab ......................................................................................................................................... 40
Scope Tab ............................................................................................................................................... 40
Getting Help With Flowcode .................................................................................................................. 41
Section 4
Adding digital outputs - Light the LED ...................................................................................................42
The hardware ..........................................................................................................................................42
Setting up a New Project.........................................................................................................................43
Adding LEDs ............................................................................................................................................44
The flowchart .........................................................................................................................................44
Running the Simulation ..........................................................................................................................45
Changing LED properties .........................................................................................................................46
Changing the output ...............................................................................................................................46
Saving the Program ................................................................................................................................46
Compiling to Chip ...................................................................................................................................46
Changing port Settings ............................................................................................................................47
Binary Numbers .....................................................................................................................................48
Converting Numbers ..............................................................................................................................48
Working in Hex .......................................................................................................................................48
Hex in Flowcode .....................................................................................................................................48
Coding Constructs - Number Systems Worksheet .................................................................................49
Section 5
Example 1. Adding digital inputs - Where's the fire? ..........................................................................51
Setting up the flowchart ........................................................................................................................51
Creating the variables ............................................................................................................................51
More on variables ..................................................................................................................................53
Flowcode variables ................................................................................................................................53
Other variable issues .............................................................................................................................53
Why worry? ...........................................................................................................................................53
Setting up the outputs ...........................................................................................................................54
Adding the switches ...............................................................................................................................54
Simulating the program .........................................................................................................................54
Example 2. Using loops - Counting sheep ............................................................................................55
Setting up the flowchart ........................................................................................................................55
Creating the variables ............................................................................................................................55
Setting up the calculation ......................................................................................................................56
Configuring loop properties ...................................................................................................................56
When to test? ........................................................................................................................................56
Loop for a set number of times .............................................................................................................56
Setting up the input ...............................................................................................................................57
Setting up the output .............................................................................................................................57
Adding the LED array .............................................................................................................................57
Adding the switch ..................................................................................................................................58
Simulating the program .........................................................................................................................58
The solution: Adding a Delay .................................................................................................................59
Example 3. The LCD display - Posting messages ..................................................................................60
LCD displays ...........................................................................................................................................60
Adding the LCD component ...................................................................................................................60
Writing messages ...................................................................................................................................61
Other LCD functions ...............................................................................................................................61
Using PrintNumber - an example: .........................................................................................................61
Example 4. A stopwatch .......................................................................................................................63
Example 5. Using binary numbers - A binary calculator ......................................................................64
Setting up the flowchart ........................................................................................................................64
Creating the variables ............................................................................................................................65
Setting up the inputs ..............................................................................................................................65
Setting up the calculation ......................................................................................................................66
Setting up the output .............................................................................................................................66
Adding a LED array .................................................................................................................................66
Adding the switches ...............................................................................................................................66
Slow simulation ......................................................................................................................................67
Example 6. Binary logic in control ........................................................................................................68
A. Controlling the microwave oven .......................................................................................................68
Setting up the flowchart ........................................................................................................................68
B. Controlling interior light in a car .......................................................................................................70
Setting up the flowchart ........................................................................................................................70
Section 6
Exercise 1 - Creating Outputs.................................................................................................................... 73
Exercise 2 - Using Delays ........................................................................................................................... 74
Exercise 3 - Using Connection Points ........................................................................................................ 75
Exercise 4 - Performing Calculations ........................................................................................................ 76
Exercise 5 - Using Loops ............................................................................................................................ 77
Exercise 6 - Inputting Data ........................................................................................................................ 78
Exercise 7 - Making Decisions ................................................................................................................... 79
Exercise 8 - Programming LCDs ................................................................................................................ 81
Exercise 9 - Using the Keypad ................................................................................................................... 82
Exercise 10 - Analogue Inputs and the EEPROM ...................................................................................... 83
Exercise 11 - Using Software Macros ........................................................................................................ 84
Exercise 12 - Using External Interrupts ..................................................................................................... 85
Exercise 13 - Using Timer Interrupts......................................................................................................... 86
Additional Challenges ............................................................................................................................... 87
www.matrixtsl.com
CP4375