SlideShare a Scribd company logo
1 of 37
NIE2206 Electronic Logbook
Name: xxx
Student ID: Uxxx
Term: Winter/Spring (delete as appropriate)
By submitting this logbook I confirm that I understand this is an
individual assignment and that this work is entirely my own.
Laboratory Practical 1 - XXX
Laboratory Aim
<Briefly paraphrase lab sheet here. Do not simply cut and paste
the material>
Exercise 1 - XXX
Aim of exercise
<Write a short aim for the exercise you are about to undertake,
what are you going to do in this exercise and why are you doing
it?>
Procedure
<Describe the tasks undertaken and evidence they were carried
out by:
Answering any questions posed in the lab sheet
Providing code snippets to showing your solution to a coding
exercise
Describing your approach to the code design including noting
any calculations
Noting any problems e.g. debugging
Note: You must show evidence that you have completed the set
tasks in order to gain credit.>
Remember: Context is the key here. It should be possible for a
reader to understand from your logbook, without reference to
the lab sheets:
What you did.
Why you did it.
How you did it.
Enter code listings using a fixed width font. Here I have used
the Code style built into this template which uses the Consolas
font as well as a compact line spacing to make code listings
compact and easy to read.
Insert evidence of calculations using the built-in Word equation
editor or a Word plug-in like Mathtype.
x=y/x + c become s + c
Outcomes
<Describe the outcome of the exercise. What did you observe?
Was it successful? Any unusual results that may need
explaining>
Conclusion
<Briefly summarise what was carried out. Be reflective - what
did you learn through completing this exercise?>
Exercise 2 - XXX
Aim of exercise
xxx
Procedure
xxx
Outcomes
xxx
Conclusion
xxx
Exercise 3 - XXX
Aim of exercise
xxx
Procedure
xxx
Outcomes
xxx
Conclusion
xxx
Laboratory Practical 2 - XXX
Laboratory Aim
Xxx
Exercise 1 - XXX
Aim of exercise
xxx
Procedure
xxx
Outcomes
xxx
Conclusion
xxx
Exercise 2 - XXX
Aim of exercise
xxx
Procedure
xxx
Outcomes
xxx
Conclusion
xxx
41
5 Lab 5 – Interrupts (part 1)
5.1 Aim
This laboratory practical will introduce you to the concept
of interrupts, which are an important
feature of all modern computer systems, including
microcontrollers. This lab will enable you to
comprehend the purpose of interrupts, and the way in which the
y can be utilised to optimise wasteful
processes such as event polling loops. Consideration of the diffe
rent hardware interrupts available on
the PIC16F877A will be undertaken in this laboratory practical,
and procedures will be developed for
their proper configuration and servicing.
5.2 Learning Outcomes
of the concept of interrupts and have
knowledge of the hardware
interrupts available on the PIC16F877A.
Knowledge of how interrupts are implemented and serviced on t
he PIC16F877A.
Ability to develop code that utilises interrupts on the PIC16F87
7A to carry out useful tasks.
5.3 Background
5.3.1 Introduction to interrupts
Interrupts are a feature of every modern computer system, whet
her it be a complex multicore CPU in
a desktop PC, or a simple 8 pin microcontroller in an electric to
othbrush. Interrupts allow computer
systems to react to events without using time wasteful processes
such as polling loops. Examples of
hardware events could be a logic state change on an external pin
, a timer overflow, or the completion
of an analogue‐to‐digital conversion.
5.3.2 Overview of instruction execution in a microcontroller
During normal code execution, the CPU retrieves
instructions from the program memory location
stored in the program counter. Under normal operation, after an
instruction has been executed, a
program counter automatically increments and the instruction he
ld in the next address in the program
memory is retrieved, see figure 5‐1.
Figure 5‐1 CPU instruction execution
In this way instructions are executed in a linear step‐wise fashio
n, one after another. The program
counter drives the retrieval and execution of instructions from t
he program memory. The program
counter can also be loaded with specific memory addresses to ca
use the CPU execution to jump (goto)
to the start of another sequence of instructions. This happens wh
en branches, loops or function calls
need to be implemented.
42
Figure 5‐2 Action of a goto instruction on CPU instruction
execution
A subroutine (known as a function in C/C++) call also causes th
e code to jump (goto) to the start of a
specific set of instructions. The key feature of a subroutine is th
at once its instructions have been
executed, the CPU returns back to the program memory address
it was at prior to the initial subroutine
call. This allows the same subroutine instructions to be called fr
om multiple points in the programme
execution because instruction execution will always return to th
e original memory location. To be able
to provide this capability a storage entity called a stack is requir
ed that can store the original memory
address. A stack is generally several levels deep and is an exam
ple of a last‐in‐first‐out (LIFO) data
structure. Several addresses may be pushed onto the stack, whic
h may then be popped back off in
reverse order. This action is illustrated in figure 5‐3.
Figure 5‐3 Pushing (top) and popping (bottom) addresses onto
the stack
When a subroutine is called, the current program memory addre
ss on the program counter is pushed
onto the stack. The program counter is then loaded with the pro
gram memory address containing the
start of the subroutine instructions. Once the subroutine
instructions have been executed, the
subroutine returns. At this point, the program memory address s
tored in the popped from the stack
and loaded onto the program counter. This action results in the
CPU returning to the program memory
location it was at prior to the function call. Figure 5‐4 and figur
e 5‐5 present a graphical overview of
this process.
43
Figure 5‐4 Overview of subroutine execution
Figure 5‐5 Detailed overview of subroutine execution including
call and return
As described earlier, the stack has several levels which means s
everal addresses may pushed onto it.
This allows the subroutines to be called from within subroutines
in a nested structure. Each subroutine
call results in the pushing of the current program counter addres
s onto the stack. When the function
returns, the previous address is popped back off again. In the PI
C16F877A, the stack is only 8 levels
deep so care must be taken not to nest too many subroutines (fu
nctions) or you may encounter a
stack overflow, which will result in undefined behaviour.
The XC8 compiler will produce warning
during the build process if it detects the potential for stack over
flow.
5.3.3 The interrupt service routine
The interrupt service routine (ISR) can be considered a special t
ype of function that is automatically
called when an interrupt event occurs. Figure 5‐6 shows the cycl
e of actions that takes place when an
interrupt event occurs. The sequence of events is precisely the s
ame as that which occurs during a
function call, except the interrupt vector is automatically loaded
into the program counter by the
hardware, which results in the ISR being called.
44
Figure 5‐6 Overview of interrupt servicing
MCUs may have several interrupt vectors, each of which link to
a different ISR. This allows the useful
grouping of interrupts event types in more complex
devices, for instance into different levels of
importance or priority. The PIC16F877A is a relatively simple d
evice having only 15 separate interrupt
events. It has only one interrupt vector and thus only one possib
le ISR.
ISR code
is often termed foreground code, which takes priority over the b
ackground code that is
executes continuously when there are no interrupts to service.
5.3.4 Interrupts on the PIC16F877A
For an event to actually trigger an interrupt, the interrupt
must first be enabled by setting
configuration bits in the specific SFRs. In this laboratory practi
cal we will be considering only three of
the interrupts available on the PIC16F877A (see table 5‐1).
Table 5‐1 The 3 interrupts to be studied in this laboratory
practical
Interrupt Event INTCON bits
TMR0 overflow Timer0 overflow occurs TMR0IE, TMR0IF
RB port change
interrupt
Logic level change on any of the pins RB7:4 (bits
4 to 7 of PORTB)
RBIE, RBIF
External interrupt Rising edge or falling edge on pin RB0.
INTE, INTF
These three interrupts can all be configured via the INTCON (in
terrupt control) SFR. The INTCON SFR
configuration bits are summarised in figure 5‐7. You will notice
that there are two bits associated with
each interrupt, an enable bit and a flag bit. In addition there are
two further bits, GIE (Global Interrupt
Enable) and PEIE (Peripheral Interrupt Enable). GIE acts as a ‘
master switch’ and disables all interrupts
when set to zero. PEIE enables the 12 remaining secondary inter
rupts which we will study in a later
laboratory.
45
Figure 5‐7 The INTCON register (adapted from the
PIC16F877A datasheet)
For an event to actually trigger an interrupt, the relevant interru
pt enable bit in the INTCON SFR must
be set. In addition the GIE bit must also be set. The interrupt fla
gs should also be cleared as a matter
of good practice during configuration so the MCU is in a known
state.
5.3.5 Interrupt configuration in MPLAB X and the XC8
compiler
Configuring interrupts can be done by writing the
appropriate value to the INTCON register. For
instance, in order to setup the Timer0 overflow register it is nec
essary to set the GIE and TMR0IE
registers. All other bits in the INTCON register should be cleare
d as shown below.
GIE PEIE TMR0IE INTE RBIE TMR0IF INTF RBIF
1 0 1 0 0 0 0 0
In this case, writing 0xA0 to the INTCON register configures th
e interrupt as required.
5.3.6 Coding ISRs in the MPLAB X and the XC8 compiler
The XC8 compiler uses the non‐standard, compiler specific key
word interrupt to define the interrupt
service routine (ISR). The ISR is defined in the same way as an
y other C function but it must be of type
void and contain no parameters. Furthermore a function prototy
pe is not required, because the ISR is
never called by the rest of the program, it is only called when a
n interrupt occurs. The syntax for
defining an interrupt is as follows:
void interrupt functionName (void)
{
// ISR code goes here
}
46
Because the PIC16F877A has only a single interrupt vector, the
first job of the ISR is to check which
interrupt has actually occurred and act accordingly. This is easil
y done by simply checking the relevant
interrupt flags as part of an if‐else‐if chain. In the
following code, all relevant interrupt flags are
checked. Code specific to each interrupt is only executed if the
relevant interrupt flag is set.
void interrupt myISR(void)
{
if(TMR0IF)
{
// Execute Timer0 overflow interrupt specific code
INTCONbits.TMR0IF = 0; // Reset flag
}
else if(INTF)
{
// Execute RB0 external interrupt specific code
INTCONbits.INTF = 0; // Reset flag
}
}
Keep to this structure rigidly. It is essential that you remember t
o reset the relevant interrupt flag after
you have executed the interrupt specific code. If this is not done
then you will inadvertently retrigger
the interrupt when you return from the ISR and your code execu
tion will get locked up.
5.3.7 Good practice when programming interrupts
ISRs can be difficult to debug because they are hardware driven
and respond to asynchronous events.
As such special care should be taken when designing code that
makes use of interrupts to ensure
against undefined behaviour.
enable the interrupts you want to use.
Ensure interrupt flags are cleared when you enable the interrupt
s.
Keep ISRs short and simple. This makes them easier to debug a
nd manage. It also reduces the
likelihood of missing further interrupt events. Limit
ISRs to simple tasks like incrementing
counter variables or changing custom flags. These can then be a
cted upon accordingly by the
background code.
if‐else‐if chain in your ISR should test interrupt flags
in order of likelihood. The most
commonly occurring interrupt should be at the top of the chain t
o increase code efficiency.
Use a strict if‐else‐if structure to test interrupt flags in your ISR
. This reduces the likelihood of
undefined behaviour in the event of an interrupt configuration e
rror elsewhere.
TIP!
Remember when an event occurs, the relevant interrupt flag
is set regardless of whether the
interrupt is enabled or not. In the Timer0 laboratory practical w
e used this facility detect a Timer0
overflow event by polling the TMR0IF flag.
47
5.4 Procedure
5.4.1 Exercise 1 – Implementing a Timer0 overflow interrupt
Create a new project in the MPLAB X IDE, add an empty source
file and populate it with the
following code listing.
// Filename: Lab5Ex1.c
// Version: 1.0
// Date: <Insert current date>
// Author: <Insert your name>
//
// Description: Implementing a Timer0 overflow interrupt
#include <xc.h> // Required for all MPLAB XC8 source
files
void main(void)
{
TRISD = 0x00; // Set up ports
PORTD = 0x00;
INTCON = 0xA0; // SET GIE, TMR0IE
// Set up Timer0 for 80 ms per overflow
OPTION_REGbits.T0CS = 0; // Set clock source to internal (ti
mer mode)
OPTION_REGbits.PSA = 0; // Set prescaler to Timer 0
OPTION_REGbits.PS = 7; // Set prescaler bits to 111 for 1
:256
while(1); // Do nothing
}
// Interrupt service routine
void interrupt myISR(void)
{
if(TMR0IF) // Timer0 overflow interrupt specific code
{
PORTD++;
INTCONbits.TMR0IF = 0; // Reset flag
}
}
Study the code listing carefully and build the project. Upload th
e HEX file onto the PIC16f877A
and observe the status of PORTD. Describe what is happening i
n terms of the interaction
between the main code, which is stuck in an infinite do‐nothing
loop, and the ISR.
5.4.2 Exercise 2 – Creating precise delays using interrupts
Create a new project and modify the code from Exercise 1 so th
at the PORTD LEDs count up
in binary at a rate of 1 Hz.
In order to do this you will need to modify the ISR so that POR
TD does not increment on every
Timer0 overflow interrupt but rather after a specific number of i
nterrupts. You can achieve
this by implementing a counter to keep track of the total number
of interrupts that have
occurred. You will also need to preload Timer0 at the appropriat
e point in the ISR.
48
If necessary, review the timer calculations you used to produce
a one second delay in section
3.4.3 to allow you choose a suitable Timer0 preload value deter
mine how many interrupts to
count. Do not simply place a for loop in the ISR to create the
delay, the background code
should continue to execute between ISR calls.
Write down a high‐level flow chart showing the operation of the
ISR ONLY.
5.4.3 Exercise 3 – Adding background code functionality
Create a new project and modify the code you developed in sect
ion 5.4.2 so that instead of
the main() function doing nothing, it performs a useful task.
In this case that task is to toggle bit 7 of PORTB every 250 ms.
This may be achieved by XORing
the relevant bit with 1, so in this case,
PORTB = PORTB ^ 0x80;
or alternatively, in a more compact notation,
PORTB ^= 0x80;
You should create the required delay using the __delay_ms() ma
cro, review section 2.4.1 to
see the correct useage. Do not forget to insert the following stat
ement in your code listing,
near the top of the file,
#define _XTAL_FREQ 3276800
This defines the MCU oscillator frequency which is needed by t
he __delay_ms() function to
calculate the delay correctly. Failure to include it will lead to a
compilation error.
Write down an XOR truth table and describe how the XOR oper
ation toggles bit 7 of PORTB.
5.4.4 Exercise 4 – Servicing multiple interrupts
Create a new project and modify the code in you developed in s
ection 5.4.3 to add a reset
button functionality. When SW0 on the E‐block switchboard co
nnected to PORTB is pressed,
then the binary count value should reset back to zero.
This functionality should be implemented using the RB0/INT ex
ternal interrupt flag to detect
a button press on SW0 of the PORTB switchboard.
Take care to set up the TRISB register so the PORTB directions
are correct, for the RB0/INT
external interrupt to operate RB0 must be an input. You will als
o need to modify the INTCON
register and the ISR to achieve this goal.
5.5 Further reading
More useful information on implementing ISRs can be
found in section 5.9 of the MPLAB XC8 C
Compiler User Guide available on Unilearn or at,
http://ww1.microchip.com/downloads/en/DeviceDoc/50002053
F.pdf
More MCU specific information on interrupts can be found in se
ction 8 of the PICmicro Mid‐Range
MCU Family Reference Manual available on Unilearn or at,
49
http://ww1.microchip.com/downloads/en/DeviceDoc/33023a.pdf
32
4 Lab 4 – Timer0 module
4.1 Aim
This laboratory practical will introduce you to the Timer0 modu
le which is one of three timer/counter
peripherals
located on the PIC16F877A MCU. Timer/counter modules allow
the creation of precise
and deterministic timing intervals which is essential in
many applications e.g. frequency
generation/measurement, timekeeping, control systems, commun
ications. This laboratory practical
will focus on the proper configuration and usage of the Timer0
module in timer mode only.
4.2 Learning Outcomes
Understand the structure of the Timer0 module on the PIC16F87
7A
Be able to configure the Timer0 module using the appropriate sp
ecial function registers
Be able to develop projects to utilise the Timer0 module in a ra
nge of applications.
4.3 Background
4.3.1 Counter/Timers
The only practical difference between a counter and a timer
is the nature of the source. A counter
simply increments a stored ‘count’ value when a logic state cha
nge (either a rising or falling edge) is
received at its input. To operate a counter as a timer, a synchron
ous pulse train (clock) of a known
frequency is applied to the input. Figure 4‐1 shows a generic re
presentation of a counter configured
as a timer. The current count value can be read from the counter
register, and the register can also be
written to or ‘preloaded’.
Figure 4‐1 Generic representation of a hardware timer module
If the frequency of the synchronous pulse train, f is
known then the elapsed time, T may be
determined from number of counts, N
recorded by the timer as follows,
NT
f
4.3.2 PIC16F877A Timer0 module
The Timer0 module on the PIC16F877A MCU is an 8 bit pre‐sca
lable timer/counter. In timer mode, the
TMR0 special function register (SFR) is automatically incremen
ted on every instruction clock cycle. In
counter mode, the TMR0 SFR is incremented either on
rising or on falling edge (configuration
dependant) of the external pin RA4/T0CKL. In this laboratory p
ractical we will only be considering the
use of Timer0 in timer mode.
33
The 8 bit Timer0 module on board the PIC16F877A can store
independent values from 0‐
255. The current count value is stored in the TMR0 SFR may be
read at any time without affecting the
operation of the Timer0 module. It may also written to (preload
ed) by writing the appropriate value
to the TMR0 SFR.
When the Timer0 module count value reaches its maximum valu
e (255), the counter overflows back
to zero and continues counting. This timer overflow results in
the setting of a bit (TMR0IF) in the
INTCON SFR. Figure 4‐2 show the structure of the INTCON SF
R which we will be looking at in more
detail in future laboratory practicals. For the moment just reme
mber that when a Timer0 overflow
occurs then the TMR0IF bit is SET.
Figure 4‐2 The INTCON register
A single bit which signifies an occurrence of an event, in this ca
se a Timer0 overflow, is called a flag.
We can detect when the overflow Timer0 has occurred by regula
rly checking the status of the TMR0IF
bit (flag) in a process known as polling. By using polling in con
junction with loops it is possible to create
accurate delays.
Timer0 receives its synchronous pulse train (clock) at the
instruction cycle rate of the PIC16F877A
MCU, which is one quarter of the frequency of the quartz crysta
l oscillator used to clock the MCU. For
the 3.2768 MHz crystal oscillators used on the E‐block develop
ment systems, this yields an instruction
cycle rate, CYf of
63.2768 10 819.2 kHz
4CY
The instruction cycle period,
is then simply the reciprocal of the instruction cycle rate,
CYf .
Along with the basic operation as a timer/counter, the Timer0 m
odule also has a prescaler associated
with it. A prescaler is a
logical device that reduced the frequency of the
incoming clock by integer
division. The prescaler may be set to divide down the incoming
clock by a range of preconfigured ratios
from 1:2 to 1:256.
For example, setting the Timer0 prescaler to 1:128 will increme
nt the timer at a now‐reduced rate of
It is important that the prescaler is
configured correctly so that the required
timings are obtained for the application in question.
4.3.3 Timer0 module configuration overview
A schematic representation of the timer module is shown
in figure 4‐3 which shows the various
elements which need to be correctly configured including the pr
ogrammable prescaler module and
two multiplexers, which select the clock source and enable the p
rescaler respectively.
34
Figure 4‐3 Schematic of the Timer0 module (adapted from
PIC16F877A MCU datasheet)
The Timer0 module is configured using the OPTION_REG SFR
which contains configuration bits to set
the clock source, prescaler value etc. Figure 4‐4 shows the
location of the configuring bits in the
OPTION_REG SFR. Note carefully at how the bit names relate t
o the schematic elements in figure 4‐3.
Figure 4‐4 The OPTION_REG SFR configuration bits (adapted
from PIC16F877A datasheet)
Only bits 0 to 5 of the OPTION_REG SFR are needed to config
ure the Timer0 module, bits RBPU and
INTEDG are used other peripheral configuration purposes that
we need not concern ourselves with
for the moment. In order to use the Timer0 module as in timer m
ode the properties of the relevant
configuration bits must be set up as shown in Table 4‐1.
Table 4‐1 Correct OPTION_REG configuration of using Timer0
in timer mode
Bit Name Bit location in
OPTION_REG
MPLAB XC8 syntax Configuration requirements
T0CS 5 INTCONbits.TOCS
Set to 0 to use Timer0 in timer mode
T0SE 4 INTCONbits.TOSE
No effect in timer mode (don’t care state)
PSA 3 INTCONbits.PSA
Set to 0 in timer mode to utilise the prescaler
PS2:0 2:0 INTCONbits.PS Define as required by application
The divide down value of the prescaler is selected by setting the
three bits, PS2:0 according to table
4‐2, 8 discrete options are available.
35
Table 4‐2 Timer0 prescaler configuration
PS2, PS1, PS0 Value TMR0 Rate
000 0 1:2
001 1 1:4
010 2 1:8
011 3 1:16
100 4 1:32
101 5 1:64
110 6 1:128
111 7 1:256
Note that a number of related bits in a SFR (in this case PS2:0)
are termed a ‘bit field’.
To summarise, the bitwise configuration of the OPTION_REG S
FR (see figure 4‐4) for operation of timer
0 in timer mode may be considered as follows:
OPTION_REG = XX0X 0UUU
where X = a don’t care state and U = a user defined state.
4.3.4 Calculation of timer counts and intervals
The prescaler and instruction clock rate are crucial parameters i
n determining/creating delays using
the Timer0 module. The total delay created by a given number o
f Timer0 counts is
4 prescaler 0countdelay
osc
TMR
f
where OSCf
is the frequency of the quartz crystal used to clock the PIC16F8
77A. This formula takes
into account the prescaler ratio and the fact that the instruction
clock rate is a quarter of the crystal
frequency (see section 4.3.2). Rearranging the above equation in
order to determine the number of
TMR0 counts to create a specific delay yields,
delay0count
4 prescaler
Remember that the maximum number of counts the 8 bit Timer0
module can store before overflowing
is 256.
For example, if a 10 ms delay is required, with the prescaler div
ide down ratio set to 1:256, then the
required number of TMR0 counts is as follows.
3 6delay 10 10 3.2768 100count 32
4 prescaler 4 256
oscfTMR
When 32 counts of the Timer0 module have occurred, we know t
hat 10 ms have elapsed. We can use
this information to design a delay loops.
36
4.3.5 Timer0 configuration procedure
With the information shown in the previous section it is possibl
e to derive a configuration procedure
for Timer0 as follows:
TOCS = 0 to enable timer mode
If using the prescaler, set PSA = 0. If not set PSA = 1 and skip t
he next step.
Calculate required prescaler divide down ratio and write the app
ropriate 3 bit value to the
PS bit field.
4.4 Procedure
4.4.1 Exercise 1 – Creating a simple delay using the Timer0
module
Create a new project in the MPLAB X IDE, create an empty sou
rce file, and populate it with
the following code listing.
// Filename: Lab4Ex1.c
// Version: 1.0
// Date: <Insert current date>
// Author: <Insert your name>
//
// Description: Simple demonstration of a timer delay
#include <xc.h> // Required for all MPLAB XC8 source
files
void main(void)
{
unsigned char preload = 0x00; // TMR0 preload variable
// PORTD setup
TRISD = 0x00; // Set PORTD all outputs
PORTD = 0x00; // Clear PORTD
//Timer0 setup
OPTION_REGbits.T0CS = 0; // Set clock source to internal
(timer mode)
OPTION_REGbits.PSA = 0; // Set prescaler to Timer 0
OPTION_REGbits.PS = 7; // Set prescaler bit field to 111
for 1:256
while(1) // Infinite loop
{
TMR0 = preload; // Preload timer0
while(!INTCONbits.TMR0IF); // Delay loop: Wait until
TMR0 overflows
INTCONbits.TMR0IF = 0; // Reset overflow flag, TM
R0IF
PORTD++; // Increment PORTD
}
}
Build the project and upload the HEX file onto the PIC16F877A
MCU.
Study the code listing carefully and observe what is happening t
o the LEDs on PORTD. You
should see PORTD incrementing from 0 to 255 in binary. Sketc
h a flow chart in your logbook
describing the sequence of events occurring in the executing co
de.
Calculate the length of the implemented delay using the appropr
iate formulae from section
4.3.4. Keep in mind that TMR0 is preloaded with 0x00 and the d
elay loop repeats until TMR0
37
overflows from 0xFF to 0x00 i.e. the loop condition becomes F
ALSE. In the general case for
the code listing above:
Using a stopwatch, time how long it takes for the LEDs on POR
TD to count up to 256 i.e. turn
from all OFF to all ON. Calculate the delay time for one individ
ual count by dividing the total
time by 256.
Compare you calculated result from the empirical result obtaine
d using a stopwatch. Does it
agree, taking into account any possible experimental error?
What happens if you increase the value of the preload variable i
n the code listing above?
4.4.2 Exercise 2 – Creating longer delays
In the previous exercise you created the longest possible delay u
sing Timer0 i.e. with the prescaler set
to a maximum divide down ratio of 1:256, and the full count of
TMR0 used i.e. from zero (0x00) until
it overflowed. However, there are many occasions when a longe
r delay than is possible using a single
timer overflow is required. One possible approach to this
is to cascade several shorter delays, in a
loop, to create a longer overall delay.
Create a new project in the MPLAB X
IDE, add an empty source file and add the following
code listing to it.
// Filename: Lab4Ex2.c
// Version: 1.0
// Date: <Insert current date>
// Author: <Insert your name>
//
// Description: Looping of a short timer delay to create a longer
one
#include <xc.h> // Required for all MPLAB XC8 source
files
void main(void)
{
unsigned char preload = 192; // TMR0 preload variable
unsigned char i; // Loop index variable
// PORTD setup
TRISD = 0x00; // Set PORTD all outputs
PORTD = 0x00; // Clear PORTD
//Timer0 setup
OPTION_REGbits.T0CS = 0; // Set clock source to internal
(timer mode)
OPTION_REGbits.PSA = 0; // Set prescaler to Timer 0
TIP!
When a Timer0 overflow occurs and the TMR0IF bit
is SET and remains in that state until it is
manually RESET in software. This can be done using the follow
ing syntax:
INTCONbits.TMR0IF = 0;
It is important to remember to do this when you are polling for t
imer overflows.
38
OPTION_REGbits.PS = 7; // Set prescaler bits to 111 for
1:256
while(1) // Infinite loop
{
for(i=0;i<8;i++) // Loop to cascade several short delay
s together
{
TMR0 = preload; // Preload timer0
while(!INTCONbits.TMR0IF); // Delay loop: Wait unt
il TMR0 overflows
INTCONbits.TMR0IF = 0; // Reset overflow flag,
TMR0IF
}
PORTD++; // Increment PORTD
}
}
Calculate the length of the delay implemented using bearing
in mind that the value of the
preload variable is now set to 192 and the shorter delay loop is
now repeated 8 times.
Using a stopwatch, time how long it takes for the LEDs on POR
TD to count up to 256 i.e. turn
from all OFF to all ON. Calculate the delay time for one individ
ual count by dividing the total
time by 256.
Compare you calculated result from the empirical result obtaine
d using a stopwatch. Does it
agree, taking into account any possible experimental error?
Modify the code to create a one second delay. You should appro
ach this by adjusting the
preload value so that the short delay loop has a length that divid
es exactly into one second.
This short delay should then be repeated the required number of
times to produce a one
second delay.
Confirm your results using a stopwatch.
4.4.3 Exercise 3 – Creating a one second delay function
A delay is a useful and often used action in any embedded
system. Having gone to the effort of
developing a one second delay it would make sense to package t
he code into a function so that it could
be easily reused whenever required.
The following code listing shows one possible template for impl
ementing the one second delay as a
function call one_sec_delay(). The operation of this code
is exactly the same as that produced in
exercise 3, the only difference
is that all the code that had previously been required to create th
e
delay has now been packaged inside a function which is called f
rom the main() function.
Create a project and enter the following listing. You will need
to replace the two ‘??’ symbols
in the listing
below with the values you derived in the previous exercise in or
der for it to build
successfully.
// Filename: Lab4Ex3.c
// Version: 1.0
// Date: <Insert current date>
// Author: <Insert your name>
//
// Description: Implementing a Timer0 delay function
#include <xc.h> // Required for all MPLAB XC8 source
files
39
void one_sec_delay (void); // Function prototype
void main(void)
{
// PORTD setup
TRISD = 0x00; // Set PORTD all outputs
PORTD = 0x00; // Clear PORTD
while(1) // Infinite loop
{
one_sec_delay(); // Call delay function
PORTD++; // Increment PORTD
}
}
void one_sec_delay (void)
{
unsigned char preload = ??; // TMR0 preload variable (deri
ved from Ex2)
unsigned char i; // Loop index variable
//Timer0 setup
OPTION_REGbits.T0CS = 0; // Set clock source to internal
(timer mode)
OPTION_REGbits.PSA = 0; // Set prescaler to Timer 0
OPTION_REGbits.PS = 7; // Set prescaler bits to 111 for
1:256
for(i=0;i<??;i++) // Loop to cascade several short delays
together
// Number of loops derived from Ex2
{
TMR0 = preload; // Preload timer0
while(!INTCONbits.TMR0IF); // Delay loop: Wait until
TMR0 overflows
INTCONbits.TMR0IF = 0; // Reset overflow flag, TM
R0IF
}
}
Build the project and validate that the operation is as anticipate
d.
4.4.4 Exercise 4 – Creating a variable delay function
In this exercise we will develop a generic variable delay functio
n that will allow the implementation of
any user defined delay of an integer number of seconds
Create a new project based upon the code developed in exercise
3.
Modify the fixed one second delay function, one_sec_delay() de
veloped in exercise 3 so that
it becomes a generic delay function taking the form,
void delay(unsigned char delay_length)
where the parameter delay_length sets the length of the delay i
mplemented by the function.
The parameter will need to modify
the number of cascaded short delays to generate the
variable delay.
4.5 Further reading
Microchip MPLAB X Timer0 (Part 1) tutorial sheet. Note
the code listings show is not directly
compatible with the XC8 compiler, but the information about co
nfiguration is still relevant.

More Related Content

Similar to NIE2206 Electronic LogbookNamexxxStudent IDUxxxTe.docx

Basic MIPS implementation
Basic MIPS implementationBasic MIPS implementation
Basic MIPS implementationkavitha2009
 
Bca examination 2015 csa
Bca examination 2015 csaBca examination 2015 csa
Bca examination 2015 csaAnjaan Gajendra
 
MIPS IMPLEMENTATION.pptx
MIPS IMPLEMENTATION.pptxMIPS IMPLEMENTATION.pptx
MIPS IMPLEMENTATION.pptxJEEVANANTHAMG6
 
Readregister 1Readregister 2WriteregisterWri.docx
Readregister 1Readregister 2WriteregisterWri.docxReadregister 1Readregister 2WriteregisterWri.docx
Readregister 1Readregister 2WriteregisterWri.docxsedgar5
 
Operating system
Operating systemOperating system
Operating systemraj732723
 
Micro c lab2(led patterns)
Micro c lab2(led patterns)Micro c lab2(led patterns)
Micro c lab2(led patterns)Mashood
 
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docxCASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docxketurahhazelhurst
 
03. top level view of computer function &amp; interconnection
03. top level view of computer function &amp; interconnection03. top level view of computer function &amp; interconnection
03. top level view of computer function &amp; interconnectionnoman yasin
 
Ecet 360 Enthusiastic Study / snaptutorial.com
Ecet 360 Enthusiastic Study / snaptutorial.comEcet 360 Enthusiastic Study / snaptutorial.com
Ecet 360 Enthusiastic Study / snaptutorial.comStephenson34
 
Ecet 360 Success Begins / snaptutorial.com
Ecet 360  Success Begins / snaptutorial.comEcet 360  Success Begins / snaptutorial.com
Ecet 360 Success Begins / snaptutorial.comWilliamsTaylorzl
 
Ecet 360 Massive Success / snaptutorial.com
Ecet 360 Massive Success / snaptutorial.comEcet 360 Massive Success / snaptutorial.com
Ecet 360 Massive Success / snaptutorial.comHarrisGeorgx
 
Compuer organizaion processing unit
Compuer organizaion processing unitCompuer organizaion processing unit
Compuer organizaion processing unitDeepak John
 
Advanced Techniques for Exploiting ILP
Advanced Techniques for Exploiting ILPAdvanced Techniques for Exploiting ILP
Advanced Techniques for Exploiting ILPA B Shinde
 
Review on 32 bit single precision Floating point unit (FPU) Based on IEEE 754...
Review on 32 bit single precision Floating point unit (FPU) Based on IEEE 754...Review on 32 bit single precision Floating point unit (FPU) Based on IEEE 754...
Review on 32 bit single precision Floating point unit (FPU) Based on IEEE 754...IRJET Journal
 
Run time, frequently, non-frequently reconfigurable system &
Run time, frequently, non-frequently reconfigurable system &Run time, frequently, non-frequently reconfigurable system &
Run time, frequently, non-frequently reconfigurable system &Sudhanshu Janwadkar
 

Similar to NIE2206 Electronic LogbookNamexxxStudent IDUxxxTe.docx (20)

Basic MIPS implementation
Basic MIPS implementationBasic MIPS implementation
Basic MIPS implementation
 
Bca examination 2015 csa
Bca examination 2015 csaBca examination 2015 csa
Bca examination 2015 csa
 
MIPS IMPLEMENTATION.pptx
MIPS IMPLEMENTATION.pptxMIPS IMPLEMENTATION.pptx
MIPS IMPLEMENTATION.pptx
 
Readregister 1Readregister 2WriteregisterWri.docx
Readregister 1Readregister 2WriteregisterWri.docxReadregister 1Readregister 2WriteregisterWri.docx
Readregister 1Readregister 2WriteregisterWri.docx
 
ES-CH6.ppt
ES-CH6.pptES-CH6.ppt
ES-CH6.ppt
 
Operating system
Operating systemOperating system
Operating system
 
Pipeline Computing by S. M. Risalat Hasan Chowdhury
Pipeline Computing by S. M. Risalat Hasan ChowdhuryPipeline Computing by S. M. Risalat Hasan Chowdhury
Pipeline Computing by S. M. Risalat Hasan Chowdhury
 
Micro c lab2(led patterns)
Micro c lab2(led patterns)Micro c lab2(led patterns)
Micro c lab2(led patterns)
 
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docxCASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
 
Lab Manual.pdf
Lab Manual.pdfLab Manual.pdf
Lab Manual.pdf
 
03. top level view of computer function &amp; interconnection
03. top level view of computer function &amp; interconnection03. top level view of computer function &amp; interconnection
03. top level view of computer function &amp; interconnection
 
Chapter 8
Chapter 8Chapter 8
Chapter 8
 
Ecet 360 Enthusiastic Study / snaptutorial.com
Ecet 360 Enthusiastic Study / snaptutorial.comEcet 360 Enthusiastic Study / snaptutorial.com
Ecet 360 Enthusiastic Study / snaptutorial.com
 
Ecet 360 Success Begins / snaptutorial.com
Ecet 360  Success Begins / snaptutorial.comEcet 360  Success Begins / snaptutorial.com
Ecet 360 Success Begins / snaptutorial.com
 
Ecet 360 Massive Success / snaptutorial.com
Ecet 360 Massive Success / snaptutorial.comEcet 360 Massive Success / snaptutorial.com
Ecet 360 Massive Success / snaptutorial.com
 
Compuer organizaion processing unit
Compuer organizaion processing unitCompuer organizaion processing unit
Compuer organizaion processing unit
 
Design
DesignDesign
Design
 
Advanced Techniques for Exploiting ILP
Advanced Techniques for Exploiting ILPAdvanced Techniques for Exploiting ILP
Advanced Techniques for Exploiting ILP
 
Review on 32 bit single precision Floating point unit (FPU) Based on IEEE 754...
Review on 32 bit single precision Floating point unit (FPU) Based on IEEE 754...Review on 32 bit single precision Floating point unit (FPU) Based on IEEE 754...
Review on 32 bit single precision Floating point unit (FPU) Based on IEEE 754...
 
Run time, frequently, non-frequently reconfigurable system &
Run time, frequently, non-frequently reconfigurable system &Run time, frequently, non-frequently reconfigurable system &
Run time, frequently, non-frequently reconfigurable system &
 

More from curwenmichaela

BUS310ASSIGNMENTImagine that you work for a company with an ag.docx
BUS310ASSIGNMENTImagine that you work for a company with an ag.docxBUS310ASSIGNMENTImagine that you work for a company with an ag.docx
BUS310ASSIGNMENTImagine that you work for a company with an ag.docxcurwenmichaela
 
BUS357 Copyright © 2020 Singapore University of Social Science.docx
BUS357 Copyright © 2020 Singapore University of Social Science.docxBUS357 Copyright © 2020 Singapore University of Social Science.docx
BUS357 Copyright © 2020 Singapore University of Social Science.docxcurwenmichaela
 
BUS308 – Week 1 Lecture 2 Describing Data Expected Out.docx
BUS308 – Week 1 Lecture 2 Describing Data Expected Out.docxBUS308 – Week 1 Lecture 2 Describing Data Expected Out.docx
BUS308 – Week 1 Lecture 2 Describing Data Expected Out.docxcurwenmichaela
 
BUS308 – Week 5 Lecture 1 A Different View Expected Ou.docx
BUS308 – Week 5 Lecture 1 A Different View Expected Ou.docxBUS308 – Week 5 Lecture 1 A Different View Expected Ou.docx
BUS308 – Week 5 Lecture 1 A Different View Expected Ou.docxcurwenmichaela
 
BUS308 – Week 1 Lecture 1 Statistics Expected Outcomes.docx
BUS308 – Week 1 Lecture 1 Statistics Expected Outcomes.docxBUS308 – Week 1 Lecture 1 Statistics Expected Outcomes.docx
BUS308 – Week 1 Lecture 1 Statistics Expected Outcomes.docxcurwenmichaela
 
BUS308 Statistics for ManagersDiscussions To participate in .docx
BUS308 Statistics for ManagersDiscussions To participate in .docxBUS308 Statistics for ManagersDiscussions To participate in .docx
BUS308 Statistics for ManagersDiscussions To participate in .docxcurwenmichaela
 
BUS308 Week 4 Lecture 1 Examining Relationships Expect.docx
BUS308 Week 4 Lecture 1 Examining Relationships Expect.docxBUS308 Week 4 Lecture 1 Examining Relationships Expect.docx
BUS308 Week 4 Lecture 1 Examining Relationships Expect.docxcurwenmichaela
 
BUS225 Group Assignment1. Service BlueprintCustomer acti.docx
BUS225 Group Assignment1. Service BlueprintCustomer acti.docxBUS225 Group Assignment1. Service BlueprintCustomer acti.docx
BUS225 Group Assignment1. Service BlueprintCustomer acti.docxcurwenmichaela
 
BUS301 Memo Rubric Spring 2020 - Student.docxBUS301 Writing Ru.docx
BUS301 Memo Rubric Spring 2020 - Student.docxBUS301 Writing Ru.docxBUS301 Memo Rubric Spring 2020 - Student.docxBUS301 Writing Ru.docx
BUS301 Memo Rubric Spring 2020 - Student.docxBUS301 Writing Ru.docxcurwenmichaela
 
BUS1431Introduction and PreferencesBUS143 Judgmen.docx
BUS1431Introduction and PreferencesBUS143 Judgmen.docxBUS1431Introduction and PreferencesBUS143 Judgmen.docx
BUS1431Introduction and PreferencesBUS143 Judgmen.docxcurwenmichaela
 
BUS210 analysis – open question codesQ7a01 Monthly OK02 Not .docx
BUS210 analysis – open question codesQ7a01 Monthly OK02 Not .docxBUS210 analysis – open question codesQ7a01 Monthly OK02 Not .docx
BUS210 analysis – open question codesQ7a01 Monthly OK02 Not .docxcurwenmichaela
 
Bus101 quiz (Business Organizations)The due time is in 1hrs1 .docx
Bus101 quiz (Business Organizations)The due time is in 1hrs1 .docxBus101 quiz (Business Organizations)The due time is in 1hrs1 .docx
Bus101 quiz (Business Organizations)The due time is in 1hrs1 .docxcurwenmichaela
 
BUS 625 Week 4 Response to Discussion 2Guided Response Your.docx
BUS 625 Week 4 Response to Discussion 2Guided Response Your.docxBUS 625 Week 4 Response to Discussion 2Guided Response Your.docx
BUS 625 Week 4 Response to Discussion 2Guided Response Your.docxcurwenmichaela
 
BUS 625 Week 2 Response for Discussion 1 & 2Week 2 Discussion 1 .docx
BUS 625 Week 2 Response for Discussion 1 & 2Week 2 Discussion 1 .docxBUS 625 Week 2 Response for Discussion 1 & 2Week 2 Discussion 1 .docx
BUS 625 Week 2 Response for Discussion 1 & 2Week 2 Discussion 1 .docxcurwenmichaela
 
Bus 626 Week 6 - Discussion Forum 1Guided Response Respon.docx
Bus 626 Week 6 - Discussion Forum 1Guided Response Respon.docxBus 626 Week 6 - Discussion Forum 1Guided Response Respon.docx
Bus 626 Week 6 - Discussion Forum 1Guided Response Respon.docxcurwenmichaela
 
BUS 499, Week 8 Corporate Governance Slide #TopicNarration.docx
BUS 499, Week 8 Corporate Governance Slide #TopicNarration.docxBUS 499, Week 8 Corporate Governance Slide #TopicNarration.docx
BUS 499, Week 8 Corporate Governance Slide #TopicNarration.docxcurwenmichaela
 
BUS 499, Week 6 Acquisition and Restructuring StrategiesSlide #.docx
BUS 499, Week 6 Acquisition and Restructuring StrategiesSlide #.docxBUS 499, Week 6 Acquisition and Restructuring StrategiesSlide #.docx
BUS 499, Week 6 Acquisition and Restructuring StrategiesSlide #.docxcurwenmichaela
 
BUS 499, Week 4 Business-Level Strategy, Competitive Rivalry, and.docx
BUS 499, Week 4 Business-Level Strategy, Competitive Rivalry, and.docxBUS 499, Week 4 Business-Level Strategy, Competitive Rivalry, and.docx
BUS 499, Week 4 Business-Level Strategy, Competitive Rivalry, and.docxcurwenmichaela
 
BUS 437 Project Procurement Management Discussion QuestionsWe.docx
BUS 437 Project Procurement Management  Discussion QuestionsWe.docxBUS 437 Project Procurement Management  Discussion QuestionsWe.docx
BUS 437 Project Procurement Management Discussion QuestionsWe.docxcurwenmichaela
 
BUS 480.01HY Case Study Assignment Instructions .docx
BUS 480.01HY Case Study Assignment Instructions     .docxBUS 480.01HY Case Study Assignment Instructions     .docx
BUS 480.01HY Case Study Assignment Instructions .docxcurwenmichaela
 

More from curwenmichaela (20)

BUS310ASSIGNMENTImagine that you work for a company with an ag.docx
BUS310ASSIGNMENTImagine that you work for a company with an ag.docxBUS310ASSIGNMENTImagine that you work for a company with an ag.docx
BUS310ASSIGNMENTImagine that you work for a company with an ag.docx
 
BUS357 Copyright © 2020 Singapore University of Social Science.docx
BUS357 Copyright © 2020 Singapore University of Social Science.docxBUS357 Copyright © 2020 Singapore University of Social Science.docx
BUS357 Copyright © 2020 Singapore University of Social Science.docx
 
BUS308 – Week 1 Lecture 2 Describing Data Expected Out.docx
BUS308 – Week 1 Lecture 2 Describing Data Expected Out.docxBUS308 – Week 1 Lecture 2 Describing Data Expected Out.docx
BUS308 – Week 1 Lecture 2 Describing Data Expected Out.docx
 
BUS308 – Week 5 Lecture 1 A Different View Expected Ou.docx
BUS308 – Week 5 Lecture 1 A Different View Expected Ou.docxBUS308 – Week 5 Lecture 1 A Different View Expected Ou.docx
BUS308 – Week 5 Lecture 1 A Different View Expected Ou.docx
 
BUS308 – Week 1 Lecture 1 Statistics Expected Outcomes.docx
BUS308 – Week 1 Lecture 1 Statistics Expected Outcomes.docxBUS308 – Week 1 Lecture 1 Statistics Expected Outcomes.docx
BUS308 – Week 1 Lecture 1 Statistics Expected Outcomes.docx
 
BUS308 Statistics for ManagersDiscussions To participate in .docx
BUS308 Statistics for ManagersDiscussions To participate in .docxBUS308 Statistics for ManagersDiscussions To participate in .docx
BUS308 Statistics for ManagersDiscussions To participate in .docx
 
BUS308 Week 4 Lecture 1 Examining Relationships Expect.docx
BUS308 Week 4 Lecture 1 Examining Relationships Expect.docxBUS308 Week 4 Lecture 1 Examining Relationships Expect.docx
BUS308 Week 4 Lecture 1 Examining Relationships Expect.docx
 
BUS225 Group Assignment1. Service BlueprintCustomer acti.docx
BUS225 Group Assignment1. Service BlueprintCustomer acti.docxBUS225 Group Assignment1. Service BlueprintCustomer acti.docx
BUS225 Group Assignment1. Service BlueprintCustomer acti.docx
 
BUS301 Memo Rubric Spring 2020 - Student.docxBUS301 Writing Ru.docx
BUS301 Memo Rubric Spring 2020 - Student.docxBUS301 Writing Ru.docxBUS301 Memo Rubric Spring 2020 - Student.docxBUS301 Writing Ru.docx
BUS301 Memo Rubric Spring 2020 - Student.docxBUS301 Writing Ru.docx
 
BUS1431Introduction and PreferencesBUS143 Judgmen.docx
BUS1431Introduction and PreferencesBUS143 Judgmen.docxBUS1431Introduction and PreferencesBUS143 Judgmen.docx
BUS1431Introduction and PreferencesBUS143 Judgmen.docx
 
BUS210 analysis – open question codesQ7a01 Monthly OK02 Not .docx
BUS210 analysis – open question codesQ7a01 Monthly OK02 Not .docxBUS210 analysis – open question codesQ7a01 Monthly OK02 Not .docx
BUS210 analysis – open question codesQ7a01 Monthly OK02 Not .docx
 
Bus101 quiz (Business Organizations)The due time is in 1hrs1 .docx
Bus101 quiz (Business Organizations)The due time is in 1hrs1 .docxBus101 quiz (Business Organizations)The due time is in 1hrs1 .docx
Bus101 quiz (Business Organizations)The due time is in 1hrs1 .docx
 
BUS 625 Week 4 Response to Discussion 2Guided Response Your.docx
BUS 625 Week 4 Response to Discussion 2Guided Response Your.docxBUS 625 Week 4 Response to Discussion 2Guided Response Your.docx
BUS 625 Week 4 Response to Discussion 2Guided Response Your.docx
 
BUS 625 Week 2 Response for Discussion 1 & 2Week 2 Discussion 1 .docx
BUS 625 Week 2 Response for Discussion 1 & 2Week 2 Discussion 1 .docxBUS 625 Week 2 Response for Discussion 1 & 2Week 2 Discussion 1 .docx
BUS 625 Week 2 Response for Discussion 1 & 2Week 2 Discussion 1 .docx
 
Bus 626 Week 6 - Discussion Forum 1Guided Response Respon.docx
Bus 626 Week 6 - Discussion Forum 1Guided Response Respon.docxBus 626 Week 6 - Discussion Forum 1Guided Response Respon.docx
Bus 626 Week 6 - Discussion Forum 1Guided Response Respon.docx
 
BUS 499, Week 8 Corporate Governance Slide #TopicNarration.docx
BUS 499, Week 8 Corporate Governance Slide #TopicNarration.docxBUS 499, Week 8 Corporate Governance Slide #TopicNarration.docx
BUS 499, Week 8 Corporate Governance Slide #TopicNarration.docx
 
BUS 499, Week 6 Acquisition and Restructuring StrategiesSlide #.docx
BUS 499, Week 6 Acquisition and Restructuring StrategiesSlide #.docxBUS 499, Week 6 Acquisition and Restructuring StrategiesSlide #.docx
BUS 499, Week 6 Acquisition and Restructuring StrategiesSlide #.docx
 
BUS 499, Week 4 Business-Level Strategy, Competitive Rivalry, and.docx
BUS 499, Week 4 Business-Level Strategy, Competitive Rivalry, and.docxBUS 499, Week 4 Business-Level Strategy, Competitive Rivalry, and.docx
BUS 499, Week 4 Business-Level Strategy, Competitive Rivalry, and.docx
 
BUS 437 Project Procurement Management Discussion QuestionsWe.docx
BUS 437 Project Procurement Management  Discussion QuestionsWe.docxBUS 437 Project Procurement Management  Discussion QuestionsWe.docx
BUS 437 Project Procurement Management Discussion QuestionsWe.docx
 
BUS 480.01HY Case Study Assignment Instructions .docx
BUS 480.01HY Case Study Assignment Instructions     .docxBUS 480.01HY Case Study Assignment Instructions     .docx
BUS 480.01HY Case Study Assignment Instructions .docx
 

Recently uploaded

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 

Recently uploaded (20)

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 

NIE2206 Electronic LogbookNamexxxStudent IDUxxxTe.docx

  • 1. NIE2206 Electronic Logbook Name: xxx Student ID: Uxxx Term: Winter/Spring (delete as appropriate) By submitting this logbook I confirm that I understand this is an individual assignment and that this work is entirely my own. Laboratory Practical 1 - XXX Laboratory Aim <Briefly paraphrase lab sheet here. Do not simply cut and paste the material> Exercise 1 - XXX Aim of exercise <Write a short aim for the exercise you are about to undertake, what are you going to do in this exercise and why are you doing it?> Procedure <Describe the tasks undertaken and evidence they were carried out by: Answering any questions posed in the lab sheet Providing code snippets to showing your solution to a coding exercise
  • 2. Describing your approach to the code design including noting any calculations Noting any problems e.g. debugging Note: You must show evidence that you have completed the set tasks in order to gain credit.> Remember: Context is the key here. It should be possible for a reader to understand from your logbook, without reference to the lab sheets: What you did. Why you did it. How you did it. Enter code listings using a fixed width font. Here I have used the Code style built into this template which uses the Consolas font as well as a compact line spacing to make code listings compact and easy to read. Insert evidence of calculations using the built-in Word equation editor or a Word plug-in like Mathtype. x=y/x + c become s + c Outcomes <Describe the outcome of the exercise. What did you observe? Was it successful? Any unusual results that may need explaining> Conclusion <Briefly summarise what was carried out. Be reflective - what did you learn through completing this exercise?> Exercise 2 - XXX Aim of exercise xxx Procedure xxx Outcomes xxx Conclusion xxx
  • 3. Exercise 3 - XXX Aim of exercise xxx Procedure xxx Outcomes xxx Conclusion xxx Laboratory Practical 2 - XXX Laboratory Aim Xxx Exercise 1 - XXX Aim of exercise xxx Procedure xxx Outcomes xxx Conclusion xxx Exercise 2 - XXX Aim of exercise xxx Procedure xxx Outcomes xxx Conclusion xxx 41 5 Lab 5 – Interrupts (part 1)
  • 4. 5.1 Aim This laboratory practical will introduce you to the concept of interrupts, which are an important feature of all modern computer systems, including microcontrollers. This lab will enable you to comprehend the purpose of interrupts, and the way in which the y can be utilised to optimise wasteful processes such as event polling loops. Consideration of the diffe rent hardware interrupts available on the PIC16F877A will be undertaken in this laboratory practical, and procedures will be developed for their proper configuration and servicing. 5.2 Learning Outcomes of the concept of interrupts and have knowledge of the hardware interrupts available on the PIC16F877A. Knowledge of how interrupts are implemented and serviced on t he PIC16F877A. Ability to develop code that utilises interrupts on the PIC16F87 7A to carry out useful tasks. 5.3 Background
  • 5. 5.3.1 Introduction to interrupts Interrupts are a feature of every modern computer system, whet her it be a complex multicore CPU in a desktop PC, or a simple 8 pin microcontroller in an electric to othbrush. Interrupts allow computer systems to react to events without using time wasteful processes such as polling loops. Examples of hardware events could be a logic state change on an external pin , a timer overflow, or the completion of an analogue‐to‐digital conversion. 5.3.2 Overview of instruction execution in a microcontroller During normal code execution, the CPU retrieves instructions from the program memory location stored in the program counter. Under normal operation, after an instruction has been executed, a program counter automatically increments and the instruction he ld in the next address in the program memory is retrieved, see figure 5‐1. Figure 5‐1 CPU instruction execution In this way instructions are executed in a linear step‐wise fashio n, one after another. The program counter drives the retrieval and execution of instructions from t
  • 6. he program memory. The program counter can also be loaded with specific memory addresses to ca use the CPU execution to jump (goto) to the start of another sequence of instructions. This happens wh en branches, loops or function calls need to be implemented. 42 Figure 5‐2 Action of a goto instruction on CPU instruction execution A subroutine (known as a function in C/C++) call also causes th e code to jump (goto) to the start of a specific set of instructions. The key feature of a subroutine is th at once its instructions have been executed, the CPU returns back to the program memory address it was at prior to the initial subroutine call. This allows the same subroutine instructions to be called fr om multiple points in the programme execution because instruction execution will always return to th e original memory location. To be able to provide this capability a storage entity called a stack is requir ed that can store the original memory
  • 7. address. A stack is generally several levels deep and is an exam ple of a last‐in‐first‐out (LIFO) data structure. Several addresses may be pushed onto the stack, whic h may then be popped back off in reverse order. This action is illustrated in figure 5‐3. Figure 5‐3 Pushing (top) and popping (bottom) addresses onto the stack When a subroutine is called, the current program memory addre ss on the program counter is pushed onto the stack. The program counter is then loaded with the pro gram memory address containing the start of the subroutine instructions. Once the subroutine instructions have been executed, the subroutine returns. At this point, the program memory address s tored in the popped from the stack and loaded onto the program counter. This action results in the CPU returning to the program memory location it was at prior to the function call. Figure 5‐4 and figur e 5‐5 present a graphical overview of this process. 43
  • 8. Figure 5‐4 Overview of subroutine execution Figure 5‐5 Detailed overview of subroutine execution including call and return As described earlier, the stack has several levels which means s everal addresses may pushed onto it. This allows the subroutines to be called from within subroutines in a nested structure. Each subroutine call results in the pushing of the current program counter addres s onto the stack. When the function returns, the previous address is popped back off again. In the PI C16F877A, the stack is only 8 levels deep so care must be taken not to nest too many subroutines (fu nctions) or you may encounter a stack overflow, which will result in undefined behaviour. The XC8 compiler will produce warning during the build process if it detects the potential for stack over flow. 5.3.3 The interrupt service routine The interrupt service routine (ISR) can be considered a special t ype of function that is automatically called when an interrupt event occurs. Figure 5‐6 shows the cycl e of actions that takes place when an
  • 9. interrupt event occurs. The sequence of events is precisely the s ame as that which occurs during a function call, except the interrupt vector is automatically loaded into the program counter by the hardware, which results in the ISR being called. 44 Figure 5‐6 Overview of interrupt servicing MCUs may have several interrupt vectors, each of which link to a different ISR. This allows the useful grouping of interrupts event types in more complex devices, for instance into different levels of importance or priority. The PIC16F877A is a relatively simple d evice having only 15 separate interrupt events. It has only one interrupt vector and thus only one possib le ISR. ISR code is often termed foreground code, which takes priority over the b ackground code that is executes continuously when there are no interrupts to service. 5.3.4 Interrupts on the PIC16F877A For an event to actually trigger an interrupt, the interrupt
  • 10. must first be enabled by setting configuration bits in the specific SFRs. In this laboratory practi cal we will be considering only three of the interrupts available on the PIC16F877A (see table 5‐1). Table 5‐1 The 3 interrupts to be studied in this laboratory practical Interrupt Event INTCON bits TMR0 overflow Timer0 overflow occurs TMR0IE, TMR0IF RB port change interrupt Logic level change on any of the pins RB7:4 (bits 4 to 7 of PORTB) RBIE, RBIF External interrupt Rising edge or falling edge on pin RB0. INTE, INTF These three interrupts can all be configured via the INTCON (in terrupt control) SFR. The INTCON SFR configuration bits are summarised in figure 5‐7. You will notice that there are two bits associated with each interrupt, an enable bit and a flag bit. In addition there are two further bits, GIE (Global Interrupt Enable) and PEIE (Peripheral Interrupt Enable). GIE acts as a ‘
  • 11. master switch’ and disables all interrupts when set to zero. PEIE enables the 12 remaining secondary inter rupts which we will study in a later laboratory. 45 Figure 5‐7 The INTCON register (adapted from the PIC16F877A datasheet) For an event to actually trigger an interrupt, the relevant interru pt enable bit in the INTCON SFR must be set. In addition the GIE bit must also be set. The interrupt fla gs should also be cleared as a matter of good practice during configuration so the MCU is in a known state. 5.3.5 Interrupt configuration in MPLAB X and the XC8 compiler Configuring interrupts can be done by writing the appropriate value to the INTCON register. For instance, in order to setup the Timer0 overflow register it is nec essary to set the GIE and TMR0IE registers. All other bits in the INTCON register should be cleare d as shown below.
  • 12. GIE PEIE TMR0IE INTE RBIE TMR0IF INTF RBIF 1 0 1 0 0 0 0 0 In this case, writing 0xA0 to the INTCON register configures th e interrupt as required. 5.3.6 Coding ISRs in the MPLAB X and the XC8 compiler The XC8 compiler uses the non‐standard, compiler specific key word interrupt to define the interrupt service routine (ISR). The ISR is defined in the same way as an y other C function but it must be of type void and contain no parameters. Furthermore a function prototy pe is not required, because the ISR is never called by the rest of the program, it is only called when a n interrupt occurs. The syntax for defining an interrupt is as follows: void interrupt functionName (void) { // ISR code goes here } 46 Because the PIC16F877A has only a single interrupt vector, the first job of the ISR is to check which
  • 13. interrupt has actually occurred and act accordingly. This is easil y done by simply checking the relevant interrupt flags as part of an if‐else‐if chain. In the following code, all relevant interrupt flags are checked. Code specific to each interrupt is only executed if the relevant interrupt flag is set. void interrupt myISR(void) { if(TMR0IF) { // Execute Timer0 overflow interrupt specific code INTCONbits.TMR0IF = 0; // Reset flag } else if(INTF) { // Execute RB0 external interrupt specific code INTCONbits.INTF = 0; // Reset flag } } Keep to this structure rigidly. It is essential that you remember t o reset the relevant interrupt flag after you have executed the interrupt specific code. If this is not done then you will inadvertently retrigger the interrupt when you return from the ISR and your code execu tion will get locked up. 5.3.7 Good practice when programming interrupts
  • 14. ISRs can be difficult to debug because they are hardware driven and respond to asynchronous events. As such special care should be taken when designing code that makes use of interrupts to ensure against undefined behaviour. enable the interrupts you want to use. Ensure interrupt flags are cleared when you enable the interrupt s. Keep ISRs short and simple. This makes them easier to debug a nd manage. It also reduces the likelihood of missing further interrupt events. Limit ISRs to simple tasks like incrementing counter variables or changing custom flags. These can then be a cted upon accordingly by the background code. if‐else‐if chain in your ISR should test interrupt flags in order of likelihood. The most commonly occurring interrupt should be at the top of the chain t o increase code efficiency. Use a strict if‐else‐if structure to test interrupt flags in your ISR . This reduces the likelihood of undefined behaviour in the event of an interrupt configuration e rror elsewhere.
  • 15. TIP! Remember when an event occurs, the relevant interrupt flag is set regardless of whether the interrupt is enabled or not. In the Timer0 laboratory practical w e used this facility detect a Timer0 overflow event by polling the TMR0IF flag. 47 5.4 Procedure 5.4.1 Exercise 1 – Implementing a Timer0 overflow interrupt Create a new project in the MPLAB X IDE, add an empty source file and populate it with the following code listing. // Filename: Lab5Ex1.c // Version: 1.0 // Date: <Insert current date> // Author: <Insert your name> // // Description: Implementing a Timer0 overflow interrupt #include <xc.h> // Required for all MPLAB XC8 source files void main(void) {
  • 16. TRISD = 0x00; // Set up ports PORTD = 0x00; INTCON = 0xA0; // SET GIE, TMR0IE // Set up Timer0 for 80 ms per overflow OPTION_REGbits.T0CS = 0; // Set clock source to internal (ti mer mode) OPTION_REGbits.PSA = 0; // Set prescaler to Timer 0 OPTION_REGbits.PS = 7; // Set prescaler bits to 111 for 1 :256 while(1); // Do nothing } // Interrupt service routine void interrupt myISR(void) { if(TMR0IF) // Timer0 overflow interrupt specific code { PORTD++; INTCONbits.TMR0IF = 0; // Reset flag } } Study the code listing carefully and build the project. Upload th e HEX file onto the PIC16f877A and observe the status of PORTD. Describe what is happening i n terms of the interaction between the main code, which is stuck in an infinite do‐nothing
  • 17. loop, and the ISR. 5.4.2 Exercise 2 – Creating precise delays using interrupts Create a new project and modify the code from Exercise 1 so th at the PORTD LEDs count up in binary at a rate of 1 Hz. In order to do this you will need to modify the ISR so that POR TD does not increment on every Timer0 overflow interrupt but rather after a specific number of i nterrupts. You can achieve this by implementing a counter to keep track of the total number of interrupts that have occurred. You will also need to preload Timer0 at the appropriat e point in the ISR. 48 If necessary, review the timer calculations you used to produce a one second delay in section 3.4.3 to allow you choose a suitable Timer0 preload value deter mine how many interrupts to count. Do not simply place a for loop in the ISR to create the delay, the background code should continue to execute between ISR calls.
  • 18. Write down a high‐level flow chart showing the operation of the ISR ONLY. 5.4.3 Exercise 3 – Adding background code functionality Create a new project and modify the code you developed in sect ion 5.4.2 so that instead of the main() function doing nothing, it performs a useful task. In this case that task is to toggle bit 7 of PORTB every 250 ms. This may be achieved by XORing the relevant bit with 1, so in this case, PORTB = PORTB ^ 0x80; or alternatively, in a more compact notation, PORTB ^= 0x80; You should create the required delay using the __delay_ms() ma cro, review section 2.4.1 to see the correct useage. Do not forget to insert the following stat ement in your code listing, near the top of the file, #define _XTAL_FREQ 3276800 This defines the MCU oscillator frequency which is needed by t he __delay_ms() function to
  • 19. calculate the delay correctly. Failure to include it will lead to a compilation error. Write down an XOR truth table and describe how the XOR oper ation toggles bit 7 of PORTB. 5.4.4 Exercise 4 – Servicing multiple interrupts Create a new project and modify the code in you developed in s ection 5.4.3 to add a reset button functionality. When SW0 on the E‐block switchboard co nnected to PORTB is pressed, then the binary count value should reset back to zero. This functionality should be implemented using the RB0/INT ex ternal interrupt flag to detect a button press on SW0 of the PORTB switchboard. Take care to set up the TRISB register so the PORTB directions are correct, for the RB0/INT external interrupt to operate RB0 must be an input. You will als o need to modify the INTCON register and the ISR to achieve this goal. 5.5 Further reading More useful information on implementing ISRs can be found in section 5.9 of the MPLAB XC8 C
  • 20. Compiler User Guide available on Unilearn or at, http://ww1.microchip.com/downloads/en/DeviceDoc/50002053 F.pdf More MCU specific information on interrupts can be found in se ction 8 of the PICmicro Mid‐Range MCU Family Reference Manual available on Unilearn or at, 49 http://ww1.microchip.com/downloads/en/DeviceDoc/33023a.pdf 32 4 Lab 4 – Timer0 module 4.1 Aim This laboratory practical will introduce you to the Timer0 modu le which is one of three timer/counter peripherals located on the PIC16F877A MCU. Timer/counter modules allow the creation of precise and deterministic timing intervals which is essential in many applications e.g. frequency generation/measurement, timekeeping, control systems, commun ications. This laboratory practical
  • 21. will focus on the proper configuration and usage of the Timer0 module in timer mode only. 4.2 Learning Outcomes Understand the structure of the Timer0 module on the PIC16F87 7A Be able to configure the Timer0 module using the appropriate sp ecial function registers Be able to develop projects to utilise the Timer0 module in a ra nge of applications. 4.3 Background 4.3.1 Counter/Timers The only practical difference between a counter and a timer is the nature of the source. A counter simply increments a stored ‘count’ value when a logic state cha nge (either a rising or falling edge) is received at its input. To operate a counter as a timer, a synchron ous pulse train (clock) of a known frequency is applied to the input. Figure 4‐1 shows a generic re presentation of a counter configured as a timer. The current count value can be read from the counter register, and the register can also be written to or ‘preloaded’. Figure 4‐1 Generic representation of a hardware timer module
  • 22. If the frequency of the synchronous pulse train, f is known then the elapsed time, T may be determined from number of counts, N recorded by the timer as follows, NT f 4.3.2 PIC16F877A Timer0 module The Timer0 module on the PIC16F877A MCU is an 8 bit pre‐sca lable timer/counter. In timer mode, the TMR0 special function register (SFR) is automatically incremen ted on every instruction clock cycle. In counter mode, the TMR0 SFR is incremented either on rising or on falling edge (configuration dependant) of the external pin RA4/T0CKL. In this laboratory p ractical we will only be considering the use of Timer0 in timer mode. 33 The 8 bit Timer0 module on board the PIC16F877A can store independent values from 0‐ 255. The current count value is stored in the TMR0 SFR may be read at any time without affecting the operation of the Timer0 module. It may also written to (preload ed) by writing the appropriate value to the TMR0 SFR. When the Timer0 module count value reaches its maximum valu
  • 23. e (255), the counter overflows back to zero and continues counting. This timer overflow results in the setting of a bit (TMR0IF) in the INTCON SFR. Figure 4‐2 show the structure of the INTCON SF R which we will be looking at in more detail in future laboratory practicals. For the moment just reme mber that when a Timer0 overflow occurs then the TMR0IF bit is SET. Figure 4‐2 The INTCON register A single bit which signifies an occurrence of an event, in this ca se a Timer0 overflow, is called a flag. We can detect when the overflow Timer0 has occurred by regula rly checking the status of the TMR0IF bit (flag) in a process known as polling. By using polling in con junction with loops it is possible to create accurate delays. Timer0 receives its synchronous pulse train (clock) at the instruction cycle rate of the PIC16F877A MCU, which is one quarter of the frequency of the quartz crysta l oscillator used to clock the MCU. For the 3.2768 MHz crystal oscillators used on the E‐block develop ment systems, this yields an instruction cycle rate, CYf of 63.2768 10 819.2 kHz 4CY The instruction cycle period, is then simply the reciprocal of the instruction cycle rate,
  • 24. CYf . Along with the basic operation as a timer/counter, the Timer0 m odule also has a prescaler associated with it. A prescaler is a logical device that reduced the frequency of the incoming clock by integer division. The prescaler may be set to divide down the incoming clock by a range of preconfigured ratios from 1:2 to 1:256. For example, setting the Timer0 prescaler to 1:128 will increme nt the timer at a now‐reduced rate of It is important that the prescaler is configured correctly so that the required timings are obtained for the application in question. 4.3.3 Timer0 module configuration overview A schematic representation of the timer module is shown in figure 4‐3 which shows the various elements which need to be correctly configured including the pr ogrammable prescaler module and two multiplexers, which select the clock source and enable the p rescaler respectively. 34 Figure 4‐3 Schematic of the Timer0 module (adapted from PIC16F877A MCU datasheet)
  • 25. The Timer0 module is configured using the OPTION_REG SFR which contains configuration bits to set the clock source, prescaler value etc. Figure 4‐4 shows the location of the configuring bits in the OPTION_REG SFR. Note carefully at how the bit names relate t o the schematic elements in figure 4‐3. Figure 4‐4 The OPTION_REG SFR configuration bits (adapted from PIC16F877A datasheet) Only bits 0 to 5 of the OPTION_REG SFR are needed to config ure the Timer0 module, bits RBPU and INTEDG are used other peripheral configuration purposes that we need not concern ourselves with for the moment. In order to use the Timer0 module as in timer m ode the properties of the relevant configuration bits must be set up as shown in Table 4‐1. Table 4‐1 Correct OPTION_REG configuration of using Timer0 in timer mode Bit Name Bit location in OPTION_REG MPLAB XC8 syntax Configuration requirements T0CS 5 INTCONbits.TOCS Set to 0 to use Timer0 in timer mode T0SE 4 INTCONbits.TOSE No effect in timer mode (don’t care state) PSA 3 INTCONbits.PSA Set to 0 in timer mode to utilise the prescaler
  • 26. PS2:0 2:0 INTCONbits.PS Define as required by application The divide down value of the prescaler is selected by setting the three bits, PS2:0 according to table 4‐2, 8 discrete options are available. 35 Table 4‐2 Timer0 prescaler configuration PS2, PS1, PS0 Value TMR0 Rate 000 0 1:2 001 1 1:4 010 2 1:8 011 3 1:16 100 4 1:32 101 5 1:64 110 6 1:128 111 7 1:256 Note that a number of related bits in a SFR (in this case PS2:0) are termed a ‘bit field’. To summarise, the bitwise configuration of the OPTION_REG S FR (see figure 4‐4) for operation of timer 0 in timer mode may be considered as follows: OPTION_REG = XX0X 0UUU where X = a don’t care state and U = a user defined state. 4.3.4 Calculation of timer counts and intervals
  • 27. The prescaler and instruction clock rate are crucial parameters i n determining/creating delays using the Timer0 module. The total delay created by a given number o f Timer0 counts is 4 prescaler 0countdelay osc TMR f where OSCf is the frequency of the quartz crystal used to clock the PIC16F8 77A. This formula takes into account the prescaler ratio and the fact that the instruction clock rate is a quarter of the crystal frequency (see section 4.3.2). Rearranging the above equation in order to determine the number of TMR0 counts to create a specific delay yields, delay0count 4 prescaler Remember that the maximum number of counts the 8 bit Timer0
  • 28. module can store before overflowing is 256. For example, if a 10 ms delay is required, with the prescaler div ide down ratio set to 1:256, then the required number of TMR0 counts is as follows. 3 6delay 10 10 3.2768 100count 32 4 prescaler 4 256 oscfTMR When 32 counts of the Timer0 module have occurred, we know t hat 10 ms have elapsed. We can use this information to design a delay loops. 36 4.3.5 Timer0 configuration procedure With the information shown in the previous section it is possibl e to derive a configuration procedure for Timer0 as follows: TOCS = 0 to enable timer mode
  • 29. If using the prescaler, set PSA = 0. If not set PSA = 1 and skip t he next step. Calculate required prescaler divide down ratio and write the app ropriate 3 bit value to the PS bit field. 4.4 Procedure 4.4.1 Exercise 1 – Creating a simple delay using the Timer0 module Create a new project in the MPLAB X IDE, create an empty sou rce file, and populate it with the following code listing. // Filename: Lab4Ex1.c // Version: 1.0 // Date: <Insert current date> // Author: <Insert your name> // // Description: Simple demonstration of a timer delay #include <xc.h> // Required for all MPLAB XC8 source files void main(void) { unsigned char preload = 0x00; // TMR0 preload variable // PORTD setup TRISD = 0x00; // Set PORTD all outputs PORTD = 0x00; // Clear PORTD //Timer0 setup
  • 30. OPTION_REGbits.T0CS = 0; // Set clock source to internal (timer mode) OPTION_REGbits.PSA = 0; // Set prescaler to Timer 0 OPTION_REGbits.PS = 7; // Set prescaler bit field to 111 for 1:256 while(1) // Infinite loop { TMR0 = preload; // Preload timer0 while(!INTCONbits.TMR0IF); // Delay loop: Wait until TMR0 overflows INTCONbits.TMR0IF = 0; // Reset overflow flag, TM R0IF PORTD++; // Increment PORTD } } Build the project and upload the HEX file onto the PIC16F877A MCU. Study the code listing carefully and observe what is happening t o the LEDs on PORTD. You should see PORTD incrementing from 0 to 255 in binary. Sketc h a flow chart in your logbook describing the sequence of events occurring in the executing co de. Calculate the length of the implemented delay using the appropr iate formulae from section 4.3.4. Keep in mind that TMR0 is preloaded with 0x00 and the d elay loop repeats until TMR0
  • 31. 37 overflows from 0xFF to 0x00 i.e. the loop condition becomes F ALSE. In the general case for the code listing above: Using a stopwatch, time how long it takes for the LEDs on POR TD to count up to 256 i.e. turn from all OFF to all ON. Calculate the delay time for one individ ual count by dividing the total time by 256. Compare you calculated result from the empirical result obtaine d using a stopwatch. Does it agree, taking into account any possible experimental error? What happens if you increase the value of the preload variable i n the code listing above? 4.4.2 Exercise 2 – Creating longer delays In the previous exercise you created the longest possible delay u sing Timer0 i.e. with the prescaler set to a maximum divide down ratio of 1:256, and the full count of TMR0 used i.e. from zero (0x00) until it overflowed. However, there are many occasions when a longe r delay than is possible using a single timer overflow is required. One possible approach to this is to cascade several shorter delays, in a
  • 32. loop, to create a longer overall delay. Create a new project in the MPLAB X IDE, add an empty source file and add the following code listing to it. // Filename: Lab4Ex2.c // Version: 1.0 // Date: <Insert current date> // Author: <Insert your name> // // Description: Looping of a short timer delay to create a longer one #include <xc.h> // Required for all MPLAB XC8 source files void main(void) { unsigned char preload = 192; // TMR0 preload variable unsigned char i; // Loop index variable // PORTD setup TRISD = 0x00; // Set PORTD all outputs PORTD = 0x00; // Clear PORTD //Timer0 setup OPTION_REGbits.T0CS = 0; // Set clock source to internal (timer mode) OPTION_REGbits.PSA = 0; // Set prescaler to Timer 0 TIP! When a Timer0 overflow occurs and the TMR0IF bit is SET and remains in that state until it is manually RESET in software. This can be done using the follow ing syntax:
  • 33. INTCONbits.TMR0IF = 0; It is important to remember to do this when you are polling for t imer overflows. 38 OPTION_REGbits.PS = 7; // Set prescaler bits to 111 for 1:256 while(1) // Infinite loop { for(i=0;i<8;i++) // Loop to cascade several short delay s together { TMR0 = preload; // Preload timer0 while(!INTCONbits.TMR0IF); // Delay loop: Wait unt il TMR0 overflows INTCONbits.TMR0IF = 0; // Reset overflow flag, TMR0IF } PORTD++; // Increment PORTD } } Calculate the length of the delay implemented using bearing in mind that the value of the preload variable is now set to 192 and the shorter delay loop is now repeated 8 times. Using a stopwatch, time how long it takes for the LEDs on POR TD to count up to 256 i.e. turn
  • 34. from all OFF to all ON. Calculate the delay time for one individ ual count by dividing the total time by 256. Compare you calculated result from the empirical result obtaine d using a stopwatch. Does it agree, taking into account any possible experimental error? Modify the code to create a one second delay. You should appro ach this by adjusting the preload value so that the short delay loop has a length that divid es exactly into one second. This short delay should then be repeated the required number of times to produce a one second delay. Confirm your results using a stopwatch. 4.4.3 Exercise 3 – Creating a one second delay function A delay is a useful and often used action in any embedded system. Having gone to the effort of developing a one second delay it would make sense to package t he code into a function so that it could be easily reused whenever required. The following code listing shows one possible template for impl ementing the one second delay as a function call one_sec_delay(). The operation of this code is exactly the same as that produced in exercise 3, the only difference is that all the code that had previously been required to create th e delay has now been packaged inside a function which is called f
  • 35. rom the main() function. Create a project and enter the following listing. You will need to replace the two ‘??’ symbols in the listing below with the values you derived in the previous exercise in or der for it to build successfully. // Filename: Lab4Ex3.c // Version: 1.0 // Date: <Insert current date> // Author: <Insert your name> // // Description: Implementing a Timer0 delay function #include <xc.h> // Required for all MPLAB XC8 source files 39 void one_sec_delay (void); // Function prototype void main(void) { // PORTD setup TRISD = 0x00; // Set PORTD all outputs PORTD = 0x00; // Clear PORTD while(1) // Infinite loop { one_sec_delay(); // Call delay function PORTD++; // Increment PORTD
  • 36. } } void one_sec_delay (void) { unsigned char preload = ??; // TMR0 preload variable (deri ved from Ex2) unsigned char i; // Loop index variable //Timer0 setup OPTION_REGbits.T0CS = 0; // Set clock source to internal (timer mode) OPTION_REGbits.PSA = 0; // Set prescaler to Timer 0 OPTION_REGbits.PS = 7; // Set prescaler bits to 111 for 1:256 for(i=0;i<??;i++) // Loop to cascade several short delays together // Number of loops derived from Ex2 { TMR0 = preload; // Preload timer0 while(!INTCONbits.TMR0IF); // Delay loop: Wait until TMR0 overflows INTCONbits.TMR0IF = 0; // Reset overflow flag, TM R0IF } } Build the project and validate that the operation is as anticipate d. 4.4.4 Exercise 4 – Creating a variable delay function In this exercise we will develop a generic variable delay functio
  • 37. n that will allow the implementation of any user defined delay of an integer number of seconds Create a new project based upon the code developed in exercise 3. Modify the fixed one second delay function, one_sec_delay() de veloped in exercise 3 so that it becomes a generic delay function taking the form, void delay(unsigned char delay_length) where the parameter delay_length sets the length of the delay i mplemented by the function. The parameter will need to modify the number of cascaded short delays to generate the variable delay. 4.5 Further reading Microchip MPLAB X Timer0 (Part 1) tutorial sheet. Note the code listings show is not directly compatible with the XC8 compiler, but the information about co nfiguration is still relevant.