Microcontroller Compete Course
Microcontroller Compete Course
Microcontroller Compete Course
Arduino users need an Arduino Uno and E-blocks Arduino Uno Shield (EB093), shown below, as
well as the Combo board.
Part 1
Programming Exercises
Part 1 Contents
The hardware: ............................................................................................................................................. 7
Hardware jumper settings: ......................................................................................................................... 7
Flowcode 7 and download settings: ........................................................................................................... 7
Exercise 1 - Creating Outputs ..................................................................................................................... 8
Exercise 2 - Using Delays............................................................................................................................. 9
Exercise 3 - Using Connection Points ........................................................................................................ 10
Exercise 4 - Performing Calculations ........................................................................................................ 11
Exercise 5 - Using Loops............................................................................................................................ 12
Exercise 6 - Inputting Data ........................................................................................................................ 14
Exercise 7 - Making Decisions ................................................................................................................... 15
Exercise 8 - Programming LCDs ................................................................................................................ 17
Exercise 9 - Using the Keypad ................................................................................................................... 19
Exercise 10 - Analogue Inputs and the EEPROM ...................................................................................... 21
Exercise 11 - Using Software Macros ........................................................................................................ 23
Exercise 12 - Using External Interrupts ..................................................................................................... 24
Exercise 13 - Using Timer Interrupts......................................................................................................... 26
Additional Challenges: .............................................................................................................................. 28
The hardware:
Most exercises use the EB006 Multiprogrammer and EB083 Combo board, shown below.
(They can be supplied together as HP4832 - E-Blocks Development Board.)
The tables list the hardware and software settings used to test most programs.
Any changes to these are indicated in the instructions for the exercise.
EB006
Jumper settings
version 9
PIC device 16F1937
Target voltage 5V J15
Voltage source PSU J11
Programming Source USB J12,13,14: USB
Oscillator Selector OSC J18,19
Port A E-block E-blocks Combo board
Port B E-block EB083
Port C E-block
Port D E-block
Port E E-block
Creating Outputs
This exercise configures ‘Flowcode 7’ to output specific digital signals to the LED array.
Objectives:
to send different 8-bit codes to port B of the microcontroller;
to change the logic level of a one single pin of port B;
to configure an output icon;
to use binary code;
to manipulate logic output levels;
to use LEDs to display an output;
to compile a program to a microcontroller.
Relevant course content:
Part 6 - ‘Introduction to microcontrollers’;
Part 2 - ‘Using E-blocks’;
Adding digital outputs - “Light the LED”;
Flowcode Wiki - ‘Using masks’;
Instructions
Program 1:
create ‘Flowcode 7’ flowcharts that:
add a single output icon, configured to light all port B LEDs and run the simulation;
then alter the parameters to light only the odd-numbered LEDs and run the simulation;
do the same but for only the even-numbered LEDs;
finally do the same but for only the high ‘nibble’ bits (4 to 7) of port B.
modify this program by:
repeating these four steps using hexadecimal rather than decimal numbering;
lighting only the LED on bit 7, by sending an 8-bit value to the port;
lighting only the LED on bit 7, using the 'single bit' output method;
lighting only the LED on bit 7, using the 'masking' output method.
Program 2:
write a program that uses at least twenty outputs icons to write different values to port B, one
after the other:
use all four methods in this exercise - hexadecimal, decimal, single bit and masking;
simulate the program and review the results;
save the program and download it to the microcontroller;
restart the program a number of times by pressing the Reset button on the multipro-
grammer board.
Using Delays
Introduction:
In this exercise, you learn how delays are used to slow down program execution. Microcontrollers
work extremely quickly - a PIC can execute about 5,000,000 assembly instructions, every second.
A human can detect and understand only around three stable images per second.
To allow a high-speed microcontroller to communicate with ‘slow’ humans, we sometimes need to
slow it down by adding Delay instructions.
Objectives:
to add a delay to slow down execution of a program;
to change the delay interval;
to configure a delay icon;
to control the speed of a microcontroller;
to use an oscilloscope to time events .
Relevant course content:
Part 6 - ‘Introduction to microcontrollers’;
Part 2 - ‘Using E-blocks’;
Flowcode Wiki - ‘Loop icon properties’;
Instructions
Program 1:
open the program created in the last exercise (Exercise 1, Program 2):
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 microcontroller;
test the program on the E-blocks boards;
modify the length of the delays caused by the Delay icons:
start with a delay of 1s;
progressively reduce the delay until it is too fast for your eyes to detect the differ-
ent outputs states;
download the program to the microcontroller every time and test it on E-blocks.
use an oscilloscope to measure the delays you set up in ‘Flowcode 7’;
make a detailed drawing of the oscilloscope image, complete with voltage and tim-
ing information and the delay time used in the ‘Flowcode 7’ program.
Hint:
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’;
Introduction:
A Connection Point, or ‘goto’ instruction, is often used to create an infinite loop - to repeat a set of instruc-
tions over and over again. (A better way to do this is to use a ‘Loop’ instruction.) The advantage of a Con-
nection Point is that it can be used jump out of a loop to a certain location in the program.
The idea of pulse-width modulation (PWM) is introduced as a means of controlling LED brightness.
Objectives:
to use Connection Points to introduce unconditional branching in a program;
to introduce PWM as a means of controlling the brightness of LEDs.
to create an infinite loop;
to manipulate logic output levels;
to use LEDs to display an output;
Relevant course content:
Adding digital outputs - “Light the LED”;
Flowcode Wiki - ‘Connection point icon properties’;
Part 6 - ‘Introduction to microcontrollers’;
Part 2 - ‘Using E-blocks’;
Instructions
Program 1:
create a flowchart that uses Delay, Output and Connection Point icons to light the even and odd LEDs of
port B, alternately on and off, with a 300ms interval between, in an infinite loop;
test the program at first ‘step-by-step’ and then continuously in the ‘Flowcode 7’ simulator.;
use Delay, Output and Connection Point icons to flash the high nibble and low nibble LEDs of port B al-
ternately on and off, with a 300ms interval between, in an infinite loop;
download the program to the microcontroller and test it.
use Delay and Output icons to flash all the LEDs of port B on and off with a 500ms interval in between,
in an infinite loop;
download the program to the microcontroller and test it.
Hint:
Make the delays in these program very short and make the on and off times asymmetrical,
(e.g. on for 8ms and off for 12ms).
You have just designed a software PWM generator. (Search for ‘PWM’ on the internet for more infor-
mation.) 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.
modify program 1 by changing the ‘on’ and ‘off’ times in such a way that the total (‘on’ + ‘off’) time is
unchanged, e.g. on for 12ms and off for 8ms;
download the program to the microcontroller and test it - what is the difference?
Program 2:
write a program that:
lights LEDs on the four most-significant bits, (MSB,) of port B and keeps them on;
dims the intensity of the LEDs on the four least-significant bits, (LSB,) of port B, compared to the
four MSB LEDs, using PWM;
download the program to the microcontroller and test it.
use an oscilloscope to examine the signal controlling one of the four LSB LEDs;
make a detailed drawing of the oscilloscope image, complete with voltage and timing information and
the on and off times used in the ‘Flowcode 7’ program.
Performing Calculations
Introduction:
Modern microcontrollers, like the PIC, are able to do simple mathematical tasks with 8-bit num-
bers 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 7’ allows complex calculations
using up to 16-bit numbers and takes care of all the complexities. However, these may slow down
execution of the program.
Objectives:
to create and use a variable;
to configure a calculation icon to perform arithmetic and logic calculations.
to create and manipulate variables;
to perform calculations;
to use LEDs with current limiting resistors;
Relevant course content:
Variables - ‘Example 1. Adding digital inputs - Where's the fire?’
Flowcode Wiki - ‘Creating variables’;
Digital inputs -‘Example 1. Adding digital inputs - Where's the fire?’;
Flowcode Wiki - ‘Calculation icon properties’;
Part 6 - ‘Introduction to microcontrollers’;
Part 2 - ‘Using E-blocks’;
Instructions
Program 1:
create a flowchart that:
uses a variable called ‘counter’ containing an initial value of ‘1’;
displays the value stored in the variable ‘counter’ on LEDs.
simulate the program to test that it works.
modify Program 1 by:
adding a Calculation icon to double the value stored in the variable ‘counter’;
displaying this new value on LEDs.
using an infinite loop to repeat these steps continuously with a 300ms delay between
them. What do you see? (This is called a ‘running light’.)
replacing the 'multiply by 2' with 'counter = counter + 1'.
What do you see now? (You just programmed a binary counter.)
Program 2:
modify Program 1 to display the result of the following calculations on the LEDs of port B:
45 + 52;
45 AND 52;
45 OR 52;
NOT 45;
(1+3)*(6/2);
VAR2 = VAR1 * 3 (where variable ‘VAR1’ stores the number 18).
On paper, check if the results are correct.
Using Loops
Introduction:
Repeating a set of instructions, for an exact number of times, while or until a condition is met is
one of the most powerful programming operations.
The programs are now getting more interesting but also more complex. Use the slow simulation or
'Step Over' function in the ‘Flowcode 7’ simulator to debug programs from now on.
Objectives:
to create and use a ‘running light’ program, using the ‘multiply-by-two’ method;
to create and use a ‘running light’ program, using the ‘shift-right’ method;
to create and populate an array;
to create a conditional loop;
Relevant course content:
Flowcode Wiki - ‘Loop icon properties’;
LCD - ‘Exercise 8 - Programming LCDs’
Flowcode Wiki - ‘Connection point icon properties’;
Flowcode Wiki - ‘Creating variables’;
Part 6 - ‘Introduction to microcontrollers’;
Part 2 - ‘Using E-blocks’;
Instructions
Program 1:
write a program to make an 8-bit binary counter, using a Loop icon, to count from 0 to 255,
then reset and repeat the count;
display the counter value on the LEDs of port B.
modify Program 1 to make the counter count up from 0 to 255 and then count back down to
‘0’:
using two loops inside an infinite loop so that the process repeats indefinitely;
displaying the counter value on the LEDs of port B.
download the program to the microcontroller and test it at full speed.
Program 2:
Remember 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:
using the ‘multiply-by-two’ method;
displaying the output on the LEDs of port B.
Using Loops
Program 3:
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:
using the ‘shift right’ method;
displaying the output on the LEDs of port B.
modify program 3 to create a 16-bit running light, using the LEDs at both port A and B.
use only loops - no decisions!
save this program, download it to the microcontroller and test it.
Program 4:
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;
uses 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]-
..... ;
refers to the four variables as ‘Matrix[x]’ where ‘x’ is a separate variable, known as the
index of the array;
displays the output on the LEDs of port B.
save this program, download it to the microcontroller and test it.
Inputting Data
Introduction:
Adding digital inputs to a microcontroller circuit is quite easy but is a big step forward. This allows
external signals to influence how the program reacts.
Objectives:
to input data from switches;
to use loops to create LED sequences;
to configure an input icon;
Relevant course content:
Adding digital outputs - “Light the LED”;
Part 6 - ‘Introduction to microcontrollers’;
Part 2 - ‘Using E-blocks’;
Instructions
Program 1:
write a program to show the status of the switches connected to port A, on the LEDs connected
to port B i.e. when a switch is pressed, the corresponding LED on port B lights;
save this program, download it to the microcontroller and test it.
modify the program so that:
the corresponding LED on port B stays lit for 2s;
during this time, no new inputs should be read;
save this program, download it to the microcontroller and test it.
modify the program again so that:
when switch ‘0’ is pressed, ‘LB1’ lights;
when switch ‘1’ is pressed, ‘LB2’ lights, and so on;
when switch ‘7’ is pressed, nothing happens;
save this program, download it to the microcontroller and test it.
Program 2:
write a program to create a counter that:
contains two loops;
counts up when switch ‘0’ is pressed;
counts down when switch ‘1’ is pressed;
displays the count on the LEDs of port B;
save this program, download it to the microcontroller and test it.
Program 3:
write a ‘running light’ program that:
contains two loops;
causes the LEDs to ‘run’ left when switch ‘0’ is pressed;
causes the LEDs to ‘run’ right when switch ‘1’ is pressed;
displays the count on the LEDs of port B;
save this program, download it to the microcontroller and test it.
Making Decisions
Introduction:
Earlier programs included simple decision-making, using loops and connection points. Now we look
in detail at the Decision icon, widely known as the ‘if…then…else’ structure, probably the most
widely used command line in any program.
Objectives:
to configure Decision icons and hence add conditional branching to a program;
to control the frequency at which LEDs flash;
to use LEDs to display output logic levels;
to use temporary memory;
Relevant course content:
Flowcode Wiki - ‘Decision icon properties’;
Flowcode Wiki - ‘Connection point icon properties’;
Part 6 - ‘Introduction to microcontrollers’;
Part 2 - ‘Using E-blocks’;
Instructions
Program 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…
Program 2:
write a program that creates an 8-bit counter, counting 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;
counting up when switch ‘0’ is pressed;
counting 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.
Program 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’:
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.
Program 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 addition:
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
Program 5:
write a program that makes all eight LEDs on port B light when switch ‘0’ is pressed the first
time and go off when it is pressed again;
save this program, download it to the microcontroller and test it.
Program 6:
A car has two interior lights, one in the front of the car, the second in the rear. These will be
simulated using LEDs.
Five switches control them:
switches ‘0’ to ‘3’ represent door switches that indicate if a door is open or not;
switch’4’ indicates that the boot (trunk) is open or not.
Assuming that the switches are closed when the doors are open - easier to simulate with ‘push-
to-make’ switches, write a program that:
lights both LEDs when any door opens;
lights only the ‘rear’ LED when the boot is opened;
save this program, download it to the microcontroller and test it.
Program 7:
write a program to control the car’s external lights, using switches on the steering wheel:
switch ‘0’ controls the left direction-indicator (represented by ‘LB0’), which flashes on for
250ms and then off for 250ms repeatedly until switch ‘0’ is released;
switch ‘1’ controls the right direction-indicator (‘LB1’) in the same way;
switch ‘2’ controls the brake lights (‘LB2’ and ‘LB3’), which light up as long as the switch is
pressed;
switch ‘3’ controls the head lights (‘LB4’ and ‘LB5’), which light when the switch is pressed
and stay on until it is pressed again;
switch ‘4’ controls the fog lights (‘LB6’ and ‘LB7’), in the same way;
save this program, download it to the microcontroller and test it.
Hint: Don’t attempt to write this program all at once - divide it into subsections and solve each sep-
arately before putting them all together.
To make it easier, use the labelling feature of ‘Flowcode 7’ to label switches and LEDs.
Program 8:
Six sheep are allowed to wander between two paddocks. Be-
tween the two paddocks, there are two sensors.
Two are needed because sometimes a sheep triggers one sen-
sor and then turns back.
write a program that counts and displays the number of
sheep in each paddock:
the results are shown in binary form on the LEDs of
port B;
the four LSB LEDs show the number in the left-hand paddock;
the four MSB LEDs show the number in the right-hand paddock;
when switch ‘0’ is pressed, it represents a sheep triggering Sensor 1;
when switch ‘1’ is pressed, it represents a sheep triggering Sensor 2;
(A sheep is longer than the gap between the sensors!)
save this program, download it to the microcontroller and test it.
Programming LCDs
Introduction:
Using LEDs to display outputs limits them to numbers only and in binary code at that!
The LCD is a much better way to display data, both letters and numbers, for ‘non binary’ humans.
Objectives:
to create, populate and manipulate string variables;
to control the display of text and numbers on a LCD;
to use a LCD as an output device for the microcontroller;
to configure a Component macro for the LCD;
Relevant course content:
LCD - ‘Exercise 8 - Programming LCDs’
Part 6 - ‘Introduction to microcontrollers’;
Part 2 - ‘Using E-blocks’;
Flowcode Wiki - ‘String manipulation functions’;
Instructions
Program 1:
write a program that displays the text “Hello World” in the centre of the bottom line of the
2x16 LCD display.
Program 2:
write a program, using either Loops or Decisions, that:
counts up while switch ‘0’ is pressed;
counts down while switch ‘1’ is pressed;
shows the current count in binary on LEDs attached to port B;
shows the count in decimal on the LCD.
Program 3:
write a program to show the status of the switches attached to port A, so that every time a
switch or switches is/are pressed, the corresponding LED(s) of port B light(s) and the decimal
equivalent is displayed on the LCD.
Program 4:
write a program to show the status of the switches attached to port A on the LED(s) of port B
and on the top line of the LCD and then:
multiply this binary number by 100;
display the result on the bottom line of the LCD, with “[x 100 = ]” displayed in front of it;
save this program, download it to the microcontroller and test it.
Program 5:
write a program that displays the text “[R15=560 ” in the centre of the bottom line of the LCD
display, using the ‘PrintASCII’ command to print the ‘ ’ sign:
save this program, download it to the microcontroller and test it.
Programming LCDs
Program 6:
write a program that scrolls the lines of text given below, one line at a time:
initially, the text is centred on the bottom line of the display for 2s;
then it moves up to be centred on the top line for 2s, to be replaced on the bottom line by the
next line of text, and so on;
Text:
“There are only”;
”10 kinds”;
”of people !”;
“Those who”;
“understand”;
“BINARY”;
“and those who”;
“DON’T….”.
enclose the program in an infinite loop;
save this program, download it to the microcontroller and test it.
Program 7:
write a program that:
uses the string manipulation icon to load a string variable called ‘MyStrA[20]’ with the text
“Hello”;
displays this string variableon the LCD using the ‘PrintString’ command with the parameter
‘MyStrA’ (without the ‘[]’].
Program 8:
write a program that:
loads a string variable called ‘MyStrA[20]’ with the text “Hello”;
loads a second string variable called ‘MyStrB[20]’ with the text “Matrix”;
displays “Hello Matrix” on the LCD using simple string manipulation.
modify program 8 so that, using the same string variables with the same content, the LCD displays the
message “HELLO MATRIX” using simple string manipulation.
save this program, download it to the microcontroller and test it.
Program 9:
write a program that:
loads a string variable called ‘MyStrA[20]’ with the text “Hello”;
loads a second string variable called ‘MyStrB[20]’ with the text “Matrix”;
displays “ello MATRIX=13” on the LCD using a range of string manipulations.
save this program, download it to the microcontroller and test it.
Hint: Find out how to display string length using string manipulation. The number changes automatically
when the length of the string changes.
Program 10:
write a program that:
loads a string variable called ‘MyStrA[20]’ with the text “Hello”;
loads a second string variable called ‘MyStrB[20]’ with the text “Matrix”;
displays the message “xirtaM olleH” on the LCD.
Program 11:
modify the sheep counter program from the last exercise to display the numbers of sheep in the two
paddocks on the LCD. (You decide the format of the display!)
Introduction:
A numeric keypad is used in many electronic devices, your mobile ‘phone, for example, where it is
used both as a numeric keypad and as a way to type text instead of numbers.
An issue- there are twelve buttons on the keypad, yet the keypad is connected to the microcontrol-
ler by only eight lines! This problem is solved by using multiplexing.
Objectives:
to input text and numbers from a keypad and display messages on the LCD;
to use ASCII code to transmit this data;
to use multiplexed inputs;
to configure a Component macro for the keypad;
Relevant course content:
LCD - ‘Exercise 8 - Programming LCDs’
Flowcode Wiki - ‘String manipulation functions’;
Part 6 - ‘Introduction to microcontrollers’;
Part 2 - ‘Using E-blocks’;
Instructions
Program 1:
write a program to:
display, on the LCD, the number that is pressed on the keypad;
display it for as long as the button on the keypad is pressed;
display only one number at a time;
save this program, download it to the microcontroller and test it.
re-write this program without using the Keypad Component macro:
save this program, download it to the microcontroller and test it.
extend this program to:
display, one after another on the top row of the LCD, numbers that are pressed on the
keypad;
use the character ‘*’ for a space;
clear the display when ‘#’ is pressed;
display a maximum of fifteen characters;
display a warning on the bottom row of the LCD when this maximum is exceeded;
save this program, download it to the microcontroller and test it.
Program 2:
write a program to:
add together two numbers, less than ‘9999’, entered via the keypad;
display the two numbers, the ‘+’ and ‘=’ and the resulting sum on the top row of the LCD;
display a warning on the bottom row when ‘9999’ limit is exceeded;
save this program, download it to the microcontroller and test it.
Program 3:
write a program for a simple guessing game, where:
a player needs to guess a number between ‘0’ and ‘9’;
the secret number is pre-programmed into the microcontroller;
the LCD displays, on the top row, the latest guess entered via the keypad;
the LCD displays a message, on the bottom row, indicating whether the guess is too high
or too low;
save this program, download it to the microcontroller and test it.
extend this program so that:
the secret number is in the range ‘0’ to ‘255’;
save this program, download it to the microcontroller and test it.
extend the program again so that:
the secret number is in the range ‘0’ to ‘9999’;
save this program, download it to the microcontroller and test it.
Program 4:
write a program to use the keypad, as on a mobile phone, to input text to the microcontroller:
using ASCII code to transmit the data;
using the character ‘*’ for a space;
clearing the display when ‘#’ is pressed;
displaying a message on the bottom row when the text has more than ten characters;
save this program, download it to the microcontroller and test it.
Introduction:
The 16F1937 PIC Microcontroller accepts fourteen separate analogue inputs. Newer devices 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, needs careful program writing!
Objectives:
to create data loggers, using 8-bit and 10-bit data from the ADC;
to configure an analogue input;
to enter data via switches;
to enter information from light and temperature sensors;
to configure and use the EEPROM;
to scroll through EEPROM data;
to display text and numerical data on the LCD;
to use the E-blocks prototype board.
Relevant course content:
LCD - ‘Exercise 8 - Programming LCDs’
Flowcode Wiki - ‘String manipulation functions’;
Part 6 - ‘Introduction to microcontrollers’;
Part 2 - ‘Using E-blocks’;
Instructions
Program 1:
write a program to:
display, on the LCD, an 8-bit number equivalent to the analogue input voltage from the
light sensor on the Sensor board;
save the program, download it to the microcontroller and test it. (Connect a voltmeter to meas-
ure the analogue input voltage.)
Program 2:
modify program 1 to:
display data from the ‘pot’ on the Sensor board;
save the program, download it to the microcontroller and test it,as before.
modify this program to:
convert the ADC 8-bit output into a voltage reading between 0 and 5V, making it as accu-
rate as the 8-bit mode allows;
save the program, download it to the microcontroller and test it, using a voltmeter to measure
the analogue input voltage, once more.
Program 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;
save the program, download it to the microcontroller and test it, using a voltmeter to measure
the analogue input voltage, once more.
then modify this program to:
convert the ADC 10-bit output into a voltage reading between 0 and 5V, making it as ac-
curate as the 10-bit mode allows;
save the program, download it to the microcontroller and test it, using a voltmeter to measure
the analogue input voltage, once more.
Program 4:
write a program to monitor the lighting in a room over a 24 hour period:
using the analogue signal from the light sensor on the Sensor board;
storing light measurements on the EEPROM;
sampling at the highest rate possible, given that the PIC has 256 bytes of EEPROM
memory on board
and displaying each sample with its sample number, on the LCD;
by scrolling forwards through the samples by pressing switch ‘0’, or scrolling backwards
by pressing switch ‘1’;
save the program, download it to the microcontroller and test it.
Hint: Increase sampling rate so that you don’t have to spend 24 hours in testing.
Program 5:
connect the Prototype board to port E and modify program 4 to develop a 10-bit accurate
temperature display unit that:
monitors room temperature every 20 minutes over a 24 hour period;
resembles the logger developed for room lighting, except that this one stores 10-bit data
in an 8-bit wide EEPROM;
keeps a LED flashing to indicate that the system is still logging;
lights all LEDs after 24 hours to indicate that logging is completed;
allows you to scroll through the results using switches ‘0’ and ‘1’ as before;
displays the temperature and its EEPROM address on the LCD.
save the program, download it to the microcontroller and test it.
Introduction:
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. Rou-
tines that are re-used can be put into a software macro, which can be called whenever it is needed
in the main program. Making use of these software macros ‘lightens up’ the main program and
makes it much easier to read.
Objectives:
to use software macros to simplify the structure of a program;
to create software macros;
to use closed loop control;
to use PWM to control the brightness of LEDs.
Relevant course content:
Software macros - Exercise 11 - Using Software Macros
Flowcode Wiki - ‘Software macro icon properties;
Part 2 - ‘Using E-blocks’;
Instructions
Program 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 bidirectional ‘running light’, displayed on the LEDs.
the LCD displays a text message identifying the selected program;
switch ‘1’ activates the chosen program when pressed.
the three programs are placed in software macros.
download this program to the microcontroller and test it.
modify program 1 so that:
if switch ‘0’ is pressed while one of the three software is running, execution stops imme-
diately and focus returns to the main loop and waits for a new selection.
download this program to the microcontroller and test it.
modify program 1 again so that:
if switch ‘0’ is pressed while one of the three software is running, execution stops and
returns to the main loop, as before, but it stores the value displayed on the LEDs;
when the next selection is made, that macro starts the LEDs from where the previous one
left off, making the transition between them smoother.
download this program to the microcontroller and test it.
Introduction:
In earlier exercises, the microcontroller did not necessarily react to inputs straight away because it
was busy doing something else. The external interrupt features of 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 initialized correctly, then a change on port B can
cause the program to stop execution immediately and switch to executing the appropriate inter-
rupt macro. We then have what is called a ‘real time’ execution.
Objectives:
to create and use ‘single-pin’ interrupts;
to create and use ‘interrupt-on-change’ (IOC) interrupts;
to use real time operation of a microcontroller;
Relevant course content:
Part 2 - ‘Using E-blocks’;
‘Flowcode 7’ Wiki.
Instructions
Program 1:
write a program to time how many seconds have passed since the program was reset and :
display the result on the LCD;
uses a variable called ‘count’ whose value is displayed on the LEDs.
Don’t use any kind of interrupt.
download this program to the microcontroller and test it.
Hint:
Use a 1s delay.
A rising edge on pin ‘RB0’ should call a macro that adds one to ‘count’.
re-design this program using an interrupt (single-pin) on RB0.
download this program to the microcontroller and test it.
now re-design it using both kinds of external interrupt so that:
triggering the single-pin interrupt increments ‘count’ (count = count + 1);
triggering the IOC interrupt decrements ‘count’ (count = count - 1).
download this program to the microcontroller and test it.
Program 2:
write a program to make an electronic dice that :
counts from 1 to 12;
display the result on the LCD;
starts ‘rolling’ when switch ‘0’ is pressed;
stops ‘rolling’ when switch ‘0’ is pressed again.
download this program to the microcontroller and test it.
Hint:
The LCD should display numbers from 1 to 12, one after the other, over and over again rapidly, at
20 ms intervals - much to fast to see with a human eye.
modify this program so that:
the dice keeps ‘rolling’ as long as switch ‘0’ is held down;
stops ‘rolling’ when the switch is released;
at that point displays the number on the LCD.
download this program to the microcontroller and test it.
Program 3:
write a program to make a reaction timer that :
lights all LEDs initially;
keeps them lit for around 6s;
switches them off and starts a timer;
stops the timer when the player presses switch ‘0’;
then displays the resulting ‘reaction time’ on the LCD.
(Use a variable that is incremented every 10ms.)
download this program to the microcontroller and test it.
modify program 3 to limit the time 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 cheating by simply holding down switch ‘0’ continuously.
download this program to the microcontroller and test it.
Introduction:
The other type of interrupt function in ‘Flowcode 7’ is the timer interrupt. These allow you to per-
form software tasks at precisely predetermined time intervals - a really useful feature when devel-
oping time critical applications and clocks.
Objectives:
to create and use timer interrupts;
to use the prescaler to create accurate time intervals;
to trigger the timer using the crystal or an external event;
Relevant course content:
Flowcode Wiki - ‘What is a 7-segment display?’;
Part 2 - ‘Using E-blocks’;
Timer arithmetic:
The 16F1937 has several timers, but we look at only two: ‘TMR0’ (Timer 0) and ‘TMR1’ (Timer 0).
TMR0 can be triggered by the crystal or by a transition on the ‘T0CKI’ pin ‘RA4’.
The internal clock has a frequency of ‘crystal clock frequency’/4, i.e. 19,660,800/4 =
4,915,200Hz.
The TMR0 prescaler can be set from 1:2 to 1:256. For this exercise, set it to 1:256, so that every
256 clock pulses cause the TMR0 to increase by 1. This happens at a frequency of
4.915.200/256 = 19.200Hz.
Every time this 8-bit timer ‘overflows’ (reaches 256), it generates an interrupt. This happens
with a frequency of 19.200/256 = 75Hz, so that the main program is stopped 75 times per sec-
ond and so the timer interrupt macro is executed 75 times per second.
Instead of using the crystal, this timer can also be ‘clocked’ by an external event, as when
measuring motor speed etc.
TMR1 can be triggered by the crystal oscillator or by a transition on the ‘T1CKI’ pin ‘RC0’.
Its operation is similar to that of TMR0, except that it uses different prescaler values.
TMR2 also exist but this in not discussed in this course.
Instructions
Program 1:
write a program to produce a precise ‘seconds’ timer that :
displays the result on the LCD;
starts when the microcontroller is reset.
(Use a 1s delay. Don’t use a timer interrupt.)
download this program to the microcontroller and test it using your watch.
rewrite the program using a timer interrupt.
download this program to the microcontroller and test it as before.
Program 2:
write a program to create a basketball timer that :
starts when switch ‘0’ is pressed;
displays the time elapsed on the LCD;
makes the LEDs flash on and off when 30s has elapsed, (the time allowed for the team
with the ball to make a goal attempt.)
(Use a ‘single-bit’ interrupt on pin ‘RB0’ to start the timing.)
download this program to the microcontroller and test it using your watch.
Program 3:
rewrite the reaction-timer program (Exercise 12, program 3) to use a timer interrupt.
download this program to the microcontroller and test it as before.
Program 4:
write a program to produce a precise clock that displays the time elapsed since the last reset, in
hours, minutes and seconds on the LCD.
download this program to the microcontroller and test it using your watch.
modify this program so that:
switch ‘0’ stops the clock when pressed the first time;
switches ‘1’, ‘2’ and ‘3’ can be used to change the displayed time to the actual time;
switch ‘0’ restarts the clock when pressed a second time;
download this program to the microcontroller and test it.
Program 5:
write a program to produce a timer that counts down from 01:00:00 to 00:00:00 in seconds and
then lights all the LEDs.
download this program to the microcontroller and test it using your watch.
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 software PWM output
to all LEDs on port B. When the PWM ‘on’ time increases, the LEDs get brighter, etc.
Put this program in a timer 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 hap-
pen 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 times, set using a timer 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 EB090 Sensor
Motherboard can be used with either the EBM003 Thermistor sensor module or the EBM004 Digi-
tal temperature sensor module. Use the LEDs to simulate the action of a heater.
2. Three judges vote on variety acts in a ‘X-factor’-like game show. When two or more judges vote ‘Yes’,
the act progresses to the next round.
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 EBM016
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 EB014 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 EBM019 Ultrasonic distance sensor module. The
system should switch on four lights (12V lamps) when a person approaches within one metre of the sen-
sor and so makes use of the EB038 Relay module
6. Use the EBM020 Infrared sensor module to time the swing of a pendulum without impeding it.
7. Design a system to drive the DC motor (and sensor) on the Actuators training panel at a steady speed.
Add a feature to modify this set speed.
8. Design a system to drive the stepper motor on the Actuators training panel so that it rotates, in 15 0
steps, through one complete circle and then reverses back to its initial position in the same manner.
Part 2
Using E-Blocks
Part 2 Contents
Using a backplane
E-blocks can be mounted onto a metal backplane to form a
completely rugged system. To facilitate this, each E-block is
fitted with four 3mm holes spaced at 20mm intervals. M3
bolts with spacers are used to mount the E-blocks onto a
backplane, which has 4mm holes on a regular 20mm grid.
The mounting holes on the backplane, the holes on the
E-blocks and the spacing of each D-type plug and socket on
the E-blocks are arranged so that E-blocks can be connected
together and still be mounted on the backplane.
If you modify your E-blocks system regularly or want others to be able to do this, we suggest that
you use steel or Nylon M3 bolts on all E-blocks. They will then ‘sit’ on the metal backplane without
being bolted to it. (If you intend to move the system around, then one or two nuts on the back will
ensure your E-blocks stay in place.)
The diagram shows 12mm bolts with self locking nuts - these keep the bolts secured onto the
circuit board and allow you to position the boards on the backplane as you wish.
For best results, attach the self locking bolts and nuts and then slacken off the nuts by a quarter
turn to allow a little movement in the PCB mounting holes. This makes it easier to take the board
off the backplane.
Be careful when doing this as using the wrong voltage can damage the PIC device on the
ultiprogrammer board!
Sharing a port
Sometimes, you need to split a port into several sections, or share signals on a port between
‘downstream’ E-blocks. To do this, use a splitter cable. This allows you to connect one ‘upstream’
port to two ‘downstream’ ports using IDC (Insulation Displacement Connector) connectors and
ribbon cable.
For example, suppose that you are developing a system that uses two external analogue sensors.
The Sensor board has only one external analogue sensor port. Use a splitter cable and two Sensor
boards, giving the result shown (note; board(s) shown below are the discontinued EB003):
The analogue sensor input on the upper board uses the default connection, bit 3. On the lower
board the jumpers are moved to the ‘patch’ position and a small wire is used to connect the
second analogue sensor to bit 2. The result allows you to connect one analogue sensor to bit 3 and
the other to bit 2 on the ‘upstream’ board.
Using ZIF Sockets
It is possible to use Zero Insertion Force (ZIF) sockets with the E-Blocks PIC
Multiprogrammer and other programmers in the E-blocks range. These sockets are
useful where the chips will be removed from the programmer many times.
ZIF sockets are available from many vendors and can be inserted into the DIL
sockets on the ‘upstream’ boards. Where E-blocks boards have other components
close to the DIL socket, add further DIL sockets to gain enough height to allow the
ZIF socket to be inserted safely.
Matrix sells a PIC microcontroller programmer complete with ZIF sockets.
Note: Despite having two full 8-bit hardware port connections between the EB083 Development
board and the EB093 Shield, the Arduino Uno can only provide 6 general purpose I/O connections
on port A, (A0-A5). Therefore, LEDs ‘LA6’ and ‘LA7’ and switches ‘SA6’ and ‘SA7’ cannot be used
with the Arduino Uno.
In order to program the Arduino Uno board directly from within Flowcode 7, you must ensure that
the appropriate drivers are installed. These are provided with the Flowcode 7 download, but are
not automatically installed.
Part 3
Introduction to
Flowcode 7
Part 3 Contents
Introduction to ‘Flowcode 7’
This section allows those who are new to ‘Flowcode 7’ to understand how it can be used to devel-
op programs. It allows you to create programs step-by-step to learn about how ‘Flowcode 7’
works.
We advise that you work through every section to familiarise you with all of the options and fea-
tures of ‘Flowcode 7’ and introduce you to a range of programming techniques. As you work
through each part, please also refer to the ‘Flowcode 7’ help file. The main ‘Flowcode 7’ icons are
introduced in turn.
Specifically in this section you will learn:
how to use each ‘Flowcode 7’ icon (except the C code icon);
how the fundamental Components in ‘Flowcode 7’ work - the LED, LCD, ADC, switch, 7-segment
display, 7-segment quad display, keypad and EEPROM components.
What is ‘Flowcode 7’
‘Flowcode 7’ 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 microcon-
troller such as LED's, LCD displays etc.
Once the flowchart has been designed, its behaviour can be simulated in ‘Flowcode 7’ before the
flowchart is compiled, assembled and transferred to a microcontroller.
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 pro-
gram.
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 7’ overview
The ‘Flowcode 7’ 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;
display variables and macro calls when the flowchart is being simulated.
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:
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 cur-
rent project.
'Macros' - user-created macros in the current program and allows the userto drag
them into the current flowchart.
'Components' - similar except that it also lists components that are present in the
panel.
Icon list
All bookmarks, breakpoints and disabled icons are listed, together with search and error results.
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.
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.
To dock it again, double-click on the ‘grab bar’.
Flowchart window
The icons that make up the flowchart are displayed in this main
space.
In addition, the flowcharts of any macros involved in the program
are shown under their own separate tab.
The Main flowchart tab is always visible and the macro tabs can
be shown or hidden as needed.
A red star alongside an icon indicates that the flowchart has not
been saved in its current form.
Simulation
When simulating a program on ‘Flowcode 7’ a red rectangle
around an icon indicates the icon to be executed next.
Debugger window
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.
Printing Flowcharts
Use the Print Preview command to display the flowchart as it would appear when printed.
When you use this command, the main window will be replaced with a Print Preview window in
which one or two pages will be displayed in their printed format.
The print preview toolbar offers you options to:
view either one or two pages at a time;
move back and forth through the document;
zoom in and out of pages;
initiate a print job.
Alternatively, the print job can be initiated without preview by selecting 'Print' from the 'File' menu
(File > Print) or clicking the ‘Print’ icon on the 'Main toolbar'.
The View menu
This dictates which panels and toolbars appear on the workspace, a useful feature when trying to
simplify its appearance.
It also has a ‘Zoom’ menu, which allows you to display more icons in the workspace window than
when using the default zoom setting. The current zoom setting is displayed on the ‘Zoom’ sub-
menu, and on the right hand side of the status bar, at the bottom of the ‘Flowcode 7’ 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 function to optimise the appearance of your flowchart on the pa-
per.
The ‘Zoom’ menu can also be accessed by right-clicking on the flowchart workspace.
Function key shortcuts:
Increase Zoom (F3) - increases zoom size by 5%;
Decrease zoom (F2) - decreases zoom size by 5%;
Default zoom (F4) - set zoom to 75%;
Zoom to fit - Zooms to fit the whole flowchart into the current window;
Zoom to fit width - Zooms to fit the width of the flowchart into the width of the window.
The ‘View’ menu also includes a ‘Style’ menu, offering a dark or a light overall appearance to the
‘Flowcode 7’ application and a ‘Global Options’ area, offering a series of powerful tools to config-
ure the flowchart.
Global Options
To see the effect of changing these settings, click the 'Preview' button at the bottom of the win-
dow.
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 ap-
pearance 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 over-
all program.
The skin presets and tab options change the general
look of ‘Flowcode 7’. 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 7’ language settings
and to display ‘Flowcode 7’ in a specified language.
To do this, select the language from those available
on the drop down list and restart ‘Flowcode 7’.
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 messag-
es.
The ‘Allow unconnected ports and pins’ option al-
lows 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 7’ compiles to by default. It also allows
you to specify directories that ‘Flowcode 7’ should
search when looking for components and dictionar-
ies.
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 differ-
ent ports simultaneously. Adjusting the ‘timebase’
allows the user to view a small amount of data at
increased accuracy or larger amounts of data.
Part 4
Flowcode 7
Your first program
Part 4 Contents
Don't worry - this program will not radically change your life!
The hardware:
This diagram shows you how to set up the E-blocks hardware. It was shown earlier at the beginning
of the 'Programming Exercises' section, along with appropriate hardware settings.
The flowchart:
Start a new project by selecting 'File' and then clicking 'New'
in the menu which appears (File > New). You are asked to
choose a target microcontroller from the list that appears.
Double-click on '16F1937'.
Next, you see a flowchart, blank except for 'BEGIN' and 'END' icons. All flowcharts have
these icons by default. Move the cursor over the 'Output' 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 Output icon will be placed. Release the mouse button to drop the icon in between
the 'BEGIN' and 'END' boxes.
Move the cursor over the Output icon. Now, either double-click with the left mouse button or
click with the right mouse button and choose 'Properties'
from the menu that appears.
You now see a dialogue box like the one opposite
Move the cursor over the ‘0’ in the ‘Variable or value’ box
and click once. This will highlight the '0' value. Change this
value to '1'. This is the value that will be sent to the se-
lected output.
Adding LEDs
Click the 'Outputs' button in the Components toolbar and select the 'LED
Array' component.
It looks like this:
Click or drag it to add it to the System Panel.
Click once on the component in the panel to select it. Its 'Properties' pane
will open and display its properties.
In the 'Simulation' section, change the 'Count'
property to '8' by typing in the box next to the name.
Now, go to the 'Connections' section and change the 'Port' to 'PORTB'. Do-
ing this means that port B controls the LED array
Change the colour of the LED's to red, using the 'Colors' property.
(Make sure that the 'Same’ property is set to 'Yes' to change the whole LED
array. )
Review the progress!
So far, you have:
inserted an Output icon in the flowchart;
set it up to deliver a value of 1 to port B;
connected eight red LED's to the eight bits of port B.
Congratulations!
You have completed the first part of the program - to control digital (i.e. on / off) outputs.
Now test it by running a simulation of this program.
High Speed Simulation
Click on the 'Run' icon, on the main toolbar.
The result - the first LED lights and then there is a message saying that the simulation is completed.
If you blinked, you missed it!
What happened? The program outputted the number 1 and displayed it on the LED's, by lighting
the first and leaving the others off. But it happened extremely quickly!
Slowing it Down
When you pressed the 'Run' button, the program was over in a flash!
It's the good news and the bad - microcontrollers work really fast.
In later programs you learn how to slow them down to a speed that humans can cope with, using
delays or loops. For now we slow down the simulation!
The table opposite shows how the two number systems compare:
Decimal Same in binary
In binary, the same thing happens, but a lot more often, because it Decimal Same in binary
uses only '0''s and '1''s. Counting up starts with '0', then '1', then back 1 1
to '0' with a '1' in front, making '10' (not ten - it's two!) Next comes
'11' (three) and start again with two '0's but with a '1' in front, to give 2 10
'100' (four) and so on. 4 100
8 1000
Converting Numbers
Notice that each time the binary '1' moves one place Binary value
to the left, it doubles in value of the number in deci- 16 Decimal value
8 4 2 1
mal, as the table opposite shows.
1 1
We can use this idea to convert between number
systems. 1 0 2
In any binary number, the bit at the left-hand end, 1 0 0 4
the 'Most Significant Bit', (MSB), has the highest val- 1 0 0 0 8
ue. The one at the right-hand end, the 'Least Signifi- so
cant Bit', (LSB), is worth least . 1 1 1 7
1 0 0 1 9
Outputting Numbers 1 0 1 0 0 20
Finally, back to the question of outputting numbers! 1 1 1 1 1 31
Modify your program to output the numbers given
in the table, setting the LED colour to match, and check that the LED array behaves as shown!
Working in Hex
An experienced programmer might wonder if Decimal Binary Hex
‘Flowcode 7’ supports hexadecimal numbers. 0 00000000 0
The answer is ‘yes’.
1 00000001 1
Hex in ‘Flowcode 7’
You can enter a hex number into ‘Flowcode 7’ by preceding it with '0x' in any of the dialogue box-
es.
For example:
This is equivalent to placing the binary number 1111 0000 onto port B.
In other words it places a logic 1 (around 5V) onto the most-significant four output pins, and a logic
0 (0 volts) onto the least-significant four pins.
Part 5
Flowcode 7
Worked Examples
Part 5 Contents
PIC or Arduino?
All of these examples can be tried out using either a PIC or an Arduino microcontroller. Arduino
users should familiarise themselves with the hardware information at the end of Part 2 of the
course.
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 quotation marks) as the
name of the new variable and click on the ‘OK’ button. It now
appears in the list of variables that the flowchart can use.
Double-click on the name of the variable to use it, or alterna-
tively click and drag the name into the variable box.
You now see the input 'Properties' box again. Notice that you
need to tell the system which port you are going to use to input
the data the system needs. It is set to port A at the moment, and we are going to leave it that
way.
In this case, the system needs to monitor the heat sensors and so each sensor will be connected
to a different bit of port A. Click on ‘OK’ to close the Input Properties box.
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 '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 ‘Flowcode 7’ can be configured to use just one
memory register or more than one.
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!
One of the problems with this program is that it shows the total number of sheep in binary format.
That is interesting, but not that useful.
In the next section, you learn that an LCD display can show the total in decimal format.
LCD displays
‘Flowcode 7’ comes with a number of components that add commonly used subsystems to
‘Flowcode 7’, 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
7’ 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 two row, sixteen character
display.
Writing messages
To display text on the LCD, simply type it in!
Add another 'Component Macro' to the flowchart and
open the macro dialogue box.
Select the LCD macro called 'PrintString'. This requires a
single parameter (item of data), 'Text', - the text to be
printed.
Type the text into the parameter box surrounded by quota-
tion marks, e.g. "Hello World"
Run the program and the text will be sent to the LCD display.
Example 4. A stopwatch
Expand your program 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.
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 hun-
dredth of a second).
Refine the program by clicking on each icon and entering comments on the icon does. It may
seem to be a lot of effort, but it saves time later as your program will be easier to follow.
Run the program. You have now made a counter that will count (approximately) the time
elapsed in hundredths of seconds.
Slow simulation
As described earlier, ‘Flowcode 7’ 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.
Do one of these!
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.
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.
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.
Add a LED connected to port B, bit 0 to represent the microwave generator.
Add labels to the System Panel to identify the components, as shown in the diagram. Position
them using the ‘World coordinates’ under the ‘Position’ tab of the label properties.
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?
Hardware setup:
The EB006 Multiprogrammer and EB083 Combo board are connected as usual, using ports A and B.
On the EB083 board, ensure that:
port A (pin 0 and 1) mode selectors are set to Analogue.
The EB013 SPI board is connected to port C. A positive power supply connection is needed between
the ‘+V’ screw terminal on the SPI board and the same on the EB006 board.
On the EB013 board, ensure that:
jumper J2 is in the right hand side - ‘AMP’ position;
jumper J4 selects ‘A’;
jumper J5 selects 1’.
The pot ‘RV1’ on the SPI board is a hard-wired hardware volume control, independent of the soft-
ware volume control created in the program.
Plug headphones into the ‘Headphones’ socket.
Connect the EB006 Multiprogrammer to a 12V power supply.
Use a USB cable to link it to the computer.
The upper ‘pot’ represents the volume control (‘AN1 POT’ on the EB083 Combo board).
The lower one represents the tone control (‘AN0 LDR’ on the EB083 Combo board.)
Click on each, in turn, and select ‘Properties’.
Configure them as shown in the following diagrams:
The program loops back to send further peak and trough values, re-creating the audio wave.
The program is now complete.
Save it and then click on the ‘Compile to Chip’ icon to transfer it to the microcontroller.
When the transfer is complete, press the ‘Reset’ button on the EB006 Multiprogrammer.
You should hear an audio tone coming through the headphones.
Turn the ‘pot’ ‘AN1 POT’ on the Combo board and notice the effect. This controls the loudness
of the tone through the software, unlike the ‘pot’ ‘RV1’ on the SPI board which controls volume
through the hardware - because of the circuit configuration.
Shade the LDR on the Combo board. The tone of the audio signal should change.
On the ‘Flowcode 7’ screen, click on ‘Data Recorder’ in the ‘View’ menu. You see the following:
Part 6
Introduction to
Microcontrollers
Part 6 Contents
What is a microcontroller?
As its name suggests, microcontrollers are tiny devices used to control other electronic devices.
They are found in a huge range of products:
automotive - engines, anti-lock brakes, climate control systems… ;
domestic electronics - TVs, VCR's, digital cameras, mobile phones, printers, microwave ovens,
dishwashers, washing machines... .
So what are these wonderful devices?
A microcontroller is a digital integrated circuit, consisting of:
central processing unit
memory
input ports
output ports
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, sets up sequences of signals
etc.
How does it know what to do? It is following a program of instructions, stored in part of the
memory, called the 'program memory', inside the PIC.
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 compo-
nents on.
Copyright © 2016 Matrix Technology Solutions Limited www.matrixtsl.com
Page 87
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.
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'.
As you have seen, ‘Flowcode 7’ has a simulation mode that allows you to attach LEDs to show the
status of the pins on the microcontroller when they are used as outputs. The LED simulation func-
tion inside ‘Flowcode 7’ assumes that current is sourced from the PIC device - like the green LEDs
in the diagram above.
At some stage, you will need to use the PIC pin specifications in order to use them as digital inputs,
analogue inputs, or as digital outputs. In particular, there are limitations on the output capabilities
of the device. Exceeding these limits, even for a short time, may cause permanent damage to the
PIC.
Fortunately the E-block boards used on this course all have current limiting resistors which protect
the PIC device. When using the prototype or patch boards, however, there is no such protection
and care must be taken not to damage your device.
Storing Data
Electronic sub-systems that store data are known as Address
'memory'. They can store only digital data. Data stored
In decimal In binary
One item of data is stored in one location in the memory. This 0 000 11101001
data could be the correct combination to disarm a burglar
1 001 00100101
alarm, or the target temperature of a car engine block.
2 010 10000101
Each memory location has a unique address, a number used
to identify the particular location. This means that we can 3 011 11001101
draw up a map of the memory, showing what data is held in 4 100 01110100
each location. 5 101 00011011
The decimal version of the address is included to make the 6 110 11110011
table easier to read. 7 111 10000101
Electronic systems understand only 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 ad-
dresses for each location. It allows us to 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 loca-
tions!
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 com-
puters.
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 con-
tents. 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 stick) and in home
video games consoles.
Random Access Memory (RAM)
RAM allows both read and write operations during the running of a program.
The contents are volatile and disappear as soon as the power supply is removed.
(The exception is NVRAM, Non-Volatile RAM, where the memory device may include a battery
to retain the contents, or may include an EEPROM chip as part of the memory to store the con-
tents during power loss.)
They are often used for the temporary storage of data or application programs.
PIC 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 organisation of the memory:
Program memory is used to store the program!
In most PICs, such as the 16F1937, this uses 'Flash'
technology, meaning that it can be programmed and
cleared many times. Older PIC's use PROM for the
program memory so that many of these can be pro-
grammed only once.
Data memory is used to store data!
Part of this uses RAM and part uses EEPROM.
The EEPROM allows us to preserve important data
even if the power supply to the system is switched
off.
For example, suppose that the PIC is part of a temperature controller that keeps an incubator at a
set temperature. It might make sense to store the target temperature value in EEPROM so that we
do not have to enter it into the system every time we switch the incubator on.
The 16F84 illustrated is a relatively small device. In the 16F1937 there are 8192 words of program
memory (each word has 13-bits), 512 bytes of user RAM and 256 bytes of EEPROM.
Programming
What is a Program?
Microcontrollers are programmable devices. They do exactly what they are told to do by the pro-
gram, and nothing else! A program is a list of instructions, along with any data needed to carry
them out.
Unfortunately, microcontrollers do not understand english. The only thing they understand is num-
bers. There's a problem! 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 lan-
guage 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 eng-
lish) or in a low-level language (assembler).
The first is usually quicker and easier for the programmer, but takes longer to run the program, be-
cause 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 microcon-
troller.
If you think that this sounds very complicated, you are right. It is!
Fortunately, ‘Flowcode 7’ works using flowcharts - the easiest, and highest level, of programming
and then takes care of all translation needed.
The ‘Flowcode 7’ Process
'‘Flowcode 7’' offers an easy way to program PIC chips, as you will see. Once the flowchart is de-
signed on-screen, one press of a button causes the software to translate it into numerical code!
‘Flowcode 7’ passes the program through a number of processes before it gets sent into the mi-
crocontroller. The flowchart is processed:
first into C code,
then into Assembler,
and finally into hexadecimal numbers or 'Hex', which the microcontroller 'understands'.
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 7’ menu, the program
'Mloader' runs. It controls 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.
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 button 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.
Different types of PIC
There are a large number of PIC devices available, from the humble 16F84 to larger more complex
PIC's such as the 40 pin 16F1937. Different PIC's have different number of ports, or I/O pins, ana-
logue inputs, larger memory, or advanced serial communications capabilities such as RS232 or SPI
bus.
Deciding on which device to use for a project can be a task in itself. For this course we use a
16F1937 device, a 40 pin PIC that has many internal subsystems (like an A/D converter, and a serial
port).
PIC16F1937 Architecture
As this course uses the 16F1937 PIC, it is important that you un-
derstand a little more about what it does and how to use it. This
section details the pins that are available on the 16F1937 and
the connectors they use on the Multiprogrammer. (The section
on 'Using E-blocks' looks at how these connections are made).
At this point in a traditional programming course, you would be
introduced in some detail to the various internal circuit blocks of
the PIC device. You would need this information to write code
for the PIC in C or assembly code. No need - ‘Flowcode 7’ takes
care of these details!
However, you do need to understand the input and output con-
nections of the PIC, the memory available and the role of the
other subsystems in the PIC.
Ports - The 16F1937 PIC has five ports, labelled ‘A’ to ‘E’,
connected to the rest of the PIC internals by an 8-bit bus system.
PORT A
All eight pins of port A are usable as inputs or
outputs:
RA0-RA7 can be used as digital inputs;
RA0-RA7 can be used as digital outputs;
RA6-RA7 can be used for an external oscil-
lator and so may not be available as I/O;
AN0-AN4 can be used as analogue inputs
(giving five analogue inputs on port A).
PORT B
All eight pins of port B are usable as inputs or outputs:
RB0-RB7 can be used as digital inputs;
RB0-RB7 can be used as digital outputs;
an external interrupt pin is possible on RB0;
an external IOC (Interrupt On Change) is possible on any
of RB0-RB7;
AN8-AN13 can be used as analogue inputs (giving six ana-
logue inputs on port B).
PORT C
All eight pins of port C are usable as inputs or out-
puts:
RC0-RC7 can be used as digital inputs;
RC0-RC7 can be used as digital outputs;
PWM (Pulse Width Modulation) is possible
on RC1 and RC2;
Port C also contains a USART (Universal Syn-
chronous - Asynchronous Receiver Trans-
mitter) and a MSSP (Master Synchronous Se-
rial Port) for serial communication.
PORT D
All eight pins of port D are usable as inputs
or outputs:
RD0-RD7 can be used as digital in-
puts;
RD0-RD7 can be used as digital out-
puts.
PORT E
There are only four pins on port E:
RE0-RE3 can be used as digital inputs;
RE0-RE2 can be used as digital outputs;
RE3 can only be an input; (When used
as the MCLR pin (i.e. reset) it may not
be available as an input.)
AN5-AN7 can be used as analogue in-
puts (giving three analogue inputs on
port E).
Other subsystems in the 16F1937 PIC
Memory:
Flash
Flash memory is used to store the pro-
gram you write.
This program is 'compiled' by the com-
puter 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 after a power cut.
The Flash memory contained in the 16F1937 can store up to 8192 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 16F1937 can store up to 512 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 oc-
curs.
The EEPROM of the 16F1937 can store up to 256 bytes of data.
ALU:
The ALU (Arithmetic 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 instruction.
How the ALU works is very complicated. Fortunately ‘Flowcode 7’ programmers do not need to
know how it works.
Timer 1 (TMR1):
This timer interrupt is used to provide the PIC 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 7’.
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 mac-
ro.
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 PIC 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 7’. 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 available on the E-blocks Multiprogrammer used in this course.
The Multiprogrammer uses an external crystal oscillator, with a frequency of 19.660800MHz.
Why such a precise number?
The reason is that this frequency can be reduced, by a sequence of binary counters, to a standard
Baud rate to facilitate communication between systems, using protocols such as RS232.
In this case the fundamental clock frequency divided by 2 to the power of 10 is 19200Hz, an
internationally recognised standard serial communication Baud rate.
Mathematically:
19660800 / 210 = 19200
Clock Settings
When ‘Flowcode 7’ downloads a program to the microcontroller, it changes internal clock settings
and circuitry to mirror the external clock circuit on the Multiprogrammer board, as specified by the
programmer.
This is done by selecting ‘Build > Project Options...’ from the ‘Flowcode 7’ menu, giving this screen:
If the target microcontroller is not 'PIC16F1937' then click on the 'Choose a Target' tab.
Select ‘OK’.
Experienced users may wish to change some of the advanced settings on the chip. All this is done
from the screen shown above.
Introduction to E-blocks
E-blocks are small circuit boards that can be snapped together to form an electronic system.
There are two kinds of E-blocks:
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, RS232 boards etc.
E-blocks Projects
‘Upstream’ and ‘downstream’ boards can be snapped together
to form complete electronic systems, like this fully working
mobile phone.
E-blocks are compatible with a wide range of sensors and
accessories, enabling you to build a wide variety of systems.
Course hardware
The two main boards for this course are the EB006 Multiprogrammer and the EB083 Combo board,
described below.
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 microcontroller 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 7’’ and the PIC microcontroller.
The PIC microcontroller executes one instruction for every four clock pulses it receives.
(Note - a single instruction is NOT the same as a single ‘Flowcode 7’ 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 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.
Part 7
Course Rationale
Part 7 Contents
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
Learning Objectives
After completing this course, you will be able to:
to send different 8-bit codes to port B of the microcontroller;
to change the logic level of a one single pin of port B;
to configure an output icon;
to use binary code;
to manipulate logic output levels;
to use LED’s to display an output;
to compile a program to the PIC.
to add a delay to slow down execution of a program;
to change the delay interval;
to configure a delay icon;
to control the speed of a microcontroller;
to use an oscilloscope to time events .
to use Connection Points to introduce unconditional branching in a program;
to introduce PWM as a means of controlling the brightness of LEDs.
to create an infinite loop;
to manipulate logic output levels;
to use LEDs to display an output;
to create and use a variable;
to configure a calculation icon to perform arithmetic and logic calculations.
to create and manipulate variables;
to perform calculations;
to use LEDs with current limiting resistors;
to create and use a ‘running light’ program, using the ‘multiply-by-two’ method;
to create and use a ‘running light’ program, using the ‘shift-right’ method;
to create and populate an array;
to create a conditional loop;
to input data from switches;
to use loops to create LED sequences;
to configure an input icon;
to configure Decision icons and hence add conditional branching to a program;
to control the frequency at which LEDs flash;
to use LEDs to display output logic levels;
to use temporary memory;
to create, populate and manipulate string variables;
to control the display of text and numbers on a LCD;
to use a LCD as an output device for the PIC;
to configure a Component macro for the LCD;
to input text and numbers from a keypad and display messages on the LCD;
to use ASCII code to transmit this data;
to use multiplexed inputs;
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
thermistor
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
Copyright © 2016 Matrix Technology Solutions Limited www.matrixtsl.com
Page 114
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
Version control
www.matrixtsl.com
CP4375