0% found this document useful (0 votes)
10 views293 pages

Sensors and Embedded Systems Course Overview

Uploaded by

omar saad
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views293 pages

Sensors and Embedded Systems Course Overview

Uploaded by

omar saad
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Sensors and

Embedded Systems - 1
Module Introduction

Sensors and Embedded Systems – David Wilson 1


My Details

Module Leader: Dave Wilson


[Link]@[Link]
MS226
x3202

Sensors and Embedded Systems – David Wilson 2


Module Learning Outcomes

1. Design, build and program a complete embedded system including


selecting the appropriate sensor, signal conditioning and data
acquisition techniques to meet specific applications.

2. Analyse and critically evaluate theoretically and practically the


performance of commonly used embedded control systems.

3. Analyse and assess theoretical and practical issues relevant to the


design and application of sensors and embedded systems
Sensors and Embedded Systems – David Wilson 3
Module Assessment CW (50%)
Component 1: COURSEWORK 50%

• A practical and written assignment, normally done as a


team, involving the development of a system to achieve a
given task.
• A practical demonstration of the final system will be made
(both in hardware and Proteus), accompanied by a written
report.

Assesses Learning Outcome: 1

Sensors and Embedded Systems – David Wilson 4


Module Assessment Exam (50%)

Component 2: Exam 50%


A 2-hour time-constrained examination.
Assesses Learning Outcomes: 2 and 3

Sensors and Embedded Systems – David Wilson 5


Lecture Plan(1)
Lecture Lab / Tutorial
1 Module Intro/ PIC / basic code structure PIC in Proteus (Group A)
2 More C Programming PIC in Proteus (Group B)
3 Interfacing with IO Keypad – 7 segment display (Group A)
4 Timers and Counters Keypad – 7 segment display (Group B)
5 PWM – (software and hardware Timers and PWM (Group A)
6 Actuators (servo and stepper) Timers and PWM (Group A)
7 Interfacing with an lcd LCD (Group A)
8 DAC LCD (Group B)
9 ADC (resistive sensors) ADC / servo position (Group A)
10 Interrupts / Priorities ADC / servo position (Group B)
11 Serial Communications I2C and SPI (Group A)
12 Writing to onboard eeprom I2C and SPI (Group B)

Sensors and Embedded Systems – David Wilson 6


Lecture Plan(2)
Lecture Lab / Tutorial
13 Effective Teamwork - the group project. Group Project (Group A)
14 Wireless Communications +IoT Group Project (Group B)
15 Reliability Group Project (Group A)
16 CAN Bus Group Project (Group B)
17 Sensors and Transducers Group Project (Group A)
18 Sensor errors / uncertainty Group Project (Group B)
19 Standards and Calibration Group Project (Group A)
20 RTOS, Realtime Clock Group Project (Group B)
21 Designing for Low Power Group Project (Group A)
22 Module Summary / Catchup Group Project (Group B)
23 Demo Group Project (Group B) Demo Group Project (Group A)
24 Exam Revision Reflections (All)
Sensors and Embedded Systems – David Wilson 7
The Assignment.

Sensors and Embedded Systems – David Wilson 8


Hardware – MplabX and Dev Board

Sensors and Embedded Systems – David Wilson 9


Software – Proteus (1)

Sensors and Embedded Systems – David Wilson 10


Software – Proteus (2)

Sensors and Embedded Systems – David Wilson 11


Microcontroller Recap
Microcontrollers
C Programming

Sensors and Embedded Systems – David Wilson 12


Microprocessor vs Microcontroller.

A microcontroller =
microprocessor core +
memory + peripherals
+ others

Sensors and Embedded Systems – David Wilson 13


Data and Program Memory

12-bit register address Data


Program 21-bit program address PIC18F Memory
Memory CPU &
16-bit instruction bus 8-bit data bus SFR’s

Harvard style of memory structure with separate


pathways for program and data memory spaces

Sensors and Embedded Systems – David Wilson 14


Program Memory

Sensors and Embedded Systems – David Wilson 15


Interfacing with Peripherals - SFR

Control SFR(s)
Microcontroller Peripheral "Outside
Core World"
Data Transfer SFR(s)

Interrupts
Interrupt(s)

· microcontroller peripherals can be configured in software to operate in a


number of different modes,
· to do this certain control data must be sent to them,
· these needs are met by means of dedicated, memory - mapped registers,
sometimes called Special Function Registers (SFRs),

Sensors and Embedded Systems – David Wilson 16


A Basic Program Structure

Includes clock source and


Initialise whether a port is input or output
PIC as well as setting up on board
peripherals such as ADC etc
Declare
C is case sensitive
Variables

Main
Loop Main application code goes here

Sensors and Embedded Systems – David Wilson 17


A Sample Program in MPLabX IDE

Comments

Space

Declaration

Statements

Sensors and Embedded Systems – David Wilson 18


Declarations.

All variables and functions in C must be declared before they can be


used. From the example code
Type of
Name
data

unsigned char counter; Terminated with a semicolon

In simple programs declarations tend to appear as one of the first


things in the program, which seems to make sense.

Sensors and Embedded Systems – David Wilson 19


C Data Types and Storage.

• Variables within a C program have four attributes:


• name, type, value, storage location.
• The compiler can determine the amount of memory needed to
store the variable. Its value can then, if needed, be initialised.
• Data names must start with a letter.
• When writing numbers in a program, the default radix for integers
is decimal, with no leading 0 (zero). Hexadecimal numbers are
prefixed with 0x. Binary 0b

Sensors and Embedded Systems – David Wilson 20


Data Types in C.

Only really four basic types: char, int, float and double
Type Storage size Value range (decimal)
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
float 4 bytes 1.2E-38 to 3.4E+38
double 8 bytes 2.3E-308 to 1.7E+308

Sensors and Embedded Systems – David Wilson 21


Characters (Char).

Roman alphabet, punctuation, digits, and other symbols:

• Encoded within one byte (256 possible symbols)

• ASCII encoding (useful for sending data to lcd)

• Can be used as ‘just numbers’

Sensors and Embedded Systems – David Wilson 22


Number Representation.

Decimal 0 63 83
Binary 0b00000000 0b00111111 0b01010011
Hexadecimal 0x00 0x3F 0x53

Sensors and Embedded Systems – David Wilson 23


Signed vs Unsigned Integer.
Binary Hex Unsigned 2’s Comp.
0000 0 0 0
0001 1 1 1
0010 2 2 2
0011 3 3 3
0100 4 4 4
0101 5 5 5
0110 6 6 6
0111 7 7 7
1000 8 8 -8
1001 9 9 -7
1010 A 10 -6
1011 B 11 -5
1100 C 12 -4
1101 D 13 -3
1110 E 14 -2
1111 F 15 -1

Negative Numbers represented using 2’s complement


Sensors and Embedded Systems – David Wilson 24
Statements (1).
Where all the action of the program takes place. Every statement
which is not a block (see later) ends with a semicolon.

The most common type of statement is the expression statement,


which includes mathematical manipulations. Again, from the
example code:

TRISB = 0; Set all bits of PORTB as output

counter = 1; Set counter to equal 1

Executed in the sequence they appear in the program, except


where program branches take place.
Sensors and Embedded Systems – David Wilson 25
Statements (2).
Where all the action of the program takes place. Every statement
which is not a block (see later) ends with a semicolon.

The most common type of statement is the expression statement,


which includes mathematical manipulations. Again, from the
example code:

TRISB = 0; Not portable across architectures

counter = 1; Portable across architectures

Executed in the sequence they appear in the program, except


where program branches take place.
Sensors and Embedded Systems – David Wilson 26
# Include Directive

Sometimes variables are declared in a separate file called a header file


eg xc.h. These files are associated with a program through
the #include directive.
Header File is in Compiler Path
#include <filename.h>
Header File is in Project Directory
#include "filename.h“
Header File is in another Specific Location
#include "C:\path\to\filename.h"
Sensors and Embedded Systems – David Wilson 27
Configuration Bits
• Configuration bits are
• Programmed into the PIC MCU with the application and
read on start up
• They are not executable code as their address is not
accessible by the Program Counter (PC).
• Cannot be modified during run-time.
Examples include:
#pragma config FOSC = HSMP // HS oscillator - medium power
#pragma config BOREN = OFF // Brownout detect off
#pragma config WDTEN = OFF // Watch dog timer off
#pragma config LVP = OFF // Low voltage programming off
#pragma config PBADEN =Sensors
OFF // Port B all digital I/O
and Embedded Systems – David Wilson 28
Comments.

Comments start with /*, and end with */. In this form they can
run over more than one line.
/******************************************
Example 1. Introductory Example of C Programming
******************************************/
Or for a single line use a double slash, //. This needs no
terminating symbol.
counter = counter + 1; //Increment counter
It’s good practice to use plenty of comments.
They do not impact on code size!
Sensors and Embedded Systems – David Wilson 29
Keywords.

C has 32 reserved "keywords". These are used for program flow control,
and declaration of data types. They cannot be used by the programmer
as names.
Example C Keywords
break double goto return switch
char else if short unsigned
const float int signed void
do for long static while
Sensors and Embedded Systems – David Wilson 30
Functions.

C programs are structured from functions. Every program must have at


least one function, called main. The program is contained within it.
Functions are used to contain an identifiable program action which
may be required more than once. Any function may call another.
Main program

call Function

return

Sensors and Embedded Systems – David Wilson 31


Function Declarations.

A function must be declared before it may be used. The function's


declaration must occur before main().
void initialise (void); Function declared
void main (void)
{
initialise(); Function called
while (1)
{
Do Stuff
}
}
Sensors and Embedded Systems – David Wilson 32
Function Arguments.

Data elements, called arguments, can be passed to a function but must be


declared in advance.
Only one return variable is allowed, also declared.
The data passed to the variable is a copy of the original. Therefore, the
function does not itself modify the value of the variable named

Return Function Argument(s)


Type Name

int multiply (int a,b);


Sensors and Embedded Systems – David Wilson 33
Example Function.

int multiply (int a,b);


void main (void)
{
i=2;
j=3;
result=multiply(i,j)
}
int multiply (int a,b)
{
return (a*b);
}
Sensors and Embedded Systems – David Wilson 34
Program Flow

All programs contain looping ReadActual


Temperature TA

and branching, known as


program flow. The keywords
ReadDemand
Temperature TD

shown below are associated Yes No


TA >TD?
with program flow. Activate Switchoff
Compressor Compressor

if while
if...else No
TA >>TD?
do...while Yes

else...if for Activate


Alarm

switch break
Sensors and Embedded Systems – David Wilson 35
While

The while keyword allows a statement, or block of statements, to be


executed repeatedly, as long as a particular condition holds true.

while (conditional expression) statement;

This will cause the statement to be executed repeatedly, as long as the


conditional expression evaluates ‘true’ If it is no longer true, then
program execution after the loop proceeds.

Sensors and Embedded Systems – David Wilson 36


While – A Continuous Loop

Continuous loop is forced by putting ‘1’ for the conditional expression.

while (1)
{
PORTB = counter; //Move value to Port B
counter = counter + 1;
}

The two statements which fall within the while braces thus repeat
indefinitely.
Sensors and Embedded Systems – David Wilson 37
If Statement.

if (PORTBbits.RB4 == 0) // Test right bump switch


PORTCbits.RC6 = 1; // Right led on
Next line of code will be executed regardless
.
.
.
if (PORTBbits.RB5 == 0) // Test left bump switch
PORTCbits.RC5 = 1; // Left led on

Sensors and Embedded Systems – David Wilson 38


Code Blocks

Declarations and Statements can be grouped together into blocks. A


block is contained within braces (curly brackets).
if (PORTBbits.RB4 == 0) // Test switch connected to RB4
{
PORTCbits.RC6 = 1; // Right led on
PORTCbits.RC1 = 1; // Turn Buzzer on
}
It is good practice to indent them such that matching pairs fall directly
below each other to help keep track of these code blocks.
Sensors and Embedded Systems – David Wilson 39
If – Else Statement.

• An else clause can be added to an if statement to make an if-else


statement
if ( condition )
statement1;
else
statement2;
• If the condition is true, statement1 is executed; if the condition is
false, statement2 is executed
• One or the other will be executed, but not both

Sensors and Embedded Systems – David Wilson 40


Some Common Mistakes
= vs ==
if (x == 4) evaluates to true (or 1) if x is equal to four.
But…
if (x = 4) is taken to be true because the expression assigns the
value 4 to x (x = 4) and then executes the following code block.
Missing ;
Misspelling a variable / function name
Not creating appropriate code blocks

Sensors and Embedded Systems – David Wilson 41


Next Lecture
More C Coding

End of Lecture Note


Sensors and Embedded Systems – David Wilson 42
Sensors and
Embedded Systems - 2
C Programming
Pseudocode and flowcharts

Sensors and Embedded Systems – David Wilson 43


One Way to Write Code

Just sit down and smash it out in one go

[Link]

Sensors and Embedded Systems – David Wilson 44


A Better Way

• First produce a general algorithm (one can use pseudocode)

• Pseudocode is an artificial and informal language that helps


programmers develop algorithms. Pseudocode is very similar to
everyday English.

• Refine the algorithm successively to get step by step detailed


algorithm that is very close to a computer language.

Sensors and Embedded Systems – David Wilson 45


Algorithms And Flowcharts

• A typical programming task can be divided into two phases:


• Problem solving phase
• produce an ordered sequence of steps that describe solution of
problem
• this sequence of steps is called an algorithm
• Implementation phase
• implement the program in some programming language

Sensors and Embedded Systems – David Wilson 46


Program Flow

All programs contain looping ReadActual


Temperature TA

and branching, known as


program flow. The keywords
ReadDemand
Temperature TD

shown below are associated Yes No


TA >TD?
with program flow. Activate Switchoff
Compressor Compressor

if while
if...else No
TA >>TD?
do...while Yes

else...if for Activate


Alarm

switch break
Sensors and Embedded Systems – David Wilson 47
Example 1.

• Write an algorithm to determine a student’s final grade and indicate


whether it is passing or failing.

• The final grade is calculated as the average of four marks.


• The student passes if the average mark is greater than 50

Sensors and Embedded Systems – David Wilson 48


Example 1 – Pseudocode.

• Start
• Input a set of 4 marks
• Calculate their average by summing and dividing by 4
• if average is below 50
• Print “FAIL”
• else
• Print “PASS”
• End

Sensors and Embedded Systems – David Wilson 49


Example 1 – Detailed Algorithm.

Step 1: Input M1,M2,M3,M4

Step 2: GRADE =(M1+M2+M3+M4)/4


Step 3: if (GRADE <50) then
Student Fails
else
Student Passes
endif
Sensors and Embedded Systems – David Wilson 50
Pseudocode Good Practice

• Pseudocode enclosed by START and STOP or similar delimiters.

• Pseudocode should be concise so ignore unnecessary details.

• Generally used keywords are capitalized while preparing pseudocode.

Sensors and Embedded Systems – David Wilson 51


Advantages of Pseudocode

• It allows the designer to focus on main logic without being distracted by


programming languages syntax.

• Since it is language independent, it can be translated to any computer


language code.

• It allows designer to express logic in plain natural language.

• Easier to modify.
Sensors and Embedded Systems – David Wilson 52
Disadvantages of Pseudocode

• There are no accepted standards for writing pseudocodes and


designer use their own style while writing pseudocodes.

• Pseudocode cannot be compiled and executed so its correctness


cannot be verified by using computers.

Sensors and Embedded Systems – David Wilson 53


The Flowchart

• A graphical representation.

• Shows the sequence of instructions in a single program or subroutine.


Emphasizes individual steps and their interconnections

• Help visualize what is going on and thereby help the people to


understand a process, and perhaps also find flaws, bottlenecks, and
other less-obvious features within it

Sensors and Embedded Systems – David Wilson 54


Flowchart Symbols

Different symbols are used for different states in flowchart.


Denotes the beginning or end of a program

Denotes an input

Denotes a process to be carried out e.g. addition,


subtraction
Denotes a decision is to be made. The program should
then continue along one of two routes ( True or False).
Denotes the direction of flow within the program.
Sensors and Embedded Systems – David Wilson 55
Example 1 – Flowchart.

START

Input
Step 1: Input M1,M2,M3,M4
M1,M2,M3,M4 Step 2: GRADE =(M1+M2+M3+M4)/4
GRADE=(M1+M2+M3+M4)/4 Step 3: if (GRADE <50) then
Student Fails
N GRADE Y else
<50
Student Passes
Student Passes Student Fails endif

STOP

Sensors and Embedded Systems – David Wilson 56


Example 2

• Write an algorithm and draw a flowchart that will calculate the roots
of a quadratic equation 𝑎 𝑥 2 +𝑏𝑥 +𝑐=0

−𝑏 ± √ 𝑏 − 4 𝑎𝑐 2
𝑥=
2𝑎

• Hint: d = sqrt (𝑏 2 − 4 𝑎𝑐), and the roots are:


x1 = (–b + d)/2a and x2 = (–b – d)/2a

Sensors and Embedded Systems – David Wilson 57


Example 2 - Pseudocode

• Start
• Input the coefficients (a, b, c) of the quadratic equation
• Calculate d
• Calculate x1
• Calculate x2
• End

Sensors and Embedded Systems – David Wilson 58


Example 2 - Flowchart

START
Start
Input a, b, c Input the coefficients (a, b, c)
Calculate d
d = sqrt(b x b – 4 x a x c)
Calculate x1
x1 =(–b + d) / (2 x a) Calculate x2
X2 = (–b – d) / (2 x a)
End

STOP

Sensors and Embedded Systems – David Wilson 59


Example 3

Sensors and Embedded Systems – David Wilson 60


A Basic Program Structure

Includes clock source and


Initialise whether a port is input or output
PIC as well as setting up on board
peripherals such as ADC etc
Declare
C is case sensitive
Variables

Main
Loop Main application code goes here

Sensors and Embedded Systems – David Wilson 61


Example 3 – PIC Initialise

External crystal
WDT

Sensors and Embedded Systems – David Wilson 62


Example 3 – Peripheral Initialise

ADC
I/O
LCD

CCP SPI LED


Sensors and Embedded Systems – David Wilson 63
Example 3 Flowchart (Basic)

Initialise Includes clock source and


PIC whether a port is input or output

Setup
ADC, SPI, CCP,LCD
Peripherals

Main
Loop Read sensors, update displays

Sensors and Embedded Systems – David Wilson 64


Lecture Plan(1)

Lecture Lab / Tutorial


1 Module Intro/ PIC / basic code structure
PIC in Proteus
2 More C Programming
3 Interfacing with IO
Keypad – seven segment display
4 Timers and Counters
5 PWM – (software and hardware
Timers and PWM
6 Actuators (servo and stepper)
7 Interfacing with an lcd
LCD
8 DAC
9 ADC (resistive sensors)
ADC / servo position
10 Writing to onboard eprom
11 Serial Communications
I2C and SPI
12 Wireless communications +IoT (USART)

Sensors and Embedded Systems – David Wilson 65


Sensors and
Embedded Systems - 4
Timers and Counters

Sensors and Embedded Systems – David Wilson 66


Counter Basics 1

A digital counter is made from a series of interconnected flip-flops/bistables.

An n-bit Counter can count from 0 to (2n-1).


Sensors and Embedded Systems – David Wilson 67
Counter Basics 1 - Example

What is the highest number (in Decimal and Hexadecimal) that the following
counters can count up to?
Remember 2n-1 is the counter range

• 4-bit 24-1=1610-110=1510 or F16


• 8-bit 28-1=25610-110=25510 or FF16
• 10-bit 210-1=102310 or 3FF16
• 12-bit 212-1=409510 or FFF16

Sensors and Embedded Systems – David Wilson 68


Counter Basics 2

• Further features can easily be designed into the counter, e.g. outputs can
be cleared to zero or be pre-loaded with a certain number.

Sensors and Embedded Systems – David Wilson 69


The Counter as a Timer

• If the incoming clock pulses are regular in frequency, the counter can also
measure time.
• If TC is clock period, and n cycles are counted, then the period during
which counting has taken place is nTC.

• 1kHz clock Period Tc= = 1ms


• n=4  nTc = 4 x 1ms = 4ms
Sensors and Embedded Systems – David Wilson 70
Timers on Microcontrollers

Timer is nothing but a simple binary counter that can be configured to


count clock pulses(Internal/External).

Once it reaches the Max value, it will roll back to zero setting up an
OverFlow flag and generates the interrupt if enabled.
Sensors and Embedded Systems – David Wilson 71
The Counter as a Timer - Example

• Complete the table below for different clock frequencies and counter sizes.
Clock Period Number of Counter
Frequency Time to fill counter
(Tc) Bits n (2n) range (2n -1)
1MHz 1ms 8 255 255ms
4MHz 250ns 6 63 15.75ms
1MHz 1ms 11 2,047 2047ms
500kHz 2ms 16 65,535 131.07ms
1MHz 1ms 32 4,294,967,295 4294.967295s
100kHz 10ms 24 16,777,215 167.77215s

• Counter range is 2047  =n= 11

• Counter range is 16777216  =n= 24


Sensors and Embedded Systems – David Wilson 72
Timers on the PIC18F25k22

•Timers and counters are so important most microcontrollers have these as


standard.
•PIC18F25K22 has 7 different counter timer modules (timer0 through to timer6).
•Up to four are16-bit timers/counters with pre-scaler
•Up to three are 8-bit timers/counters
•Dedicated, low-power oscillator option for Timer1
•Software programmable post-scaler available on some timer / counters.

Let’s take a closer look at these individually


Sensors and Embedded Systems – David Wilson 73
Timer0 in 8-bit mode

The 18F25K22 Timer0 can operate either in 8-bit, or in 16-bit mode.


It is shown here in 8-bit mode (page 155 PIC18F25K22 datasheet)

Actual Timer

Sensors and Embedded Systems – David Wilson 74


Registers Associated with
Timer 0

These are associated with interrupts – more about this in Lecture 14


Let’s take a closer look at this SFR

Sensors and Embedded Systems – David Wilson 75


Timer0 Control Register T0CON

• Timer0 is
controlled (SFR)
T0CON.

• The overall
operating mode is
selected by bit 6
(T08BIT), which
determines either
8 or 16 bit mode.

• (page 154 of
datasheet)
Sensors and Embedded Systems – David Wilson 76
Timer0 in 16-bit mode (1)

• Timer 0 in 16-bit mode just extends the concepts of the 8-bit version..
• (Page 156 PIC18F25K22 datasheet)

Mmmm, what’s all this then?

Sensors and Embedded Systems – David Wilson 77


Timer0 in 16-bit mode (2)

The PIC is only 8-bit.


Between reading low byte and returning to
read the high byte the value could have
changed.

Solution.
When low byte is read the high byte is also
transferred to a buffer which can then be
read later. This ensures that an accurate
snapshot of all 16bits has been captured.
The same happens during a read.

Sensors and Embedded Systems – David Wilson 78


Timer0 - Example

• An 18F25K22 Timer 0 is configured in 8-bit mode, free running from the


internal oscillator source, with prescaler set to divide-by-two. The
microcontroller oscillator is running at 4MHz.

• How should T0CON be set?

• What is the frequency of the resulting interrupt on overflow signal?

Sensors and Embedded Systems – David Wilson 79


Timer0 – TCON0 Setup

• 0b110x0000

x 2 = 2s
28-1 = 255
2 x 255 = 510
=1.96kHz

Sensors and Embedded Systems – David Wilson 80


Timer0 – TCON0 Example Code

T0CONbits.T0PS= 0b000; //Set the prescaler to 1:2


[Link] = 0; //Prescaler assigned to Timer 0
T0CONbits.T0CS = 0; //Use the instruction clock (Fcy/4)
T0CONbits.T08BIT=1; //8 bit operation
T0CONbits.TMR0ON=1; //Timer 0 enabled
while(1) // Main Program Loop
{
INTCONbits.T0IF = 0; //Clear the Timer 0 interrupt flag
TMR0 = 0; //Load a value of 0 into the timer
INTCONbits.T0IE = 1; //Enable the Timer 0 interrupt
while(INTCONbits.T0IF == 0) //Wait for interrupt to occur –when TMR0 overflows
{
NOP(); // Wait here
}
}
Sensors and Embedded Systems – David Wilson 81
Timer1 Block Diagram

• Timer 1 can be operated as a Timer with internal clock source input


(FOSC/4), as a Counter with external input (T13CKI), or as a Timer with
external oscillator input (T1OSO and T1OSI).

Actual Timer

Sensors and Embedded Systems – David Wilson 82


Timer1 – Secondary Oscillator Input

Sensors and Embedded Systems – David Wilson 83


Timer2 Block Diagram

• The Timer 2 peripheral of an 18F25K22 uses the Fosc/4 clock source.


• It features both pre and post scalers.
• A comparison register is also used to vary the overflow interrupt flag
frequency (used in the generation on PWM – next lecture).

Actual Timer

Sensors and Embedded Systems – David Wilson 84


PIC18F25K22 Timer Summary (1)

•PIC18F25K22 has 7 different counter timer modules (timer0,


timer1/3/5 and timer2/4/6).

Timer 0
• 8 or 16 bit timer/counter
• Dedicated 8-bit software programmable pre-scaler
• Internal or external clock select with edge select for external
clock
• Interrupt on overflow from FFh to 00h

Sensors and Embedded Systems – David Wilson 85


PIC18F25K22 Timer Summary (2)
Timer 1/3/5
• 16-bit timer/counter with two 8-Bit registers
• 2-bit pre-scaler
• Internal or external clock select with edge select for external
clock
• Interrupt on overflow from FFFFh to 00h
• Time base for Capture/Compare function
Timer 2/4/6
• 8-bit Timer and Period registers (TMRx and PRx)
• Software programmable pre-scaler (1:1, 1:4, 1:16)
• Software programmable post-scaler (1:1 to 1:16)
• Interrupt on TMRx match with PRx, respectively
Sensors and Embedded Systems – David Wilson 86
Timer Example

• A PIC18F25K22 is set up with an external crystal of 32.768kHz connected


to SOSCO and SOSCI.

• Sleep mode is not required.

• An interrupt on overflow is required from the Timer exactly once very 5


seconds.

• Which Timer should be used and how would it be set up?

Sensors and Embedded Systems – David Wilson 87


Timer Example – Solution (1)

Only Timer1 can be used with a secondary oscillator.

Couldn’t use timer 2/4/6


Period =30.52s anyway as they are 8 bits
only
With no prescaler and in 16 bits ( max count = 65535) longest period is

65535 x 30.52s = 2 seconds

Need prescaler of 1:4 which gives a maximum period of 8s

Sensors and Embedded Systems – David Wilson 88


Timer Example – Solution (2)

• 16-bit operation.

• Prescaler 1:4

• Secondary Oscillator

T1CON = 0b10101111

Sensors and Embedded Systems – David Wilson 89


Timer Example – Solution (3)

• This would give a period of 8 seconds so need to use the preload feature
discussed in slide 4.

• To do this use TMR1L and TMR1H registers.


• Counter only tiggers an event once it reaches its maximum count.

• To overflow after 5 seconds rather than 8 seconds need to preload the


counter with 3 seconds worth of counts.

Sensors and Embedded Systems – David Wilson 90


Timer Example – Solution (4)

Need to preload 3 seconds worth of counts. Timer counts incrementally,


and overflows only when 8 seconds has been reached.

F=8192Hz
\ 8192 counts per second
= 8192 x 3 = 24576

In Hex = 6000

In Binary = 0110 0000 0000 0000

Sensors and Embedded Systems – David Wilson 91


Timer Example – Code (1)

//************** Timer 1 Setup**************//

T1CONbits.TMR1ON=1; //Timer1 enabled


T1CONbits.T1RD16=1; //16 bit operation
T1CONbits.T1SYNC=0; //Do not synchronise with Fosc
T1CONbits.T1OSCEN=1; //Secondary Clock Enable
T1CONbits.T1CKPS=0b11; //1:4 Prescaler
T1CONbits.TMR1CS=0b10; //Timer clock source
// select.

Sensors and Embedded Systems – David Wilson 92


Timer Example – Code (2)

while(1) // Main Program Loop


{
PIR1bits.TMR1IF=0; //Clear the Timer 1 interrupt flag
PIE1bits.TMR1IE = 1; //Enable the Timer 1 interrupt
TMR1L=0x00; // Preload counter with 3 seconds worth of counts
TMR1H=0x60;
while(PIR1bits.TMR1IF == 0) //Wait for the interrupt to occur.
//This happens when the Timer overflows
{
NOP();
}

PORTBbits.RB7 = ~PORTBbits.RB7; //Toggle the LED


} Sensors and Embedded Systems – David Wilson 93
Timer2 – Example

• An 18F25K22 microcontroller is running from a clock oscillator frequency


of 8MHz.

• The T2CON register has been set to 10111101, and the PR2 loaded with
1111 1010.

• With what frequency (or period) is the TMR2IF interrupt flag set?

Sensors and Embedded Systems – David Wilson 94


Timer2 – Solution (2)

TCON2=0b10111101

Prescaler 1:4
Timer 2 ON
Post scaler 1:8

Sensors and Embedded Systems – David Wilson 95


Timer2 – Solution (1)

Fosc/4 = 2MHz
Prescaler (1:4)
Period = 500ns 500ns x 4 = 2s

Post scaler overflow 500s x 8 = 4.0ms


=250Hz

PR2 = 0b11111010 = 250


Comparator match 2s x 250 = 500s

Sensors and Embedded Systems – David Wilson 96


The Counter as a Counter

• Counter mode is selected by setting the clock source bit in the timer control
register.

• The counter will increment either on rising or falling edge of the clock pulses,
which is software selectable by the T0SE (Timer0 Source Edge) bit of the timer
control register.

• The range of the counter can be extended by the use of the prescaler.

Sensors and Embedded Systems – David Wilson 97


The Counter as a Counter (Timer 0)

Sensors and Embedded Systems – David Wilson 98


The Counter as a Counter (Timer 1)

Sensors and Embedded Systems – David Wilson 99


Next Lecture
Pulse Width Modulation (PWM).

End of Lecture Note


Sensors and Embedded Systems – David Wilson 100
Sensors and
Embedded Systems - 5
Pulse Width Modulation in Hardware
Pulse Width Modulation in Software

Sensors and Embedded Systems – David Wilson 101


The Principles of PWM, 1

A larger number of steps applied, which lengthens the pulse width, also supplies
more power to the load. Lowering the number of steps applied, which shortens the
pulse width, supplies less power
Sensors and Embedded Systems – David Wilson 102
A Practical Implementation of PWM
V
"freewheeling" diode S

L (with resistance R)
d ecay in g cu rren t flo w s
in th is d irectio n , w h en IL
sw itch ed o ff.

V
G

lo g ic g ate,
o r p o rt b it
o u tp u t
t
on
Closed In general:
Switch
Open
ton VS
T
I Iave = ___
x _____
Iave
T R
Sensors and Embedded Systems – David Wilson 103
A Simple PWM Structure.

clock Counter

Comparator Output

= 0 if Counter < PWM Reg.


= 1 if Counter > PWM Reg.
PWM Register

data bus

Sensors and Embedded Systems – David Wilson 104


PWM Waveforms.

Sensors and Embedded Systems – David Wilson 105


The 18F25K22 PWM Types

• Three Enhanced Capture/Compare/PWM modules (ECCP1/2/3) and two


standard Capture/Compare/PWM modules (CCP4/5) – Table 14.1 pg 173 of
datasheet.

• In CCP modules, the standard PWM function is identical.

• In ECCP modules, the Enhanced PWM function has either full-bridge or half-
bridge PWM output. Full-bridge ECCP modules have four available I/O pins while
half-bridge ECCP modules only have two available I/O pins.

• ECCP PWM modules can be configured as standard PWM modules.

Sensors and Embedded Systems – David Wilson 106


Standard PWM on The 18F25K22

• The standard PWM mode generates a Pulse-Width modulation (PWM) signal on


the CCPx pin with up to 10 bits of resolution. The period, duty cycle, and
resolution are controlled by the following registers:

• PRx registers
• TxCON registers
• CCPRxL registers
• CCPxCON registers

Sensors and Embedded Systems – David Wilson 107


Setup For PWM Operation.
1. Select the 8-bit Timer source, (Timer2/4 or 6) to be used by setting the
CxTSEL<1:0> bits in CCPTMRSx register.
2. Load the PRx register with the PWM period value.
3. Configure the CCP module for the PWM mode using the CCPxCON
register .
4. Load the CCPRxL register and the DCxB<1:0> bits of the CCPxCON
register, with the PWM duty cycle value.
5. Configure and start the 8-bit TimerX resource:
a. Clear the TMRxIF interrupt flag bit.
b. Configure the TxCKPS bits of the TxCON register with the Timer
prescale value.
c. Enable the Timer by setting the TMRxON bit of the TxCON register.
Sensors and Embedded Systems – David Wilson 108
18F25K22 Timer Block Diagram
A signal from
Internal clock the comparator,
frequency, Optional
8-bit which resets
straight from the frequency
counter counter to zero
oscillator divider

An 8-bit register,
whose value you
can set in your
program

Postscaler not used for PWM generation

Sensors and Embedded Systems – David Wilson 109


Example Waveforms for PWM

CCPRIL value
Timer 2 and PR2 values changed in program
equal, Timer is reset and
PWM goes high
CCPRIL value transferred
PR2 Value to CCPRIH as Timer clears

Timer 2 Value

PWM Output
T ton

Sensors and Embedded Systems – David Wilson 110


Timer 2 Control Register

Sensors and Embedded Systems – David Wilson 111


18F25K22 PWM Operation
Programmer writes
required pulse
width here.

Gets value from


buffer. Determines
PWM pulse width.

Timer 2, free-
running

Sets the PWM


Period.

Sensors and Embedded Systems – David Wilson 112


CCP1CON/CCP2CON Registers

Sensors and Embedded Systems – David Wilson 113


Locating the Relevant SFRs

Sensors and Embedded Systems – David Wilson 114


CCP on the PIC18F25K22

Sensors and Embedded Systems – David Wilson 115


Example PWM

Generate a PWM signal on CCP1, Frequency = 250Hz, Duty =3/4, Xtal=4MHz

• Configure timer 2 to give a frequency of 250Hz and determine any prescale


values
• Set PWM duty cycle
• Write the code

Sensors and Embedded Systems – David Wilson 116


Solution (1) Configure Timer2

• Determine Prescale value

Input clock to timer is


Maximum period with no prescaler
With prescaler set to 1:16 maximum period = 4.096ms

Sensors and Embedded Systems – David Wilson 117


Solution (2) Set PWM Period

Limit counter to overflow after 4ms

From data sheet (pg181)

PWM period = [(PR2) + 1] • 4 • Tosc • (TMR2 prescale)

PWM period = 1/250 = 4ms


0.004 = [PR2 + 1] •4 •[1 / 4000000] • 16
PR2 + 1 = 250
PR2 = 249
PR2 = 0xF9 ( 249 in hex)
Sensors and Embedded Systems – David Wilson 118
Solution (3) Set PWM Duty Cycle
Equation 14.3 pg 181 of datasheet gives;

CCPR = 750 = 1 0 1 1 1 0 1 1 1 0

CCPR1L = 0xBB

DC1B =0x2

Sensors and Embedded Systems – David Wilson 119


Solution (4) The Code
void PIC_Initialise(void)
{
TRISCbits.RC2=0; //CCP1 to RC2 and set to output
ANSELCbits.ANSC2=0; //CCP1 to RC2 and set to digital
}
void EPWM1_Initialise(void)
{
CCP1CON = 0x2C; // CCP1M DC1B 2; P1M single
CCPR1L = 0xBB; // CCPR1L 187
CCPTMRS0bits.C1TSEL = 0x0; // Selecting Timer2
}

void TMR2_Initialise(void)
{
PR2 = 0xF9; // PR2 249;
TMR2 = 0x00;
PIR1bits.TMR2IF = 0; // Clearing IF flag
T2CON = 0x06; // T2CKPS 1:16; T2OUTPS 1:1; TMR2 on
}
Sensors and Embedded Systems – David Wilson 120
Solution (5) The Code

void main(void)
{
PIC_Initialise();
EPWM1_Initialise();
TMR2_Initialise();
while(1)
{
//sit here and do nothing
}

Sensors and Embedded Systems – David Wilson 121


Additional Config for ECCP

The ECCP modules have the following additional PWM registers which control
Auto-shutdown, Auto-restart, Dead-band Delay and PWM Steering modes:

• ECCPxAS registers
• PSTRxCON registers
• PWMxCON registers

Not to worry too much about these as we will be using standard PWM.

Sensors and Embedded Systems – David Wilson 122


PWM in Software - delays

void servoRotate90() //90 Degree


{
unsigned int i;
for(i=0;i<50;i++)
{
PORTBbits.RB4=1;
__delay_us(1375);
PORTBbits.RB4=0
__delay_us(18625);
}
}

Sensors and Embedded Systems – David Wilson 123


PWM using Timer0 and software (1)

Timer 0

• Timer 0 16 bit mode


• PWM Duty=20ms

Sensors and Embedded Systems – David Wilson 124


PWM using Timer0 and software (2)

• Timer 0 in 16 bit mode with 4MHz clock overflows every 65535s


• Use preload 65535 – 20000 to get a 20ms period.
• Timer 1 counts from 45536 to 65535

void Timer0_Init(void)
{
T0CON=0x88 // Clock Fosc/4,no prescale,16bit, timer on
TMR1H=0xB1; // Preload timer 1 so overflows every 20ms
TMR1L=0xE0; // 65535 -20000+1 ( 1 for ISR overhead))
}

Sensors and Embedded Systems – David Wilson 125


The code
while (1)
{
value = (TMR0H<<8)+TMR0L; // combine 2 8bit timer registers to one 16bit number.
if (value>duty)
{
PORTAbits.RA2=1;
}
else
{
PORTAbits.RA2=0;
}
if (T0IF==1)
{
TMR0H=0xB1; // Preload timer 0 so overflows every 20ms
TMR0L=0xE0; // 65535-20000
T0IF=0; // Clear interrupt flag
}
Read_ADC(); // read AN0 and return ‘duty’
Sensors and Embedded Systems – David Wilson 126
}
Next Lecture
Actuators and Motor Control

End of Lecture Note


Sensors and Embedded Systems – David Wilson 127
Sensors and
Embedded Systems - 6
Motors and Actuators

Sensors and Embedded Systems – David Wilson 128


A Practical Implementation of PWM

V
S
"freewheeling" diode In general:
L (with resistance R) ton VS
d ecay in g cu rren t flo w s
in th is d irectio n , w h en
Iave = ___
x _____
IL
sw itch ed o ff. T R

t
V on
G Closed
Switch
Open
lo g ic g ate, T
I
o r p o rt b it
Iave
o u tp u t

Sensors and Embedded Systems – David Wilson 129


H Bridge Motor Direction Control
Enable1

VBAT
9V

R6 R5
PNP PNP
R3 R4

Clockwise on Q3 Q4
off

Direction Output1 M Output2

INPUT 1
R1 off Q1 Q2
on R2
INPUT 2

NPN NPN

Enable1

VBAT
9V

R6 R5
PNP PNP
R3 R4
Q3 Q4
off on
Anti clockwise
Output1 M Output2
Direction
R1 on off R2
INPUT 1 Q1 Q2
INPUT 2

NPN NPN

Sensors and Embedded Systems – David Wilson 130


Single half bridge Equivalent circuit

Equivalent single
half bridge

Enable1

VBAT
9V

R6 R5
PNP PNP
R3 R4
Q3 Q4

Output1 M Output2

R1 R2
INPUT 1 Q1 Q2
INPUT 2

NPN NPN

Sensors and Embedded Systems – David Wilson 131


H Bridge Motor Speed Control
Enable1

VBAT
9V

R6 R5
PNP PNP
R3 R4
Q3 Q4

Output1 M Output2

R1 R2
INPUT 1 Q1 Q2
INPUT 2

NPN NPN

PWM
PWM Signal

Sensors and Embedded Systems – David Wilson 132


Changing Motor Speed / Direction .

void mot_fwd(void) //sets motor running forward


{
CCPR2L = 155;
PORTCbits.RC2 = 1; //enable motor
}

void mot_rev(void) //sets motor running in reverse


{
CCPR2L = 100;
PORTCbits.RC2 = 1; //enable motor
}

Sensors and Embedded Systems – David Wilson 133


Servo Motors (1)

A servomotor is a rotary actuator or linear actuator that allows for high-response,


high-precision control of angular or linear position

Sensors and Embedded Systems – David Wilson 134


Servo Motors (2)

When the shaft of the motor is at the desired position, the motor is stopped.
The motor's speed is proportional to the difference between its actual position and
desired position.
PWM needs to be sent several times for system to move to desired position ( see
datasheet)

Sensors and Embedded Systems – David Wilson 135


Servo Motors – Control Signal

The angle is determined by the duration of the pulse (PWM) that is applied to the
control wire.

The servo expects to see a pulse every 20 ms

Min Pulse 0
Pulse Width 1ms
90

Neutral
Pulse Width 1.5ms

Max Pulse 180


Pulse Width 2ms

Sensors and Embedded Systems – David Wilson 136


Servo Motors – Position Feedback

The position of the servo motor is sensed by a rotational potentiometer

Sensors and Embedded Systems – David Wilson 137


Servo Motors – PWM Code

Can use CCP ( hardware) on a dedicated pin ( more in lecture 6) or software


generated e.g.
void servoRotate90() //90 Degree
{
unsigned int i;
for(i=0;i<50;i++)
{
PORTBbits.RB4=1;
__delay_us(1375);
PORTBbits.RB4=0
__delay_us(18625);
}
}
Sensors and Embedded Systems – David Wilson 138
Servo Motors – Improved
Method?
20ms is very slow period
Whet your appetite to look into interrupts?

• Timer 1 16 bit mode


• CCP5 – compare Timer_1 with value
• Eg ADC
• Use ISR to toggle output pin

Sensors and Embedded Systems – David Wilson 139


Servo Motors – Improved Code (1)

• Timer 1 in 16 bit mode with 4MHz clock overflows every 65535s


• Use preload 65535 – 20000 to get a 20ms period.
• Timer 1 counts from 45536 to 65535

void Timer1_Init(void)
{
T1CON=0x3; // ClockFosc/4,no prescale,16bit, timer on
TMR1H=0xB1; // Preload timer 1 so overflows every 20ms
TMR1L=0xE0; // 65535 -20000+1 ( 1 for ISR overhead))
}

Sensors and Embedded Systems – David Wilson 140


Servo Motors – Improved Code (2)

• Configure CCP5 to compare Timer 1 value with data passed from main code.

void CCP5_Init(void)
{
CCP5CON = 0x0A; // CCP5 Compare mode: generate
// software interrupt on compare match
// (CCP5 pin is unaffected, CCP5IF is set)
CCPTMRS1 = 0x0; // Timer 1 used.
}
• Pass data to compare register

CCPR5 = duty;
Sensors and Embedded Systems – David Wilson 141
Servo Motors – ISR Code, Worth a
Look?
void __interrupt(high_priority) Timer1_ISR(void)
{
if (TMR1IF && TMR1IE) // if Timer 1's interrupt flag and enable set
{
TMR1H=0xB1; // Reload timer values Reload Timer 1
TMR1L=0xE0; with 45536
TMR1IF = 0; // clear the interrupt flag
LATAbits.LATA5 = 0;
}
if (CCP5IF && CCP5IE) // if CCP5's interrupt flag and enable set
Port pins
{ toggled
LATAbits.LATA5 = 1;
CCP5IF=0; // clear the interrupt flag
}
}

Sensors and Embedded Systems – David Wilson 142


Stepper Motors

Used in process control, CNC machines, 3D printers etc


Sensors and Embedded Systems – David Wilson 143
Stepper Motors – Wave Drive

A A

B B B B

A A

A A

B B B B

A A

Sensors and Embedded Systems – David Wilson 144


Stepper Motors – Half Step

A A A A

B B B B B B B B

A A A A

A A A A

B B B B B B B B

A A A A
Sensors and Embedded Systems – David Wilson 145
Stepper Motors – Micro-stepping

A
With maximum power in phase A,
phase B is at zero. The rotor will line
B B
up with phase A. As the current to
stepper motor energised coil phase A decreases, it increases to
sequence
A
phase B. The rotor will take small
A steps towards phase B until phase B
is at its maximum and phase A is at
B B zero. The process continues around
the other phases.
A

Sensors and Embedded Systems – David Wilson 146


Stepper Motors – Code

• Individually switch on and off ports to match the desired drive pattern.
• Use CCP module to generate PWM ‘sine wave’ for micro-stepping.
• Use a dedicated stepper driver module eg TMC2130.

Sensors and Embedded Systems – David Wilson 147


Next Lecture
Interfacing with LCD’s

End of Lecture Note


Sensors and Embedded Systems – David Wilson 148
Sensors and
Embedded Systems - 7
Interfacing with Displays

Sensors and Embedded Systems – David Wilson 149


Seven Segment Display

Sensors and Embedded Systems – David Wilson 150


Port Mapping for Display
U6
7Seg13.2mm
a 7 C7
10 6 C6
C1 9 f g b
4
C2 C5
1 5 C0
C3 2 e
d
c
C4
dp 470Ω
470Ω

3
8

Complete for remaining patterns


Sensors and Embedded Systems – David Wilson 151
Generic LCD Pinout
•Pins 1&2 Display supply voltage.
•Pin 3 – VEE: Contrast control.
•Pin 4 –RS: Register Select
• RS = 0: Command , RS = 1: Data
•Pin 5 – RW: Read / Write.
•Pin 6 –E: Enable.
• High to low pulse to latch data.
•Pins 7:14 - DATA pins D0 to D7.
•Pin 15:16 - LED + and LED -.
Sensors and Embedded Systems – David Wilson 152
Examples of Compatible LCD
Controllers

Sensors and Embedded Systems – David Wilson 153


LCD 8-bit Interface

Sensors and Embedded Systems – David Wilson 154


8 Bit LCD Initialisation.

Sensors and Embedded Systems – David Wilson 155


8-bit Initialisation Code

void LCD_Init() Mmmm, what’s this?

{
__delay_ms(15); // Power on delay as per datasheet
LCD_Command(0x38); // Uses 2 line and initialise 5*7 matrix
__delay_ms(5); // Additional delay as per datasheet
LCD_Command(0x01); // Clear display screen
LCD_Command(0x0c); // Display on cursor off
LCD_Command(0x06); // Increment cursor (shift cursor to right)
}
Full function set used and 5ms delay routine incorporated into
LCD_Command routine rather than 3 function set commands
Sensors and Embedded Systems – David Wilson 156
LCD Command – 8 bit mode

void LCD_Command(unsigned char cmd )


{
ldata = cmd; //Send data to PORT connected to data
//bits on LCD.
RS = 0; //Command Register is selected
EN = 1; //High-to-low on Enable to latch data
__delay_ms(1);
EN = 0;
__delay_ms(5);
}

Sensors and Embedded Systems – David Wilson 157


LCD 4-bit interface (1)

Sensors and Embedded Systems – David Wilson 158


LCD 4-bit interface (2)
• 8 bit data/commands are sent a nibble (4-bits) at a time

• The higher nibble is sent first and then the lower nibble.

• Pulse the enable line between each nibble

• Only 4 data (D4 - D7) pins of the LCD are connected to the microcontroller
along with Register select, Read/write and Enable.

• Pro – less pins used.

• Cons – slower and coding slightly more complex ( AND, OR and bit shifting
operations).

Sensors and Embedded Systems – David Wilson 159


4 Bit LCD Initialisation –Flow Chart.

Sensors and Embedded Systems – David Wilson 160


4 Bit Initialisation by Instruction (1)

PIC RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0


LCD DB7 DB6 DB5 DB4 X En R/W RS
Step LCD Initialisation
1 Wait 15ms
2 0 0 1 1 X 1 0 0 Initial Function Set 1 (still 8 bit mode)
3 0 0 1 1 X 0 0 0 High to low on 'En' to latch data
4 Wait 5ms
5 0 0 1 1 X 1 0 0 Initial Function Set 2 (still 8 bit mode)
6 0 0 1 1 X 0 0 0 High to low on 'En' to latch data
7 Wait 1ms
8 0 0 1 1 X 1 0 0 Initial Function Set 3 (still 8 bit mode)
9 0 0 1 1 X 0 0 0 High to low on 'En' to latch data
10 Wait 1ms
11 0 0 0 0 X 0 0 0 Initial Function Set 3 (still 8 bit mode)
12 0 0 0 0 X 1 0 0 High to low on 'En' to latch data
13 Wait 5ms
14 0 0 1 0 X 1 0 0 Initial Function Set to set 4 bit interface (still 8 bit mode)
15 0 0 1 0 X 0 0 0 High to low on 'En' to latch data
16 0 0 1 D/L X 1 0 0 Function Set (D/L = 0)

Sensors and Embedded Systems – David Wilson 161


4 Bit Initialisation by Instruction (2)

PIC RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0


LCD DB7 DB6 DB5 DB4 X En R/W RS
Step LCD Initialisation
17 0 0 1 D/L X 0 0 0 High to low on 'En' to latch data
18 N F X X X 1 0 0 Function Set ( N=1 and F=0)
19 N F X X X 0 0 0 High to low on 'En' to latch data
20 0 0 0 0 X 1 0 0 Clear Display
21 0 0 0 0 X 0 0 0 High to low on 'En' to latch data
22 0 0 0 1 X 1 0 0 Clear Display
23 0 0 0 1 X 0 0 0 High to low on 'En' to latch data
24 0 0 0 0 X 1 0 0 Display Control (display on cursor off)
25 0 0 0 0 X 0 0 0 High to low on 'En' to latch data
26 1 D C B X 1 0 0 Display Control (display on cursor off)
27 1 D C B X 0 0 0 High to low on 'En' to latch data
28 0 0 0 0 X 1 0 0 Entry Set Mode
29 0 0 0 0 X 0 0 0 High to low on 'En' to latch data
30 0 1 I/D S X 1 0 0 Entry Set Mode (I=1, S=0)
31 0 1 I/D S X 0 0 0 High to low on 'En' to latch data

Sensors and Embedded Systems – David Wilson 162


4-bit Initialisation Code(1)

void LCD_Init() More about this routine later


{
LCD_Port = 0; //PORT as Output Port
__delay_ms(15); //15ms,16x2 LCD Power on delay
LCD_Command(0x03);
LCD_Command(0x02); //send for initialization of LCD
//for nibble (4-bit) mode
LCD_Command(0x28); //use 2 line and 5*7 dots
LCD_Command(0x01); //clear display screen
LCD_Command(0x0c); //display on cursor off
LCD_Command(0x06); //increment cursor (shift cursor to right)

}
Sensors and Embedded Systems – David Wilson 163
Logical vs Bitwise Operations (1)

• Logical operations assume that the entire variable represents either true or false.

• Combining two integer values using a logical operator produces one result,
with the variable representing true or false.

• Use double operators && ||

Sensors and Embedded Systems – David Wilson 164


Logical AND (&&)

int x = 0000FFFF;
int y = FFFF00FF;
int z = x && y;

x is not zero , so x is true


y is not zero, so y is true
z = true && true
z = true = 1

Sensors and Embedded Systems – David Wilson 165


Logical vs Bitwise Operations (2)

• Bitwise operations assume that each bit in the variable’s value represents a
separate true or false.

• Combining two integer values using a bitwise operators produces 8 (or 16 or


32 or 64) separate bits each representing a true or a false.

• Use single operators & |

Sensors and Embedded Systems – David Wilson 166


Bitwise AND (&)

• A bitwise AND operation is actually 8 (or 16 or 32) AND operations.

• An example of ANDing:

0011 1011
0000 1111
cleared 0000 1011 unchanged

• The AND instruction can be used to clear selected bits in an operand


while preserving the remaining bits. This is called masking.
Sensors and Embedded Systems – David Wilson 167
Bitwise OR (|)
• A bitwise OR operation is actually 8 (or 16 or 32) OR operations.

• An example of ORing:
0011 1011
0000 1111
unchanged 0011 1111 set

• The OR instruction can be used to set selected bits in an operand


while preserving the remaining bits.

Sensors and Embedded Systems – David Wilson 168


Bit Shifting

• Shift Left – Same as multiply by two 0 0 1 1 0 1 0 1 0000…


.
signed char x=53; 0 1 1 0 1 0 1 0

signed char y=x<<1;

• Shift Right – Same as divide by two


(almost)
sig 0 0 1 1 0 1 0 1
signed char x=53; n

signed char y=x>>1; 0 0 0 1 1 0 1 0

Sensors and Embedded Systems – David Wilson 169


LCD Command – 4 bit mode
void LCD_Command(unsigned char cmd )
{
ldata = (ldata & 0x0f) |(0xF0 & cmd); //Send higher nibble of command first
RS = 0; //Command Register is selected
EN = 1; //High-to-low on Enable to latch data
__delay_ms(1);
EN = 0;
__delay_ms(5);
ldata = (ldata & 0x0f) | (cmd<<4); //Send lower nibble of command
EN = 1;
__delay_ms(1);
EN = 0;
__delay_ms(5);
}

Sensors and Embedded Systems – David Wilson 170


4-bit Initialisation Code(2)

void LCD_Init()
{
LCD_Command(0x03);
LCD_Command(0x02); //send for initialisation of LCD
//for nibble (4-bit) mode
LCD_Command(0x28); //use 2 line and initialise 5*7 dots
LCD_Command(0x01); //clear display screen
LCD_Command(0x0c); //display on cursor off
LCD_Command(0x06); //increment cursor (shift cursor to right)
}

Sensors and Embedded Systems – David Wilson 171


LCD Display Addresses (1)

• The HD44780 type controller chip is used with a wide variety of Liquid Crystal
Displays.
• These LCDs come in many configurations and can be arranged in 1, 2, or 4 rows.
• The controller operates exactly the same way for all displays and it is up to the
programmer to deal with this situation.
• The controller contains 80 bytes of Display Data Random Access Memory which is
usually referred to as DDRAM.

Sensors and Embedded Systems – David Wilson 172


LCD Display Addresses (2)
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27
40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F 60 61 62 63 64 65 66 67
The DDRAM uses 6 bit addressing with the most significant bit identifying the row.
By comparing the addresses in the first row with those just below in the second
row the only difference is in that one bit (pg24 of datasheet ).
Position
Row
Hex

80 1 0 0 0 0 0 0 0
C0 1 1 0 0 0 0 0 0

In code you will sometimes see the address therefore as


80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F 90 91 92 93 94 95 96 97 98 99 9A 9B 9C 9D 9E 9F A0 A1 A2 A3 A4 A5 A6 A7
C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CACB CC CD CE CF D0D1D2D3D4D5D6D7D8D9 DA DB DC DD DE DF E0 E1 E2 E3 E4 E5 E6 E7
Sensors and Embedded Systems – David Wilson 173
Example LCD Display Addresses

16 x 2
80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F
C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF

20 x 4
80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F 90 91 92 93
C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF D0 D1 D2 D3
94 95 96 97 98 99 9A 9B 9C 9D 9E 9F A0 A1 A2 A3 A4 A5 A6 A7
D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF E0 E1 E2 E3 E4 E5 E6 E7

Sensors and Embedded Systems – David Wilson 174


Writing to LCD’s (1)
TEXT:
Most displays work with the standard 128 ASCII characters.

NUMBERS:
Numbers can be more difficult !

Example 1:
Your micro-controller measures a sensor and returns the value of 5.
Issue:
The value of five and the character “5” are two different things. The
ASCII number for the character “5” is 53.
Solution:
Add 48 to any number that you are sending to the display.
Sensors and Embedded Systems – David Wilson 175
ASCII
American Standard Code for Information Interchange
DEC HEX Char/Control DEC HEX Char/Control DEC HEX Char DEC HEX Char DEC HEX Char DEC HEX Char DEC HEX Char/Control DEC HEX Char DEC
0 00 Null 20 14 DC4 (Device Control 4) 40 28 ( 60 3C < 80 50 P 100 64 d 120 78 x 140 8C Œ 160
1 01 SOH (Start of Header) 21 15 NAK (Negative Acknowledge) 41 29 ) 61 3D = 81 51 Q 101 65 e 121 79 y 141 8D 161
2 02 STX (Start of Text) 22 16 SYN Synchronize 42 2A * 62 3E > 82 52 R 102 66 f 122 7A z 142 8E Ž 162
3 03 ETX (End of Text) 23 17 ETB (End Transmission Block) 43 2B + 63 3F ? 83 53 S 103 67 g 123 7B { 143 8F unused 163
4 04 EOT ( End of Transmission) 24 18 CAN Cancel 44 2C , 64 40 @ 84 54 T 104 68 h 124 7C | 144 90 unused 164
5 05 ENQ (Enquiry) 25 19 EM (End of Medium) 45 2D - 65 41 A 85 55 U 105 69 i 125 7D } 145 91 ‘ 165
6 06 ACK (Acknowledge) 26 1A SUB (Substitute) 46 2E . 66 42 B 86 56 V 106 6A j 126 7E ~ 146 92 ’ 166
7 07 BELL (Ring) 27 1B ESC ( Escape) 47 2F / 67 43 C 87 57 W 107 6B k 127 7F DEL (Delete) 147 93 “ 167
8 08 BS (Backspace) 28 1C FS (File Separator) 48 30 0 68 44 D 88 58 X 108 6C l 128 80 € 148 94 ” 168
9 09 HT (Horizontal Tab) 29 1D GS (Group Separator) 49 31 1 69 45 E 89 59 Y 109 6D m 129 81 unused 149 95 • 169
10 0A LF (Line Feed) 30 1E RS (Record Separator) 50 32 2 70 46 F 90 5A Z 110 6E n 130 82 ‚ 150 96 – 170
11 0B VT (Vertical Tab) 31 1F US (Unit Separator) 51 33 3 71 47 G 91 5B [ 111 6F o 131 83 ƒ 151 97 — 171
12 0C FF (Form feed) 32 20 SPACE 52 34 4 72 48 H 92 5C \ 112 70 p 132 84 „ 152 98 ˜ 172
13 0D CR (Carriage Retrun) 33 21 ! 53 35 5 73 49 I 93 5D ] 113 71 q 133 85 … 153 99 ™ 173
14 0E SO ( Shift Out) 34 22 " 54 36 6 74 4A J 94 5E ^ 114 72 r 134 86 † 154 9A š 174
15 0F SI (Shift In) 35 23 # 55 37 7 75 4B K 95 5F _ 115 73 s 135 87 ‡ 155 9B › 175
16 10 DLE ( Data Link Escape) 36 24 $ 56 38 8 76 4C L 96 60 ` 116 74 t 136 88 ˆ 156 9C œ 176
17 11 DC1 (Device Control 1) XON 37 25 % 57 39 9 77 4D M 97 61 a 117 75 u 137 89 ‰ 157 9D unused 177
18 12 DC2 (Device Control 2) 38 26 & 58 3A : 78 4E N 98 62 b 118 76 v 138 8A Š 158 9E ž 178
19 13 DC3 (Device Control 3) XOFF 39 27 ' 59 3B ; 79 4F O 99 63 c 119 77 w 139 8B ‹ 159 9F Ÿ 179

The original ASCII specification encodes 128 characters into numbers (see table below). These include the numbers 0 to 9, lowercase a-z, uppercase A-Z, and punctuation.
The first 31 characters are non-printing "control codes", most of which are no longer used, with the exception of the carriage return (13), line feed (10), and tab (9).

Sensors and Embedded Systems – David Wilson 176


Letter ‘v’= 0x76 = 01110110 -
ASCII LCD_Data = (LCD_Data & 0x0F) | (0xF0 & letter)
Step 1
LCD_Data 0 0 0 0 0 0 0 0 Letter 0 1 1 1 0 1 1 0
& 0F 0 0 0 0 1 1 1 1 & F0 1 1 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0

(LCD_Data& 0x0F) 0 0 0 0 0 0 0 0
OR (0xF0 & letter) 0 1 1 1 0 0 0 0
LCD_Data 0 1 1 1 0 0 0 0

Need to also incorporate RS=1 and a high-to-low pulse on En


Port bit GPIO7 GPIO6 GPIO5 GPIO4 GPIO3 GPIO2 GPIO1 GPIO0
LCD bit DB7 DB6 DB5 DB4 X En X RS
Sensors and Embedded Systems – David Wilson 177
Letter ‘v’= 0x76 = 01110110 -
ASCII
Step 2 LCD_Data = (LCD_Data & 0x0F) | (letter<<4)
LCD_Data 0 0 0 0 0 0 0 0 Letter 0 1 1 1 0 1 1 0
& 0F 0 0 0 0 1 1 1 1 Letter<<4 0 1 1 0 0 0 0 0
0 0 0 0 0 0 0 0

(LCD_Data& 0x0F) 0 0 0 0 0 0 0 0
OR (letter<<4) 0 1 1 0 0 0 0 0 Send Low Nibble
LCD_Data 0 1 1 0 0 0 0 0

Need to also incorporate RS=1 and a high-to-low pulse on En


Port bit GPIO7 GPIO6 GPIO5 GPIO4 GPIO3 GPIO2 GPIO1 GPIO0
LCD bit DB7 DB6 DB5 DB4 X En X RS
Sensors and Embedded Systems – David Wilson 178
Writing to LCD’s (2)
Example 2:

Your micro-controller measures a sensor and returns the value of 139.

Issue:

You can only send a single digit at a time to the display.


Solution:

First 139 must be chopped into “1”, “3”, and “9” then add 48 to each to convert the
value into ASCII then send individually to the display.

What a bother, if only we could string them together !


Sensors and Embedded Systems – David Wilson 179
Strings

C has no native string data type, so strings must always be treated as character
arrays.

Strings:
•Are enclosed in double quotes "string"
•Are terminated by a null character '\0’ (ASCII value of 0).
•Must be manipulated as arrays of characters
•(treated element by element)

Sensors and Embedded Systems – David Wilson 180


Sending Text to LCD (1)
A D C = \0
String msg msg +3

LCD_String("ADC=“); // Sends a string to LCD


Pointer
void LCD_String(const char *msg)
{ This routine loops until the pointer
while((*msg)!=0) reaches the end of the string.
{
LCD_Char(*msg);
msg++;
}
Increment pointer
} Sensors and Embedded Systems – David Wilson 181
Sending Text to LCD (2)

This routine sends ascii one character at a time

void LCD_Char(char dat)


{
ldata= dat; //Send data to LCD
RS = 1; //Data Register is selected
EN=1; //High-to-Low pulse on Enable pin to latch data
RW = 0; // Select the Write Operation.
NOP();
EN=0;
__delay_ms(1);
}
Sensors and Embedded Systems – David Wilson 182
Sending Numbers to LCD -
Sprintf()
Print format to string

sprintf( data, "%2.1f“ ,flaps); // sprintf with float 2 sig figs and 1 decimal place

String to be formatted
Destination string

The conversion type field is where a single character specifies that the
argument is interpreted as a character, string, number, or pointer.
Sensors and Embedded Systems – David Wilson 183
Sprintf() Arguments
Conversion type Argument Type Output Format
d int Signed decimal number
u unsigned int Unsigned decimal number
o unsigned int Unsigned octal number
x unsigned int Unsigned hexadecimal number using 0123456789abcdef
X unsigned int Unsigned hexadecimal number using 0123456789ABCEDF
f double Floating-point number using the format [-][Link]
e double Floating-point number using the format [-][Link][-]dd
E double Floating-point number using the format [-][Link][-]dd
g double Floating-point number using either e or f format.
c int int is converted to unsigned char, and the resulting character is written
s char * String with a terminating null character
p void * Pointer value, the X format is used
% <none> A % is written. No argument is converted.

Sensors and Embedded Systems – David Wilson 184


Sprintf() in Code

while(1)
{
Read_ADC();
LCD_Command(0xC4); //move cursor to row 2 column 4
sprintf(data, "%d", result);
LCD_String(data);
__delay_ms(200);
}

Sensors and Embedded Systems – David Wilson 185


Sprintf() in Code
while(1)
{
Read_ADC();
LCD_Command(0xC4); //move cursor to row 2 column 4
sprintf(data, "%d", result);
LCD_String(data);
__delay_ms(200);
}

186
Next Lecture
Digital to Analogue Conversion

End of Lecture Note


Sensors and Embedded Systems – David Wilson 187
Sensors and
Embedded Systems - 8
Digital to Analogue Conversion

Sensors and Embedded Systems – David Wilson 188


Digital to Analog Converter

Resistor ladder

MUX signal
selection bits

MUX, selects
between several
signals and forwards
the selected one to a
single output line.

Sensors and Embedded Systems – David Wilson 189


8 to 1 MUX Operation

Let’s look at an 8 to 1
MUX as an example.

Source Select
Sensors and Embedded Systems – David Wilson 190
8 to 1 MUX (Input 0)

Sensors and Embedded Systems – David Wilson 191


8 to 1 MUX (Input 1)

Sensors and Embedded Systems – David Wilson 192


8 to 1 MUX (Input 2)

Sensors and Embedded Systems – David Wilson 193


8 to 1 MUX (Input 3)

Sensors and Embedded Systems – David Wilson 194


8 to 1 MUX (Input 4)

Sensors and Embedded Systems – David Wilson 195


8 to 1 MUX (Input 5)

Sensors and Embedded Systems – David Wilson 196


8 to 1 MUX (Input 6)

Sensors and Embedded Systems – David Wilson 197


8 to 1 MUX (Input 7)

Sensors and Embedded Systems – David Wilson 198


Resistor Ladder

Each MUX setting selects one output from the internal resistor ladder and hence
generates an output voltage dependent on the MUX input setting.

Sensors and Embedded Systems – David Wilson 199


Resistor Ladder (Input 0)

Sensors and Embedded Systems – David Wilson 200


Resistor Ladder (Input 1)

Sensors and Embedded Systems – David Wilson 201


Resistor Ladder (Input 2)

Sensors and Embedded Systems – David Wilson 202


Resistor Ladder (Input 3)

Sensors and Embedded Systems – David Wilson 203


Resistor Ladder (Input 4)

Sensors and Embedded Systems – David Wilson 204


Resistor Ladder (Input 5)

Sensors and Embedded Systems – David Wilson 205


Resistor Ladder (Input 6)

Sensors and Embedded Systems – David Wilson 206


Resistor Ladder (Input 7)

Sensors and Embedded Systems – David Wilson 207


DAC - Other Features

Selectable
reference
voltages

Output
Enable

Sensors and Embedded Systems – David Wilson 208


DAC SFR’s

VREFCON0 – sets up fixed voltage reference peripheral


VREFCON1 – configures the voltage references used by the DAC
VREFCON2 – voltage select bits (DACR <4:0>

𝑉 𝑜𝑢𝑡 =¿
Sensors and Embedded Systems – David Wilson 209
DAC Initialisation

void DAC_Initialise (void)


{
DACEN = 1; // DAC enabled
DACLPS = 1; // +ve low power reference source
DACOE = 1; // DACOUT pin enabled
[Link] = 0b00; // Vdd as +ve reference
DACNSS = 0; // Vss as -ve reference
[Link]=0b0000; // Initial output is 0v
}

Sensors and Embedded Systems – David Wilson 210


DAC Example Code - Sawtooth
void main(void)
{
int i=0;
DAC_Initialise ();
while(1)
{
[Link]=i; // increase i for DAC o/p
i++;
__delay_us(310);
if (i>=31) i=0; // Start next cycle from 0
}
}
Sensors and Embedded Systems – David Wilson 211
DAC in Proteus

DAC o/p to input for Proteus simulation to work

Sensors and Embedded Systems – David Wilson 212


Proteus Scope Output

Sensors and Embedded Systems – David Wilson 213


Next Lecture
Analogue to Digital Conversion

End of Lecture Note


Sensors and Embedded Systems – David Wilson 214
Sensors and
Embedded Systems - 9
Analogue to Digital Conversion

Sensors and Embedded Systems – David Wilson 215


The Analog to Digital Converter
(ADC)
• Accepts an input voltage that is infinitely variable and converts this to one of a
fixed number of output values.
• For n-bits, the maximum output value will be (2n –1). For example, for an 8-bit
ADC, the maximum value will be 25510 or 111111112.

Sensors and Embedded Systems – David Wilson 216


The Need for ADC

Analogue Digital
voltage value
temperature
pressure
light Transducer Signal ADC Controller
weight Conditioning
(optional)
airflow
humidity

A Basic System

Sensors and Embedded Systems – David Wilson 217


Data Acquisition System.

Usually, more than one input is required and the signal needs processing
before it can be converted. In most cases, therefore, it is necessary to build
up a complete data acquisition system.

Sensors and Embedded Systems – David Wilson 218


Sample and Hold Circuit.

ADCs work better converting a stationary voltage.


A capacitor is charged from a source which inevitably has some resistance.
Resistance comes from the source, internal resistance of the solid-state
switch used in the S&H, and/or in the multiplexer.
VC
0.9995VS
0.9980VS
0.9000VS

2.3R C 6.2R C 7.6R C t

A Simple Form of Charging


Sample and Hold Characteristic of
Circuit Sample & Hold

Sensors and Embedded Systems – David Wilson 219


Some Common Types of ADC.

• Single slope integration


• Counter Ramp
• Flash ADC
• Successive approximation

Sensors and Embedded Systems – David Wilson 220


Single slope integration

• Start to charge a capacitor at


constant current Vin

• Count clock ticks during this time


• Stop when the capacitor voltage
reaches the input
Counting time

•Cannot reach high resolution


•Capacitor tolerance

Sensors and Embedded Systems – David Wilson 221


Counter – Ramp Converter (1)
• The counter is reset to zero
• A clock signal increments the counter until the reference voltage
generated by the D-A converter is greater than the analogue input
• The output of the comparator goes to a logic 1, which notifies the control
logic the conversion has finished
• The value of the counter is output as the digital value

Sensors and Embedded Systems – David Wilson 222


Counter – Ramp Converter (2)

• A drawback of the counter- conversion


request

ramp converter is the comparitor


output
length of time required to
convert large voltages d.c input voltage

D-A converter
• Must assume the worst output

case when calculating


conversion times 0 1 2 3 4 5 6 6 6 6 6 6 counter output

clock

Sensors and Embedded Systems – David Wilson 223


Flash ADC (1)

• Direct measurement with 2n-1


comparators
• Typical performance:
• 4 to 10-12 bits
• 15 to 300 MHz
• High power

Sensors and Embedded Systems – David Wilson 224


Flash ADC (2)

Advantages Disadvantages
• Simplest in terms of operational • Expensive
theory
• For each additional output bit, the
• Most efficient in terms of speed, number of comparators is doubled
very fast • i.e. for 8 bits, 256
• limited only in terms of comparators needed
comparator and gate propagation
delays

Sensors and Embedded Systems – David Wilson 225


Successive Approximation
ADC (1).
• A Successive Approximation Register (SAR) is added to the circuit.

• Instead of counting up in binary sequence, this register counts by trying all


values of bits starting with the MSB and finishing at the LSB.

• The register monitors the comparators output to see if the binary count is
greater or less than the analog signal input and adjusts the bits accordingly

Sensors and Embedded Systems – David Wilson 226


Successive Approximation ADC (2).
Offers a good compromise between speed, accuracy and cost. It requires
the input signal to be stable during a conversion, and hence is used with a
Sample & Hold.

Sensors and Embedded Systems – David Wilson 227


Successive Approximation Example.
• 8 Bit SAR ADC Vref
Vin
1V
0.425V
• Vref=1V

• Vin =0.425V

MSB LSB

Sensors and Embedded Systems – David Wilson 228


Successive Approximation Bit 7.
Set DAC MSB=1 (bit 7)
VDAC
VDAC = Vref =0.5V 0.5V

Compare Vref and VDAC


10000000

0.425<0.5  bit 7 =0

Sensors and Embedded Systems – David Wilson 229


Successive Approximation Bit 6.
Set Next DAC Bit (bit 6)=1 Vref
Vin VDAC
VDAC = Vref =0.25V 1V
0.425V 0.25V

Compare Vref and VDAC


01000000

0.425>0.25  bit 6 =1

MSB LSB
0 1

Sensors and Embedded Systems – David Wilson 230


Successive Approximation Bit 5.
Set DAC Bit 5=1 Vref
Vin VDAC
VDAC = Vref =0.375V 1V
0.425V 0.375V

Compare Vref and VDAC


01100000

0.425>0.375  bit 5 =1

MSB LSB
0 1 1

Sensors and Embedded Systems – David Wilson 231


Successive Approximation Bit 4.
Set DAC Bit 4=1 Vref
Vin VDAC
VDAC = Vref =0.4375V 1V
0.425V 0.4375V

Compare Vref and VDAC


01110000

0.425<0.4375  bit 4 =0

MSB LSB
0 1 1 0

Sensors and Embedded Systems – David Wilson 232


Successive Approximation Bit 3.
Set DAC Bit 3=1 Vref
Vin VDAC
VDAC = Vref =0.40625V 1V
0.425V 0.40625V

Compare Vref and VDAC


01101000

0.425>0.40625  bit 3 =1

MSB LSB
0 1 1 0 1

Sensors and Embedded Systems – David Wilson 233


Successive Approximation Bit 2.
Set DAC Bit2=1 Vref
Vin VDAC
VDAC = Vref =0.40625V 1V
0.425V 0.40625V

Compare Vref and VDAC


01101100

0.425>0.40625  bit 3 =1

MSB LSB
0 1 1 0 1 1

Sensors and Embedded Systems – David Wilson 234


Successive Approximation Bit 1.
Set DAC Bit 1=1 Vref
Vin VDAC
VDAC 1V
0.425V 0.4296875V
=

=0.4296875V 01101110

Vref =0.25V

Compare Vref and VDAC

0.425<0.4296875
 bit 1 =0
MSB LSB
0 1 1 0 1 1 0

Sensors and Embedded Systems – David Wilson 235


Successive Approximation Bit 0.
Vref
Vin VDAC
VDAC = 1V
0.425V 0.25V

01101101
=0.42578125V

Vref =0.25V

Compare Vref and VDAC

0.425< 0.42578125V
 bit 0 =0
MSB LSB
0 1 1 0 1 1 0 0

Sensors and Embedded Systems – David Wilson 236


Successive Approximation
Complete.
MSB LSB
0 1 1 0 1 1 0 0

=0.421875V

Successive Approximation ADC


0.6

0.5
0.5
0.4375 0.4296875 0.42578125
0.421875 0.421875
0.40625
0.4 0.375

0.3
0.25

0.2

0.1

0
1 2 3 4 5 6 7 8 9

Iteration Desired Value

Sensors and Embedded Systems – David Wilson 237


SAR ADC Review.

• Good trade-off between speed and cost

• Capable of outputting the binary number in serial format.

Sensors and Embedded Systems – David Wilson 238


ADC onto the Microcontroller.
• ADCs don’t easily integrate onto microcontrollers, mainly because there is
the risk of massive digital interference.

• Steps to improve performance include

– separate the ADC earth and supply from that of the microcontroller
– minimise interference during conversion - by synchronising
conversion to internal clock transitions and minimising all other
switching at this time.

• Ultimately, you will only find ADCs of limited resolution (generally 8- or 10-
bit) integrated onto a microcontroller.

Sensors and Embedded Systems – David Wilson 239


ADC’s on the PIC 18F25K22

AN 5-7 and AN20-27 not on PIC18F25K22


Sensors and Embedded Systems – David Wilson 240
The 18F25K22 ADC

Input multiplexer
AN 5-7 and AN20-27 Incorporates
not on PIC18F25K22 Sample and Hold

An external +ve and -


ve voltage reference
can be used.

Sensors and Embedded Systems – David Wilson 241


ADC Setup Without Interrupts.
[Link] Configuration: ANSELx and TRISx
[Link] Selection: A/D input channel (ADCON0)
[Link] Voltage: PVCFG and NGCFG (ADCON1)
[Link] Clock Source: A/D clock (ADCON2)
Acquisition time (ADCON2)
Turn on A/D (ADCON0)
5. Result Format: ADFM (ADCON2)
6. Start conversion: Set GO/DONE bit (ADCON0)
7. Wait for conversion: Poll the GO/DONE bit to be cleared
8. Read Result register: (ADRESH:ADRESL).
9. Wait of 2TAD is required before next acquisition starts.

Sensors and Embedded Systems – David Wilson 242


The ADCON0 Register
U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
— CHS<4:0> GO/DONE ADON
bit 7 bit 0
bit 7 Unimplemented: Read as ‘0’
bit 6-2 CHS<4:0>: Analog Channel Select bits
00000 = AN0
00001 = AN1
00010 = AN2
00011 = AN3
00100 = AN4
01000 = AN8
01001 = AN9 Remember only 1 actual
01010 = AN10
01011 = AN11 ADC so only one
01100 = AN12
01101 = AN13
conversion at a time
01110 = AN14
01111 = AN15
10000 = AN16
10001 = AN17
10010 = AN18
10011 = AN19
bit 1 GO/DONE: A/D Conversion Status bit
1 = A/D conversion cycle in progress. Setting this bit starts an A/D conversion cycle.
0 = A/D conversion completed/not in progress
bit 0 ADON: ADC Enable bit
1 = ADC is enabled
0 = ADC is disabled.

Sensors and Embedded Systems – David Wilson 243


The ADCON1 Register.
R/W-0 U-0 U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0
TRIGSEL — — — PVCFG<1:0> NVCFG<1:0>
bit 7 bit 0

bit 7 TRIGSEL: Special Trigger Select bit


1 = Selects the special trigger from CTMU
0 = Selects the special trigger from CCP5
bit 6-4 Unimplemented: Read as ‘0’
bit 3-2 PVCFG<1:0>: Positive Voltage Reference Configuration bits
00 = A/D VREF+ connected to internal signal, AVDD
01 = A/D VREF+ connected to external pin, VREF+
10 = A/D VREF+ connected to internal signal, FVR BUF2
11 = Reserved
bit 1-0 NVCFG<1:0>: Negative Voltage Reference Configuration bits
00 = A/D VREF- connected to internal signal, AVSS
01 = A/D VREF- connected to external pin, VREF-
10 = Reserved
11 = Reserved

Used to set up the ADC Reference Voltages

Sensors and Embedded Systems – David Wilson 244


The ADCON2 Register.
R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
ADFM — ACQT<2:0> ADCS<2:0>
bit 7 bit 0

bit 7 ADFM: A/D Conversion Result Format Select bit


1 = Right justified
0 = Left justified
bit 6 Unimplemented: Read as ‘0’
bit 5-3 ACQT<2:0>: A/D Acquisition time select bits.
001 = 2 TAD
010 = 4 TAD
011 = 6 TAD
100 = 8 TAD
101 = 12 TAD
110 = 16 TAD
111 = 20 TAD
bit 2-0 ADCS<2:0>: A/D Conversion Clock Select bits
000 = FOSC/2
001 = FOSC/8
010 = FOSC/32
100 = FOSC/4
101 = FOSC/16
110 = FOSC/64

Need to look at acquisition and conversion times before this SFR can be set.
Sensors and Embedded Systems – David Wilson 245
Typical Timing Requirements.
Configure & enable ADC

Select Multiplexer input These stages merge


if multiplexer forms
part of S&H
“Sample” Input Signal

Delay for signal acquisition

“Hold” Input Signal

Start Conversion

Delay for conversion


to complete

Read Data

Sensors and Embedded Systems – David Wilson 246


Analogue Input Model
Max 3kΩ (Section 17.4,
pg 300) but 10kΩ on next
page

From datasheet

TACQ= Amplifier settling time + capacitor charging time + temperature coefficient

Sensors and Embedded Systems – David Wilson 247


Acquisition Time Equations

Amplifier Hold Capacitor Temperature


TACQ = + +
Settling Time Charging Time Coefficient

TACQ = TAMP + TC + TCOFF

TAMP = 5μs – from datasheet

TC= –CHOLD (RIC + RSS + RS ) ln(1/2047)

TCOFF = [(Temperature - 25°C)(0.05µs/°C)]

Sensors and Embedded Systems – David Wilson 248


Acquisition Time Example
TACQ = TAMP + TC + TCOFF

TAMP = 5μs – from datasheet

TC= –CHOLD (RIC + RSS + RS ) ln(1/2047)


TC= –13.5pF (1kΩ + 100 + 10kΩ ) ln(1/2047)
TC= 1.1μs
TCOFF = [(Temperature - 25°C)(0.05µs/°C)]
TCOFF = 0μs
TACQ = 5μs + 1.1μs + 0μs

TACQ = 6.1μs
Sensors and Embedded Systems – David Wilson 249
ADC Clock Source

The A/D conversion time per bit is defined as TAD. The A/D conversion
requires 11 TAD per 10-bit conversion.

The source of the A/D conversion clock is software selectable. There are
seven possible options for TAD:
• 2 TOSC
• 4 TOSC
• 8 TOSC
• 16 TOSC
• 32 TOSC
• 64 TOSC
• Internal RC Oscillator Sensors and Embedded Systems – David Wilson 250
Conversion Time

Cannot be any shorter than 1.0µs


Sensors and Embedded Systems – David Wilson 251
Example

• For a given system based on a PIC 18F25K22 running from a 4MHz


crystal configure all registers associated with the ADC and start the first
conversion.

• The only analogue signal is connected to RA0


• The result is right justified

Sensors and Embedded Systems – David Wilson 252


How to Calculate Conversion Time

1
𝑇 𝑂𝑆𝐶=
𝐹𝑂𝑆𝐶 Minimum
conversion
time from
datasheet
So divide 1.0µs by 250ns = 4
For TAD to be a minimum time it needs to be at least
4xTOSC
𝐹 𝑂𝑆𝐶 Can only be
∴ 𝐹𝐴𝐷= divide by
4 2,4,8,16,32
Sensors and Embedded Systems – David Wilson 253
How to Calculate Acquisition Time

Minimum TACQ =6.1µs from previous example

Since TAD=4TOSC = 4x250ns = 1.0µs

Acquisition Time needs to be 8TAD

Sensors and Embedded Systems – David Wilson 254


Formatting the Result
The 10-bit result is stored in ADRESH and ADRESL.

ADC left justified, result will be dddddddd dd000000


ADC right justified, result will be 000000dd dddddddd
Sensors and Embedded Systems – David Wilson 255
Solution
- CHS4 CHS3 CHS2 CHS1 CHS0 Go/Done ADON
ADCON0
x 0 0 0 0 0 1 1 0x03
AN0 Channel Selected Not ON
started
Trigsel - - - PVCFG1 PVCFG0 NVCFG1 VCFG10 ADCON1
0 x x x 0 0 0 0 0x00

CCP5 Vdd Vss

ADFM - ACQT2 ACQT1 ACQT0 ADCS2 ADCS1 ADCS0 ADCON2


1 x 1 0 0 1 0 0 0xA4

Right Acquisition Time 8TAD Conversion Time FOSC/4

- CHS4 CHS3 CHS2 CHS1 CHS0 Go/Done ADON ADCON0


x 0 0 0 0 0 1 1

AN0 Channel Selected Started ON


Sensors and Embedded Systems – David Wilson 256
ADC Initialisation Code
void ADC_Initialize(void)
{
ANSELA = 0x01; // RA0 set to analogue
TRISA = 0x01; // RA0 set to input
ADCON0 = 0x00; // AN0; ADC enabled but not started
ADCON1 = 0x00; // TRIGSEL CCP5; VSS; VDD
ADCON2 = 0xA4; // ADFM left; ACQT 8; ADCS
// FOSC/4
ADRESL = 0x00; // Clear ADC results registers
ADRESH = 0x00;
ADCON0 = 0x01; // AN0 and ADC started
}

Sensors and Embedded Systems – David Wilson 257


Sample Code.

while (1)
{
__delay_us(7); //Wait the acquisition time ( 6.1us).
[Link] = 1; //start the conversion
while([Link]==1)
{
} //wait for the conversion to end
result = (ADRESH<<8)+ADRESL; //combine the 10 bits
//of the conversion
PORTB=result>>2; // use only the 8 most significant bits
}

Sensors and Embedded Systems – David Wilson 258


Some Notes About Sampling (1).
• 200Hz signal sampled at 2000Hz

Sensors and Embedded Systems – David Wilson 259


Some Notes About Sampling (2).
• 1000Hz signal sampled at 2000Hz

Sensors and Embedded Systems – David Wilson 260


Some Notes About Sampling (3).
• 2200Hz signal sampled at 2000Hz

This is aliasing

Sensors and Embedded Systems – David Wilson 261


Some Notes About Sampling (3).
• 2200Hz signal sampled at 2000Hz

This is aliasing

262
Next Lecture
Using Interrupts .

End of Lecture Note


Sensors and Embedded Systems – David Wilson 263
Sensors and
Embedded Systems -
10
Interrupts

Sensors and Embedded Systems – David Wilson 264


Interrupt vs Polling.

Interrupt Polling
• An interrupt is like being • The polling method is like
a shopkeeper. If someone a salesperson. The salesperson
needs a service or product, goes from door to door checking
they go to the shopkeeper to see if a product is required.
and state their needs. • Similarly, the controller keeps
• In case of interrupts, when monitoring the flags or signals
the flags are received, they one by one for all devices and
notify the controller that they provides service to whichever
need to be serviced. component that needs its service.
Sensors and Embedded Systems – David Wilson 265
Interrupt Overview.

When an Interrupt is detected by the CPU, it:

• Completes the current instruction,


• Stores (pushes) the address of the next instruction, onto the
stack (this is called the context),
The programmer will need to decide if any other data should be
stored such as accumulator, status registers etc.
• Jumps to an interrupt service routine (ISR), whose address is
determined by an "interrupt vector". The ISR is terminated when
a “return from interrupt” instruction is executed,
• Retrieves (pops) the context and reloads the Program Counter.
Sensors and Embedded Systems – David Wilson 266
Program Counter – A Reminder
Program Counter

• 21 bits wide from and holds the


memory address of the current
instruction being executed.

• As the program runs through the


instructions, the program counter
automatically increments to the next
instruction in line during execution of
the current instruction.
Sensors and Embedded Systems – David Wilson 267
The Stack – A Reminder

• Temporary memory
storage space used during Stack
the execution of a
program.

• The MPU uses a register


called the stack pointer,
similar to the program
counter, to keep track of
available stack locations.

Sensors and Embedded Systems – David Wilson 268


The Interrupt Vector – A Reminder
• The high priority (defaults)
interrupts location 008h and
the low priority at 018h.
• Once the execution reaches Interrupt
Vector
the ISR, the interrupt is
determined by polling the
interrupt flags and associated
code sequence is executed.
• After execution of code, the
flag bit must be cleared in
software to avoid recursion.
Sensors and Embedded Systems – David Wilson 269
Sources of Interrupts.

 Timers 0, 1, 2, 3
 Pins RB0, RB1, RB2 for external hardware interrupts INT0, INT1,
INT2
 PORTB-Change interrupt (any one of the upper four Port B pins)
 Serial communication’s USART interrupts: receive and transmit,
respectively
 ADC (analog-to-digital converter)
 CCP (compare capture pulse-width-modulation)

Sensors and Embedded Systems – David Wilson 270


More Interrupt Info.

• Many interrupts can be masked, ie disabled, by setting a bit in a


control register..
• Interrupt Flags are set whenever an associated interrupt occurs.
These record the fact that an interrupt has occurred, even if the
CPU is unable to respond to it.
• An Interrupt that has occurred, but has not received CPU response,
is called a Pending Interrupt.
• In the case of several interrupts, one ISR is completed before the
next interrupt is responded to.
Sensors and Embedded Systems – David Wilson 271
The Interrupt Control Registers (1).

• INTCON, INTCON2, INTCON3


• Various enable, priority and flag bits
• PIR1, PIR2, PIR3, PIR4, PIR5
• Individual flag bits for the peripheral interrupts
• PIE1, PIE2, PIE3, PIE4, PIE5
• Individual enable bits for the peripheral interrupts. IPR1, IPR2,
IPR3, IPR4, IPR5
• Individual priority bits for peripherals. Using the priority bits
requires the Interrupt Priority Enable (IPEN) bit be set
• RCON
• Reset Control Register
Sensors and Embedded Systems – David Wilson 272
The Interrupt Control Registers (2).

• In general, interrupt sources have three bits to control their


operation.

• Enable bits: To enable a specific interrupt request.


• Priority bits: To set as High or Low.
• Flag bits: Set when interrupt request is received.

Sensors and Embedded Systems – David Wilson 273


The 18F25K22 INTCON Register

Sensors and Embedded Systems – David Wilson 274


The 18F25K22 INTCON2 Register

RBPU

Sensors and Embedded Systems – David Wilson 275


The 18F25K22 INTCON3 Register

Sensors and Embedded Systems – David Wilson 276


Peripheral Interrupt Request
(PIR1)

Contains the
individual flag bits
for the peripheral
interrupts.

Sensors and Embedded Systems – David Wilson 277


Peripheral Interrupt Enable (PIE)

• When IPEN = 0, the PEIE


bit must be set to enable
any of these peripheral
interrupts.

• Contains the individual


enable bits for the
peripheral interrupts.

Sensors and Embedded Systems – David Wilson 278


The Interrupt Priority

There are two interrupt vectors, high priority and low. All interrupts but
one can be allocated to high or low priority.
The one source that is not prioritised is the external interrupt 0. This is
always high priority and is labeled as such in the diagram.
It is possible to enable or disable the whole prioritisation process. This
is done by IPEN, the Interrupt Priority Enable bit. IPEN is the msb in the
RCON register.

Sensors and Embedded Systems – David Wilson 279


Interrupt Priority Register1 (IPR1)

• Using the priority


bits requires that
the Interrupt
Priority Enable
(IPEN) bit be set.
• Contains the
individual priority
bits for the
peripheral
interrupts.
Sensors and Embedded Systems – David Wilson 280
Summary of PIE/PIR/IPR

Sensors and Embedded Systems – David Wilson 281


Basic Steps
• Set the (Global Interrupt GIE)
• Set (Peripheral Enable Interrupt PEIE )
• Set the Flag and Enable bits for that interrupt
• (eg timers, ADC, CCP, IOC, etc ).
Interrupt Flag Bit Register Enable Bit Register
Timer0 TMR0IF INTCON TMR0IE INTCON
Timer1 TMR1IF PIR1 TMR1IE PIE1
Timer2 TMR2IF PIR1 TMR3IE PIE1
Timer3 TMR3IF PIR3 TMR3IE PIE2
IOC RBIF INTCON RBIE INTCON
Sensors and Embedded Systems – David Wilson 282
A Simple Generic Interrupt Structure

Other
replicated for all other
maskable
maskable interrupts
interrupts Global Interrupt Enable*

Interrupt X Enable*

Interrupt X
S Q Interrupt
inputs to
(reset by CPU R Interrupt CPU
or program) Flag*
Non-maskable
Interrupt
* bits in a Special Function Register

Sensors and Embedded Systems – David Wilson 283


The 18F25K22 Interrupt Logic
External
Interrupt
Sources, and
Timer 0

Generalised
Pattern for High Activates
Priority Peripheral High
Interrupt Priority
Vector
Priority
Steering
Logic

Activates
Low Priority
Vector
Generalised
Pattern for Low
Priority Peripheral
Interrupt

Sensors and Embedded Systems – David Wilson 284


Interrupt Latency

The delay between the interrupt occurring, and the CPU response.

incoming interrupt detected Response to interrupt starts

Sensors and Embedded Systems – David Wilson 285


Summary of Interrupts

A number of distinct and important actions must be taken in order


interrupts to work successfully on the PIC18F Series of
microcontrollers.
• The interrupt must be enabled and allocated to the desired priority.
• The ISR must be located in program memory at the right start
address,
• Context saving must be managed.

Sensors and Embedded Systems – David Wilson 286


A Multi-Tasking Program Structure

Initialisation

Routine task A Event-driven Interrupt(s)

Routine task B
Timer-based Interrupt(s)
Routine task C
Timed task X

Timed task Y

Timed task Y
Sensors and Embedded Systems – David Wilson 287
Do I Need Interrupts?

• You shouldn’t aim to use interrupts until you are a confident C


programmer. They do what they say (i.e., they interrupt!), and a
programme interruption at the wrong place/time can cause immense
problems.

• In terms of the assignment, you don’t particularly need to use


interrupts. However, if you are ambitious and confident in C
programming, it can be interesting to incorporate one or two.

Sensors and Embedded Systems – David Wilson 288


Simple XC8 Code with Interrupts (1)

// File: Interrupt test.c Author: jeng548

unsigned long int milliseconds;// milliseconds device been on

void main(void)
{
TMR0ON = 1; // enable Timer 0
TMR0IE = 1; // enable Timer 0's interrupt
GIE = 1; // enable general interrupts
while (1) { } // main loop
}
Sensors and Embedded Systems – David Wilson 289
Simple XC8 Code with Interrupts (2)

void interrupt high_priority myHiIsr(void) // ISR


{
if (TMR0IF&& TMR0IE) // if Timer 0's interrupt
// flag and enable set
{
milliseconds++; // update counter
TMR0IF = 0; // clear flag
}
}
Could be low_priority or high priority
Sensors and Embedded Systems – David Wilson 290
Alternative Syntax

void __interrupt (high_priority) myHiIsr(void) // ISR


{
if (TMR0IF&& TMR0IE) // if Timer 0's interrupt flag and enable
set
{
milliseconds++; // update counter
TMR0IF = 0; // clear the interrupt flag
}
}
Good practice to check both flag and enable bits.
Never re enable interrupts within ISR.
Sensors and Embedded Systems – David Wilson 291
Remember This ( Lecture 6)?
void __interrupt(high_priority) Timer1_ISR(void)
{
if (TMR1IF && TMR1IE) // if Timer 1's interrupt flag and enable set
{
TMR1H=0xB1; // Reload timer values
TMR1L=0xE0;
TMR1IF = 0; // clear the interrupt flag
LATAbits.LATA5 = 0;
}
if (CCP5IF && CCP5IE) // if CCP5's interrupt flag and enable set
{
LATAbits.LATA5 = 1;
CCP5IF=0; // clear the interrupt flag
}
}

Sensors and Embedded Systems – David Wilson 292


Next Lecture
Serial Communications

End of Lecture Note


Sensors and Embedded Systems – David Wilson 293

You might also like