You are on page 1of 425

TRƯỜNG ĐẠI HỌC BÁCH KHOA

KHOA CƠ KHÍ
BỘ MÔN CƠ ĐIỆN TỬ

KỸ THUẬT
VI ĐIỀU KHIỂN PIC
Firma
(Dành cho sinh viênconvenzione
ngành Kỹ thuật Cơ điện tử)
Politecnico diNăm
Milano e Veneranda
học 2023 – 2024 Fabbrica
del Duomo di Milano
Aula Magna – Rettorato
Mercoledì 27 TS. Đặng
maggio Phước Vinh
2015

Email: dpvinh@dut.udn.vn
2
Content (2 credits)
1. Introduction

2. Hardware Configuration

3. Instructions

4. Timer Modules

5. Interrupt Operation

6. Analog-Digital-Converter (ADC) Module

7. Serial Comunication
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
3
Evaluation
▪ 6 groups: presentation with 6 topics
▪ Evaluation: Process + Mid-term + Final Exam
▪ Percentage :
✓ Process: 30% → Diligence 15% + Report 15%
▪ -2.0 points for one absent
▪ 05 absences/no report → No final exam
✓ Mid-term: 20%
✓ Final exam: 50%
▪ Mid-term (45 min) + Final (60 min): Written exam
✓ No using class documents
✓ “Liêm chính học thuật”
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
4
Liêm chính học thuật
▪ Đình chỉ học tập 6 tháng: mang phương tiện kỹ thuật mang
tin, truyền - nhận tin (như điện thoại, máy ảnh, đồng hồ thông
minh,...) vào phòng thi
▪ Đình chỉ học tập 12 tháng: đi thi hộ hoặc nhờ người khác thi
hộ, làm bài hộ đối với trường hợp vi phạm lần thứ nhất; người
học sử dụng phương tiện kỹ thuật mang tin, truyền - nhận tin
trong thời gian thi.
▪ Buộc thôi học: đã bị kỷ luật với hình thức “Đình chỉ học tập 6
tháng” hoặc “Đình chỉ học tập 12 tháng” và sau đó phạm lỗi có
mức độ “Đình chỉ học tập 6 tháng” hoặc “Đình chỉ học tập 12
tháng”; sử dụng giấy tờ giả mạo và nhờ thi hộ; tổ chức thi hộ; tổ
chức làm giả các giấy tờ liên quan đến kỳ thi.
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
5
Topics
1. 7-segment LED: 1÷4 LED, with/without IC
2. Buttons, Matrix button and LCD display
3. DC Motor
4. Step Motor *
5. Loadcell using HX711
6. I2C communication

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


6
Notes for slide
1. Use Standard type with ratio of 4:3 (at classroom)

2. White background, dark forecolor (black)

3. Font size > 24 (Times New Roman)

4. Do not use too much animation effect

5. Do not use long sentences


→ Present under the main ideas (with animation)

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


7
References
1. Datasheet of PIC

2. CCS C Compiler
3. Vi xử lý. Nguyễn Đình Phú, Trường Đại học Sư phạm Kỹ thuật
TP. Hồ Chí Minh.
4. Related websites
5. “Giáo trình kỹ thuật vi điều khiển PIC”. Đặng Phước Vinh, Võ
Như Thành. NXB Xây dựng, 2019.
6. “Lập trình vi điều khiển PIC và thiết bị ngoại vi”. Đặng Phước
Vinh, Trần Quang Khải, Đoàn Lê Anh, Võ Như Thành, Phạm
Anh Đức. NXB Khoa học và kỹ thuật, 2022.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


2019 20218

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


9
Software

PICKit 3 HyperTerminal

Virtual Serial Port Driver


(Eltima Software) Faculty of Mechanical Engineering
Dr. Dang Phuoc Vinh
10
Software

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


11
Proteus – Schematic

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


12
Proteus – Layout

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


13
Proteus – 3D

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


14
Altium Designer – 3D

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


15
Altium Designer – 3D

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


16
Role
1. Microcontroller Practice
2. PBL3

3. Workshop 2

4. PBL4-5

5. Final Project

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


17
PBL3

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


18
Workshop 2

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


19
Symbols
Nguồn Ground/Masse

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


20
Analog vs. Digital
▪ Analog: Điện tử tương tự
▪ Digital: Điện tử số
✓ 0V - 0.8V → “0” / Low
✓ 2.7V - 5V → “1” / High

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


21
Analog vs. Digital

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


22
3 kinds of Number
▪ Binary number (base-2)
→ Only “0” and “1”
▪ Decimal number (base-10)
→ The decimal or “denary” counting system uses the Base-
of-10 numbering system where each digit in a number
takes on one of ten possible values, called “digits”,
from 0 to 9
▪ Hexadecimal number
→ Hexadecimal Numbers group binary numbers into sets of
four allowing for the conversion of 16 different binary
digits
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
23
Binary to Decimal
▪ Base-2 to Base-10
▪ Decimal, base-10 or denary numbering system
▪ Important concept to understand as the binary
numbering system forms the basis for all computer and
digital systems
▪ The decimal or “denary” counting system uses the
Base-of-10 numbering system where each digit in a
number takes on one of ten possible values, called
“digits”, from 0 to 9, eg. 21310

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


24
Binary to Decimal
Most Least
Significant Bit Significant Bit

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


25
Binary to Decimal
Binary number: 101100101 → Decimal number ?

(256) + (64) + (32) + (4) + (1) = 35710

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


26
Binary to Decimal
Decimal number: 29410 → Binary number ?
Repeated Division-by-2 Method

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


27
Binary to Hexadecimal
▪ Hexadecimal Numbers group binary
numbers into sets of 4-bit allowing
for the conversion of 16 different
binary digits
▪ The “Hexadecimal” or simply “Hex”
numbering system uses the Base of
16 system
▪ There are 16 possible digit symbols
▪ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


28
Binary to Hexadecimal
Binary number: 1101 0101 1100 11112
→ Hexadecimal number: D5CF

Binary number: 11 0010 1101 10012


→ Adding of Additional 0’s to a Binary Number

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


29
Binary Coded Decimal
▪ Binary Coded Decimal, or BCD, is another process for
converting decimal numbers into their binary
equivalents

BCD 8421
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
30
Analog vs. Digital

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


31
Leader vs. Follower

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


Chapter 1

Introduction
Firma convenzione
Politecnico di Milano e Veneranda Fabbrica
del Duomo di Milano
Aula Magna – Rettorato
Mercoledì 27 maggio 2015
33
Microprocessor
✓ CPU for computers
✓ Without RAM, ROM, I/O on CPU chip
✓ Example: Intel’s x86, Motorola’s 680x0
DATA BUS

CPU
I/O SERIAL
Micro RAM ROM
PORTS
TIMER
PORTS
Processor

Dr. Dang Phuoc VinhADDRESS BUSFaculty of Mechanical Engineering


34
Microcontroller
✓ Mini computer
✓ With RAM, ROM, I/O ports on CPU chip
✓ Example: Intel’s 8051, Zilog’s Z80, & PIC 16X

CPU RAM ROM


Integrated on
I/O SERIAL 1 chip
TIMER
PORT PORTS

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


Crystal Microprocessor 35
RAM

ADC Memory
Crystal SPI
USART T0 T1 T2 RAM
0 – 20Mhz I2C SFR
(368 byte)
Internal Serial Timers
Crystal Communication
Program Memory
(8k)

CPU EEPROM
CCP1 , CCP2 35 instructions (256 byte)
ADC
Module PWM
Memory
CCP/PWM Interrupt WDT
Vref
Modules
RESET

Port A Port B Port C Port D Port E Supply Voltage


2 – 5.5 VDC
I/O Ports (25mA)

Microcontroller
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
36
CPU

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


37
Comparison
Microprocessor Microcontroller
Single chip CPU, RAM, ROM, I/O and Timer are
External RAM, ROM, I/O, Timer located on one chip

Changeable storage capacity of Fixed storage capacity of ROM,


ROM, RAM, I/O Ports RAM, I/O Ports

Expensive Suitable for applications:


▪ Cheap
▪ Less consumption
▪ Small space

Multipurpose Single purpose

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


38
How can choose Microcontroller
1. Meet the requirement and cost
✓ Speed, memory capacity, I/O ports, timers, size, package,
power consumption
✓ Easy updating
✓ Price

2. Tools for software development


✓ Debug, C compiler, simulation, technical support

3. Reliable Suppliers

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


39
Microcontroller Types

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


40
8051 and PIC
▪ Intel – 1981 ▪ Microchip – 1976
▪ 01CDT – 13CDT ▪ 14CDT – now…

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


41
PIC Microcontroller

✓ Programmable Intelligent
Computer
✓ PIC made by Microchip
Technology
✓ PIC1650 originally developed
by General Instrument's
Microelectronics Division
✓ PIC 8-bit was developed in
1976

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


42
PIC Microcontroller
✓ Easy to buy in Vietnam

✓ Cheap price

✓ Large community → large document, open source →


easy to discussion, study…

✓ Supporting of manufacturer about complier, program


tools, program upload…

✓ Features are updated day by day

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


43
Price

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


44
PIC Types
Symbol of PIC microcontroller:
PIC12xxxx: 12-bit instructions
PIC16xxxx: 14-bit instructions
PIC18xxxx: 16-bit instructions

C: PIC with EPROM program memory (EEPROM only on 16C84)


F: PIC with Flash program memory
LF: PIC with Flash program memory and low-voltage operation

✓ Microcontroller with xxFxxx symbol → program memory is


EEPROM if “A” at the end position → Flash type
✓ PIC16F877 is EEPROM, PIC16F877A is Flash.
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
45
PIC Family

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


46
Memory Types
ROM (Read-Only Memory)
▪ Non-volatile memory: data stored in ROM still available even
though no power supply.
▪ Storing program code of operation system and default data
of system
▪ Read only and only one-time programed

EPROM (Erasable Programmable Read-Only Memory)


▪ Non-volatile memory: data stored in ROM still available even
though no power supply
▪ Erasable memory only with special device. Fully delete
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
47
Memory Types
EEPROM (Electrically Erasable Program
mable Read-Only Memory)
▪ Can be erased and re-programmed; but low
speed

Flash memory
▪ One kind of EEPROM
▪ Can be erased and re-programmed
▪ Can be read/write with different sector

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


48
Memory Types
Loss data Erase
Size
Type if no Write? many Speed Price
Erase ?
power? times?
ROM No No No High Inexpensive
Yes, but
EPROM
need special Full High Inexpensive
equipment
No
EEPROM Byte Limitation High for Expensive
read
Yes Slow for
Flash Sector erase and Inexpensive
write

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


49
Compiler Program
There are 2 kinds of programming language:
• Low-level programming language: MPLAB
• High-programming language (C language): CCS, HTPIC,
PIC BASIC…

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


50
Programming Languages

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


51
MPLAB Compiler
✓ Free complier from Microchip

✓ Help students to deeply understand structure of PIC

✓ Optimization of program memory.

✓ Much faster than high-level languagues

✓ However, assembly language is hard to learn and few


support.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


52
MPLAB Compiler

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


53
CCS Compiler
✓ C language → familiar with students
✓ Built-in useful functions for PIC: ADC,
PWM, RS232, SPI
✓ Can combine with assembly language
✓ Flexible syntax and easy to learn
✓ Easy for developing and updating
applications
✓ Useful features are updated day by day.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


54
CCS Compiler

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


55
CCS Compiler
Create a .HEX file

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


56
HEX File

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


57
From PC to MCU

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


58
From PC to MCU to Robot

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


59
Connect PICkit – Computer
PICkit
Software

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


60
PICkit 2

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


61
PICkit 2 – Price

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


62
PICkit 3

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


63
PICkit 3 – Price

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


64
PICkit 4 – Price

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


65
Practice Board
PICkit 2

Chân nạp

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


66

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


Chapter 2
Hardware Configuration
Firma convenzione

PIC 16F877A
Politecnico di Milano e Veneranda Fabbrica
del Duomo di Milano
Aula Magna – Rettorato
Mercoledì 27 maggio 2015
68
Overview
✓ Belong to PIC16Fxxx family with instruction set has 35
instructions.
✓ The execution time is the same for almost all instructions, and
lasts 4 clock cycles which is stabilized by a quartz crystal.
✓ The exceptions to the rule are jump and branch instructions the
execution time of which is 2 instruction cycles.

If a 4 MHz crystal is used


→ frequency of one
instruction is 1 MHz
(cycle is 1 µs)

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


69
Overview
✓ Flash program memory with capacity of 8K × 14 bit, can be
read/write up to 100.000 times
✓ RAM Memory size of 368 byte
✓ EEPROM Memory:
▪ Size of 256 byte
▪ Can be read and written up to 1.000.000 times
▪ Data can be stored up to 40 years
✓ Supply power: 5 VDC
✓ SLEEP mode for saving power usage
✓ Five I/O ports with 33 pins, namely A, B, C, D, E

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


70
PIC16F87XA Devices

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


71
PIC16F87XA Pinout

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


72

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


73
PIC16F87XA Pinout
Reset

Port A Port B

Port E Power
Power
Port D
Oscillator

Port C Port C

Dr. Dang Phuoc Vinh PortofDMechanical Engineering


Faculty
74
Basic Elements
Power Clock

Motor

Program
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
75
Voltage vs. Frequency
Voltage

Frequency
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
76
𝐌𝐂𝐋𝐑 /Vpp
𝐌𝐂𝐋𝐑 /Vpp (1)
✓ 𝐌𝐂𝐋𝐑 : Reset input,
low-active
✓ Have a noise filter
✓ The filter will detect
and ignore small pulses

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


77
𝐌𝐂𝐋𝐑 /Vpp
𝐌𝐂𝐋𝐑 /Vpp (1)
✓ 𝐌𝐂𝐋𝐑 : Reset input,
low-active
✓ Have a noise filter 𝐌𝐂𝐋𝐑

✓ The filter will detect


and ignore small pulses

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


78
𝐌𝐂𝐋𝐑 /Vpp
𝐌𝐂𝐋𝐑 /Vpp (1)
✓ Vpp: Programing voltage output → connect with pin #1 of
the PICkit

PICkit 3

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


79
I/O Port Fuctions
RA0(1)/AN0(1) (2, 3)
✓ RA0(1): Digital Input/Output
✓ AN0(1): Analog input of 0 (1) channel

RA2/AN2/VREF-/CVREF (4)
✓ RA2: Digital Input/Output
✓ AN2: Analog input of 2nd channel
✓ VREF-: ADC voltage reference (low)
✓ CVREF: Comparator voltage reference
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
80
I/O Port Fuctions
RA3/AN3/VREF+ (5)
✓ RA3: Digital Input/Output
✓ AN3: Analog input of 3rd channel
✓ VREF+: ADC voltage reference (high)

RA4/T0CKI/C1OUT (6)
✓ RA4: Digital Input/Output
✓ T0CKI: Input of external clock Timer 0
✓ C1OUT: Output of comparator #1

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


81
I/O Port Fuctions
RA5/AN4/𝐒𝐒/C2OUT (7)
✓ RA5: Digital Input/Output
✓ AN4: Analog input of 4th channel
✓ 𝐒𝐒: Slave select in SPI mode
✓ C2OUT: Output of comparator #2

RE0/𝐑𝐃/AN5 (8)
✓ RE0: Digital Input/Output
✓ 𝐑𝐃: Read in parallel slave port
✓ AN5: Analog input of 5th channel

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


82
I/O Port Fuctions
RE1/𝐖𝐑/AN6 (9)
✓ RE1: Digital Input/Output
✓ 𝐖𝐑: Write in parallel slave port
✓ AN6: Analog input of 6th channel

RE2/𝐂𝐒/AN7 (10)
✓ RE2: Digital Input/Output
✓ 𝐂𝐒: Chip select in parallel slave port
✓ AN7: Analog input of 7th channel

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


83
Voltage Supply Pins

Multiple power pins on


a small microcontroller

VDD (11, 32)


VSS (12, 31)

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


84
Voltage Supply Pins
▪ The typical reason for
multiple power pins on
a small microcontroller
is that one of the power
pins feeds the analog
section of the chip.
▪ By keeping analog
power and digital
power separate, noise
in the analog section can
be reduced.
▪ Digital noise on the
power supply can cause
inaccurate ADC readings
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
for example
85
Power Supply

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


86
Power Supply

10 Ohm/5W

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


87
DC Power Supply

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


88
DC Power Supply

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


89
Crystal Osc.
The external oscillator in LP, XT and HS modes uses the external oscillator within the
microcontroller as a clock source. The clock frequency depends on the quartz crystal
or ceramic resonators connected to OSC1 and OSC2 pins.
• LP designed to drive only 32.768 kHz crystals usually embedded in quartz
watches. The current consumption is the least of the three modes.
• XT mode is used for intermediate-frequency quartz crystals up to 8 MHz.
• HS mode is used for high-frequency quartz crystals over 8 MHz. The current
consumption is the highest of the three modes.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


90
Oscillator
OSC1/CLKIN (13)
OSC2/CLKOUT (14)
→ Connecting to crystal device to create oscillation for PIC
→ Adding 2 capacitors C1, C2 to obtain stable oscillation
→ See datasheet for recommended values

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


91
Capacitor Selection
Crystal Freq. Cap. Range C1 Cap. Range C2
1 MHz 15 pF 15 pF
4 MHz 15 pF 15 pF
8 MHz 15-33 pF 15-33 pF
20 MHz 15-33 pF 15-33 pF

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


92
Crystal Osc.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


93
Crystal Osc.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


94
PIC16 Oscillator Options
XT Standard frequency crystal oscillator 100kHz - 4MHz
HS High frequency crystal oscillator 4MHz - 20MHz
LP Low frequency crystal oscillator 5kHz - 200kHz
RC External RC oscillator DC - 4MHz
INTRC Internal RC oscillator 4 or 8 MHz  2%

Selectable clock options provide greater flexibility for the designer:


– LP Oscillator designed to draw least amount of current
– RC or INTRC provide ultra low cost oscillator solution
– XT optimized for most commonly used oscillator frequencies
– HS optimized to drive high frequency crystals or resonators

Speed ranges are guidelines only

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


95
I/O Port Functions
RC0/T1OSO/T1CKI (15)
✓ RC0: Digital Input/Output
✓ T1OSO: Output of Timer 1
✓ T1CKI: Input of external clock of Timer 1

RC1/T1OSI/CCP2 (16)
✓ RC1: Digital Input/Output
✓ T1OSI: Input of Timer 1
✓ CCP2: Input of Capture 2, Output of
Compare 2, Output of PWM 2

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


96
I/O Port Functions
RC1/T1OSI/CCP2 (16)
✓ RC1: Digital Input/Output
✓ T1OSI: Input of Timer 1
✓ CCP2: Input of Capture 2, Output of
Compare 2, Output of PWM 2

RC2/CCP1 (17)
✓ RC2: Digital Input/Output
✓ CCP1: Input of Capture 1, Output of
Compare 1, Output of PWM1

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


97
I/O Port Functions
RC3/SCK/SCL (18) RC4/SDI/SDA (23)
✓ RC3: Digital Input/Output ✓ RC4: Digital Input/Output
✓ SCK: Output in SPI mode ✓ SDI: Input in SPI mode
✓ SCL: Serial Clock Line in ✓ SDA: Serial Data Line in
the I2C mode the I2C mode

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


98
I/O Port Functions
RDx/PSPx (19, 20, 21, 22, 27-30)
✓ RDx: Digital Input/Output
✓ PSPx: Data of parallel slave port

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


99
I/O Port Functions
RC6/TX/CK (25) RC7/RX/DT (26)
✓ RC6: Digital Input/Output ✓ RC7: Digital Input/Output
✓ TX: Transmit in USART ✓ RX: Receive in USART
✓ CK: Synchronous pulse in USART ✓ DT: Data in USART

RC5/SDO (24)
✓ RC5: Digital Input/Output
✓ SDO: Output in SPI mode

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


100
I/O Port Functions
RB0/INT (33)
✓ RB0: Digital Input/Output
✓ INT: External interrupt input

RB1, RB2, RB4, RB5 (34, 35, 37, 38)


✓ Digital Input/Output

RB3/PGM (36)
✓ RB3: Digital Input/Output
✓ PGM: Low-Voltage Programming
function

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


101
I/O Port Functions

RB6/PGC (39)
✓ RB6: Digital Input/Output
✓ PGC: Clock transmit data to the PIC micro

RB7/PGD (40)
✓ RB7: Digital Input/Output
✓ PGD: Data transmit to the PIC micro

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


102
Peripheral Characteristics
✓ Master Synchronous Serial Port (MSSP)
▪ Serial Peripheral Interface (SPI)
▪ Inter-Integrated Circuit (I2C)

✓ Asynchronous Mode USART

✓ Parallel communication PSP

✓ ADC module with 8 channels has 10-bit digital number

✓ Can be operated with some different oscillator

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


103
Peripheral Characteristics
✓ 3 Timer Modules
▪ Timer 0: Timer/counter 8 bit, Prescale
▪ Timer 1: Timer/counter 16 bit, Prescale, can work in
SLEEP mode with internal/external clock
▪ Timer 2: Timer/counter 8 bit, Prescaler and Postscaler

✓ 2 CCP Modules (Capture/Compare/PWM)


▪ 16-bit Capture register
▪ 16-bit Compare register
▪ 10-bit PWM

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


104

CrystalđồSPI
0 – 20Mhz
khối
I2C
USART T0 T1 T2 RAM
SFR
(368 byte)
Internal Serial Timers
Crystal Communication
Program Memory
(8k)

CPU EEPROM
CCP1 , CCP2 35 instructions (256 byte)
ADC
Module PWM
Memory
CCP/PWM Interrupt WDT
Vref
Modules
RESET

Port A Port B Port C Port D Port E Supply Voltage


2 – 5.5 VDC
I/O Ports (25mA)
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
105
Memory: Harvard Architecture
Von Neumann
Architecture Von Neumann Architecture:
▪ Fetches instructions and data from a
single memory space
▪ Limits operating bandwidth
8-bit Program
Bus & Data
Memory
CPU

Harvard
Architecture
Harvard Architecture:
▪ Uses two separate memory spaces for
8-bit Data program instructions and data
Bus Memory
CPU ▪ Improved operating bandwidth
14-bit
Bus ▪ Allows for different bus widths
Program
Memory

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


106
Program Memory
▪ Flash memory with 8K word
(1 word = 14 bit)
▪ Multipage: page 0 - page 3
▪ The reset vector is 0000h.
▪ Interrupt vector is 0004h.
▪ 13-bit program counter
capable of addressing an
8K word × 14 bit program
memory space
▪ Program memory can stores
8×1024 = 8192 instructions
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
107
Program Counter (PC)
PCH PCL
12 11 10 9 8 7 6 5 4 3 2 1 0
Program Counter 0 0 0 0 0 0 0 0 0 0 0 0 0

▪ 13-bit PC can access up to 213 = 8192 words


▪ Contains address of NEXT instruction (pipelining)
▪ Lower byte accessible in data memory as PCL
▪ Upper byte indirectly accessible via PCLATH
▪ Runs freely across page boundaries
▪ Events that modify PC out of sequence:
– Interrupts
– Instructions: CALL, GOTO, RETURN, RETLW, RETFIE
– Any instruction that uses the PCL register as an operand
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
108
Stack
PCLATH

PCH<12:8> PCL PC<12:0>

CALL, RETURN,

8 Level Deep Stack


RETFIE, RETLW

Stack Level 1
– Stores the contents of the PC
• PUSHES
– CALL/Interrupt
• POPS Stack Level 8
– RETURN, RETFIE, RETLW
Program Memory

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


109
Data Memory

✓ EEPROM memory
✓ Divided in 4 banks.
✓ Each bank has 128 byte
▪ Special Function Registers
(SFR) located in low-
address memory

▪ General Purpose Registers


(GPR) located in
remaining registers

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


110
Data Memory Organization
368 Bytes of General Purpose RAM Plus Special Function Registers
000h 080h 100h 180h
SFR SFR
10Fh 18Fh
SFR SFR
110h 190h

01Fh 09Fh
020h 0A0h

128 Bytes

GPR GPR GPR GPR


96 Bytes 80 Bytes 96 Bytes 96 Bytes

0EFh 16Fh 1EFh


Accesses Accesses Accesses
07Fh 0FFh 70h – 7Fh 17Fh 70h – 7Fh 1FFh 70h – 7Fh
Bank 0 Bank 1 Bank 2 Bank 3

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


111
Data Memory Organization
Bank 0 Bank 1 Bank 2 Bank 3
000 INDF 080 INDF 100 INDF 180 INDF

001 TMR0 081 OPTION_REG 101 TMR0 181 OPTION_REG

002 PCL 082 PCL 102 PCL 182 PCL

003 STATUS 083 STATUS 103 STATUS 183 STATUS

004 FSR 084 FSR 104 FSR 184 FSR

005 PORTA 085 TRISA 105 185


006 PORTB 086 TRISB 106 PORTB 186 TRISB

007 PORTC 087 TRISC 107 187


008 PORTD 088 TRISD 108 188
009 PORTE 089 TRISE 109 189
00A PCLATH 08A PCLATH 10A PCLATH 18A PCLATH

00B INTCON 08B INTCON 10B INTCON 18B INTCON

00C PIR1 08C PIE1 10C EEDATA 18C EECON1


PIR2 PIE2 EEADR EECON2
Dr. Dang Phuoc
00D Vinh 08D Faculty of Mechanical
10D Engineering
18D
112
In CCS

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


113
Data Memory
▪ Some registers are
addressable across the
bank boundaries: STATUS
▪ These register can be
accessed in all blocks at
the corresponding address
in each bank
▪ Bank switching can be
minimized by the compiler
when assembling the
machine code, thus saving
program code space and
execution time

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


114
Status Register
IRP RP1 RP0 TO PD Z DC C

RP1 RP0
RP1
0 RP0
0 Bank 0
0 1 Bank 1
1 0 Bank 2
Contains: 1 1 Bank 3
– Arithmetic status of the ALU Indirect Register Bank Select bit:
– The RESET status (used for indirect addressing)
• 1 = Bank 2,3
– Bank select bits for data • 0 = Bank 0,1
memory

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


115
Long Word Instruction
8-bit Instruction on typical 8-bit MCU
Example: Freescale ‘Load Accumulator A’:
• 2 Program Memory Locations
• 2 Instruction Cycles to Execute
8-bit Program
Memory
ldaa #k ▪ Limits Bandwidth
1 0 0 0 0 1 1 0 ▪ Increases Memory Size
k k k k k k k k Requirements

14-bit Instruction on PIC16 8-bit MCU


Example: ‘Move Literal to Working Register’
• 1 Program Memory Location
14-bit Program • 1 Instruction Cycle to Execute
Memory movlw k
1 1 0 0 0 0 k k k k k k k k

▪ Separate busses allow different widths


▪ 2k x 14 is roughly equivalent to 4k x 8

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


116
Xuất nhập I/O
1 0 0 1 0 1 1 0 TRIS

Output
Output

Output

Output
CPU Input

Input
Input
Input
1 1 0 1 0 1 0 1 PORT

I/O Port: Bidirectional port


TRIS = 1: Input
▪ PORT: Port State
TRIS = 0: Output
▪ TRIS: Port Data Direction

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


117
TRIS & PORT

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


118
Port A
✓ Bidirectional port. 6-bit: RA0 – RA5
✓ Corresponding data direction register:
TRISA: 0: OUTPUT, 1: INPUT.
✓ Pin RA4 is multiplexed with the Timer0
module clock input to become the
RA4/T0CKI pin
✓ Other PORTA pins are multiplexed with
analog inputs and the analog VREF
input for both the A/D converters and
the comparators
✓ The user must ensure the bits in the
TRISA register are maintained set when
using them as analog inputs
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
119
Registers Associated with Port A

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


120
Port B
✓ Bidirectional port. 8-bit: RB0 – RB7
✓ Corresponding data direction register: TRISB.
✓ Each of the PORTB pins has a weak internal
pull-up. Control bit: 𝐑𝐁𝐏𝐔 (OPTION_REG<7>)
✓ 𝐑𝐁𝐏𝐔 = 0 → Enable internal pull-up resistor
✓ The weak pull-up is automatically turned off
when the port pin is configured as an output.
✓ The pull-ups are disabled on a Power-on Reset
✓ RB0/INT is an external interrupt input pin
✓ RB4 – RB7 have an interrupt-on-change

Dr.𝐑𝐁𝐏𝐔
Dang Phuoc Vinh
INTEDG T0CS T0SEFacultyPSA
of Mechanical
PS2 Engineering
PS1 PS0
121
Internal pull-up resistor
Pin with pull-up resistor Pin without pull-up resistor

PICmiro PICmiro
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
122
Bit 𝐑𝐁𝐏𝐔
𝐑𝐁𝐏𝐔 = 𝟎 → enable internal pull-up resistor
In CCS: port_b_pullups(1)

OPTION_REG

Dr. INTEDG
Dang Phuoc Vinh T0CS T0SEFacultyPSA PS2 Engineering
of Mechanical PS1 PS0
𝐑𝐁𝐏𝐔
123
Registers Associated with Port B

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


124
Port C
✓ Bidirectional port.
8-bit: RC0 – RC7
✓ Data direction
register TRISC
0: OUTPUT, 1: INPUT.
✓ Pins RC3 - RC4 are
multiplexed with the
SPI and I2C mode.
✓ Pins RC6-RC7 are
multiplexed with the
USART mode.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


125
Registers Associated with Port C

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


126
Port D
✓ Bidirectional port.
8-bit : RD0 – RD7
✓ Data direction
register: TRISD.
0: OUTPUT
1: INPUT.
✓ PortD is multiplexed
with the parallel
communication

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


127
Registers Associated with Port D

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


128
Port E

✓ Bidirectional port. 3-bit: RE0 – RE2


✓ Data direction register: TRISE.
0: OUTPUT, 1: INPUT.
✓ Port E is multiplexed with analog
input.
✓ The user must ensure the bits in
the TRISE register are maintained
set when using them as analog
inputs

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


129
Registers Associated with Port E

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


130
RESET Activities
PIC16F87XA has different RESET activities:
• Power-on Reset (POR)
• 𝑴𝑪𝑳𝑹 Reset (during normal operation)
• 𝑴𝑪𝑳𝑹 Reset (during Sleep)
• WDT Reset (during normal operation)
• WDT Wake-up (during Sleep) Page 149 in datasheet

• Brown-out Reset (BOR)

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


131
BOR Reset
▪ PIC has a circuit for brown out
reset built-in.
▪ A Brown-out Reset (BOR) is a
circuit that monitors the VDD level
during operation by comparing it
to a fixed threshold level.
▪ When VDD drops below the
threshold level, the BOR is
activated.
▪ When VDD rises again, the
controller is restarted after a
specified delay.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


132
BOR Reset
VDD
BVDD

72ms
Holds PICmicro® MCU Internal
Reset
in reset until ~72ms
VDD
after VDD rises back BVDD

above threshold 72ms


Internal
Reset <72ms

VDD
BVDD

72ms
Internal
Reset

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


133
RESET Activities

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


134
Registers status after RESET

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


135
Registers status after RESET

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


136
Registers status after RESET

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


137
SLEEP Mode
The processor can be put into a power-down mode by executing the
SLEEP instruction
– System oscillator is stopped
– Processor status is maintained (static design)
– Watchdog timer continues to run, if enabled
– Minimal supply current is drawn - mostly due to leakage (0.1 - 2.0A)
Events that wake processor from sleep
MCLR Master Clear Pin Asserted (pulled low)
WDT Watchdog Timer Timeout
INT INT Pin Interrupt
TMR1 Timer 1 Interrupt (or also TMR3 on PIC18)
ADC A/D Conversion Complete Interrupt
CMP Comparator Output Change Interrupt
CCP Input Capture Event
PORTB PORTB Interrupt on Change
Dr.SSP Synchronous
Dang Phuoc Vinh Serial Port (I2C Mode) Start
Faculty of/Mechanical
Stop Bit Detect Interrupt
Engineering
PSP Parallel Slave Port Read or Write
138
Programmable Low Voltage Detect
VDD LVDIN
• Early warning before brown out LVDCON

• 16 selectable trip points:

16-bit Multiplexer
– 1.8V up to 4.5V in 0.1 to 0.2V steps
– External analog input LVDIF

• Internal VREF

VREF
LVDIN

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


139
In-Circuit Serial Programming™
• Only two pins required for programming
• Convenient for In-System Programming of
– Calibration Data
– Serialization Data
• Supported by MPLAB® PM3 & ICD2
Application PCB VDD VDD

MCLR/VPP
Pin Function ICSP™ Connector
ICSP Connector

PIC16Fxxx
VPP Programming Voltage = 13V
VDD Supply Voltage VDD
VSS Ground VSS

RB6 Clock Input RB6

RB7 Data I/O & Command Input RB7

Isolation
To application circuit
circuits

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


Chapter 3
Instructions
Firma convenzione
Politecnico di Milano e Veneranda Fabbrica
del Duomo di Milano
Aula Magna – Rettorato
Mercoledì 27 maggio 2015
141
Flow Charts
Symbol Activity
Input

Process

Output

Decision

Flow lines

Procedure, Function…

Begin, End

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


Connector
142
Example

Draw.io

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


143
Variable Declaration
Syntax: <Data type> <Variable name>
Example: int a, b, c;

Variable type: ✓ Global variable ✓ Local variable


Symbol Explain Example
{} Begin/end of instruction(s) void main() { }
int a;
; End of one instruction
void NhapMang(int a[]);

//Nhap mang
// Comment with single line
void NhapMang(int a[]);
/* Dau tien nhap vao n.
/*
Comment with several lines Sau do nhap tung phan tu*/
*/
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
NhapMang(int a[], int &n);
144
Variable Declaration
Unsigned Signed
Type Storage Size
(Không dấu) (Có dấu)
1 bit
int1 true or false 0→1 Not available
(0 or 1)
Integer
int8 1 byte ( 8 bit)
0 → 255 -128 → 127

int16 Integer 16 bit 0 → 65535 -32768 → 32767


-2147483648 →
int32 Integer 32 bit 0 → 4294967295
2147483647
0→ -140737488355328 →
int48 Integer 48 bit
281474976710655 140737488355327
-9223372036854775808 →
int64 Integer 64 bit Not available
9223372036854775807
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
float32 Float 32 bit -1.5 × 1045 → 3.4 × 1038
145
Variable Declaration
Data Type in C Data Type in CCS
short int1
char unsigned int8
int int8
long int16
long long int32
float float32
double Not available

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


Operators 146

Arithmetic Operators
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Remainder after division (modulo division)

Relational Operators
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
!= Not equal to
Operators
147

Logical Operators
! NOT Logical NOT. True only if the operand is 0
&& AND Logical AND. True only if all operands are true
|| OR Logical OR. True only if either one operand is true
Increment and Decrement Operators
++ Increment Increment ++ increases the value by 1 whereas
-- Decrement decrement -- decreases the value by 1.
Bitwise Operators
& AND
| OR
^ XOR
<< Left shift
>> Right shift
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
~ Complement
148
Left Shift & Right Shift
Left Shift

A=4

B = A << 2

Right Shift

A=4

B = A >> 2

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


149
Ternary Operators
Conditional operators return one value if condition is true and
returns another value is condition is false. Symbol: “?:”
Syntax: <Condition>?< true_value >:< false_value>
This operator will give:
✓ true_value if condition is true
✓ false_value if condition is false

int a = 10, b = 20;


Max = (a>b)?a:b; → max = b = 20
Min = (a<b)?a:b; → min = a = 10
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
150
Change data type
Change the data type of one variable to any required data type
Syntax: (Data type) Variable name

int a = 9, b = 2;
int c = a/b; →c=5
float d = (float)a/b; → d = 4.5

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


151
if...else Statement
The if statement evaluates the test expression inside the parenthesis {}
if (test expression) if (test expression) if (test expression 1)
{ { code(s) } { code(s) 1}
code(s) else elseif (test expression 2)
} { code(s) } { code(s) 2}

Vào Vào
elseif (test expression n-1)
Sai Điều kiện
Sai { code(s) n-1}
Điều kiện
Đúng Đúng else

Khối lệnh Khối lệnh 1 Khối lệnh 2 { code(s) n}

Ra Ra
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
152
switch Statement
Similar with if…else…if
✓ Expression must be in an integer
switch (expression)
value (int, long…) or a char type
{
✓ If the statement has more than 2
case constant 1: statement;
instructions → put them in { }
break;
✓ Some keywords such as switch,
case constant 2: statement;
case, break must be in lowercase
break;
✓ Note: if no “break” after the ith
…………….
instruction → (i+1)th instruction
case constant n: statement;
will be executed.
break;
✓ No using “;” after switch
}

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


153
switch Statement
Vào
switch (expression)
Đúng
switch (biểu thức) Giá trị = 1? Lệnh/khối lệnh 1
{

case constant 1: statement; Sai break?

Không
break;
Đúng
Giá trị = 2? Lệnh/khối lệnh 2
case constant 2: statement;

break; Sai
break?

Không
…………….
Đúng
Giá trị = n? Lệnh/khối lệnh n
case constant n: statement;

break; break?
Sai
Không
}
Ra

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


154
switch Statement
switch (expression) ✓ Expression must be in an integer
{ value (int, long…) or a char type
case constant 1: statement; ✓ If the statement has more than 2
break; instructions → put them in { }
case constant 2: statement; ✓ Some keywords such as switch,
break; case, break must be in lowercase
……………. ✓ Note: if no “break” after the ith
case constant n: statement; instruction → (i+1)th instruction
break; will be executed.
default: statement; ✓ No using “;” after switch
break; ✓ If there is no match, the default
} statements are executed

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


155
switch Statement
switch (expression) Vào

{ switch (biểu thức) Giá trị = 1?


Đúng
Lệnh/khối lệnh 1

case constant 1: statement; Có


Sai break?
break; Không
Đúng
case constant 2: statement; Giá trị = 2? Lệnh/khối lệnh 2

break; break?

Sai
……………. Không
Đúng
Giá trị = n? Lệnh/khối lệnh n
case constant n: statement;
break; Sai
break?

Không
default: statement;
default: Lệnh/khối
break; lệnh n+1

} Ra

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


156
for Loop
for (initial Statement; test Expression ; update Statement) #include <stdio.h>
void main()
{ {
code(s) int i;
for (i = 1; i <= 10; i++)
} {
printf ("%-5d", i);
}
▪ The initialization statement is executed only once. }
▪ If the test expression is evaluated to false, the for loop is terminated.
▪ If the test expression is evaluated to true, statements inside the body of the for
loop are executed, and the update expression is updated.
▪ Again the test expression is evaluated.
▪ This process goes on until the test expression is false. When the test
expression is false, the for loop terminates.
▪ To end the for loop → break; return; goto

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


157
while Loop
while (testExpression) ✓ The while loop evaluates the testExpression inside the
parentheses ().
{ ✓ If the testExpression is true, statements inside the body of
while loop are executed. Then, the testExpression is
code(s) evaluated again.
✓ The process goes on until the testExpression is evaluated
} to false.
✓ If the testExpression is false, the loop terminates (ends).
✓ To end the while loop, using break, goto, return.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


158
do...while Loop
do
{ Vào

code(s)
}
Đúng Khối lệnh
while (testExpression)

▪ The do…while loop is similar to the while Điều kiện?


loop with one important difference.
Sai
▪ The body of do…while loop is executed at
least once. Ra
▪ Only then, the test expression is evaluated.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


159
A program in CCS
#include <16F877A.h>
#device ADC=10
#use delay(clock = 4000000) // pre-processor
#FUSES NOWDT, NOPROTECT, NODEBUG, NOBROWNOUT
……
#use rs232(baud=9600, parity=N, xmit=PIN_C6, RCV=PIN_C7) // serial
#use i2c(Master , SDA=PIN_C3 , SCL=PIN_C4)

int a = 0, b = 1, c = 2; // variable declaration

#int_TIMER1{ // interrupt
…}

void chuong_trinh_con() { // sub-routine


…}

Dr. Dang
void Phuoc
main() {… Vinh
} Faculty of Mechanical Engineering
// main program
160
Functions in CCS
1. No return value void sang_led(led)
void <function_name>(variable) {
{ output_high(led);
code(s)
}
}

2. Return value
<data type> < function_name > (variable) int tinh_toan(int a, int b)
{ {
code(s) int z = a + b;
return z;
return data; }
}

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


161
Functions delay in CCS
✓ In order to use delay functions, we need use “delay” pre-processor
▪ #use delay(clock = 4000000)

✓ delay_cycles(unsigned int8 X) → delay X instruction cycle


▪ X: 1 – 255
▪ 1 instruction cycle = 4 CPU cycles

✓ delay_ms(unsigned int16 X) → delay X ms


▪ X: 0 - 65535

✓ delay_us(unsigned int16 X) → delay X µs


▪ X: 0 - 65535

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


162
Pre-processor
#INCLUDE​
#include <filename>
▪ Filename: is a valid PC filename *.h , *.c
▪ This allows include files to be distributed without
releasing the source code
▪ This method is normally used to include standard library
header files
▪ Example: #include <16F877A.h>​
#include < I2C.h>​

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


163
Pre-processor
#BIT​
#bit name = x.y
▪ A new C variable (one bit) is created and is placed in memory
at byte x and bit y.
▪ This is useful to gain access in C directly to a bit in the
processors special function register map
▪ It may be used to easily access a bit of a standard C variable.
▪ Example: #bit TMR1IF = 0x0B.2; → create a bit namely
TMR1IF located at a byte at address 0Bh and at 2nd bit.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


164
Pre-processor
#BYTE​
#byte name = x
▪ If the “name” is already known as a C variable then this
will locate the variable at address "x​”.
▪ If the “name” is not known, a new C variable is created
and placed at address "x​” with the type int (8 bit).
▪ Memory at "x​” is not exclusive to this variable → other
variables may be located at the same location.
▪ Name is normally identical with the register at address "x​”
▪ Example: #byte portB = 0x06;

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


165
Pre-processor
#DEFINE​
#define ID text​
▪ Used to provide a simple string replacement of the “ID”
with the given text from this point of the program

▪ Example: #define LED_D5 PIN_E2;

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


166
Pre-processor
#USE
#use delay(clock = speed)​
▪ It specifies the clock the CPU runs at.
▪ The compiler will automatically set the oscillator
configuration bits based upon your defined type.
▪ It is essential to use delay_ms or delay_us

#use I2C(options)
▪ Set up the I2C communication
▪ #use i2c(master , SDA = PIN_B1 , SCL = PIN_B4)
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
167
Pre-processor
#USE
#use fast_io(port)
▪ port is I/O ports of PIC (port is A, B, C, D, E)​
▪ Taking control of the port I/O direction instead of letting the
compiler do it automatically.
▪ If use this instruction → some instruction such as output_low(),
input_high() need only one CPU cycles.
▪ The user must ensure the direction register is set correctly via
set_tris_x()
▪ Example: #use fast_io(A)
#use fast_io(all)
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
168
I/O Functions
✓output_low(pin), output_high(pin)
▪ Set up a pin as an OUTPUT pin, ouput value is 0 or 1.
▪ output_low(PIN_B0); // RB0 produces a logic 0 signal (0V)
output_high(PIN_A0); // RA0 produces a logic 1 signal (5V)

✓output_x(byte)
▪ Set up PORT x as OUTPUT, output value is byte.
▪ output_b(0x35); // output value of portB is 0b00110101
output_d(0x76); // output value of port D is 0b01110110

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


169
I/O Functions
output_bit(pin,value)
▪ Set up a pin as an OUTPUT before writting, ouput is value.
▪ Using when the output value depends on value of a
specified variable.

output_bit(PIN_B1,0);
→ Pin RB1 produces a logic 0 signal (0V)

output_bit(PIN_C2,input(PIN_B2));
→ Output of pin RC2 = Input of pin B2

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


170
I/O Functions
✓output_toggle(pin)
▪ Toggle the high/low state of the specified pin
▪ output_toggle(PIN_B1); // inverse status of pin RB1

✓output_float(pin)
▪ This function sets the specified pin to input mode (TRIS
bit 1), which is in high impedance state.
▪ output_float(PIN_B3); // pin RB3 is input

✓output_drive(pin)
▪ This function sets the specified pin to output mode (TRIS
bit 0).
Dr. Dang output_drive(PIN_B1);
▪ Phuoc Vinh // pin
Faculty RB1 is output
of Mechanical Engineering
171
I/O Functions
✓ input(pin)
▪ Return 1-bit value of a specified I/O pin (0 or 1).
▪ if(input(PIN_C5)) output_b(0xFF); // if RC5 = 1 → PORTB = 0xFF
if(!input(PIN_C5)) output_b(0x00); // if RC5 = 0 → PORTB = 0x00

✓ input_x()
▪ Return 1-byte value of a PORT register
▪ int8 DATA;
DATA = input_a(); // DATA stores value of PORTA

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


172
I/O Functions
✓ port_b_pullups(value)
▪ value = 1 → enable PORTB internal pull-up resistors.
▪ In PIC 16F877A only PORTB has internal pull-up resistors.

✓ set_tris_x(byte)
▪ Set data direction (IN/OUT) for PORT-x
where 0: OUTPUT, 1: INPUT.
▪ set_tris_b(0xF0);
// Pins 0,1,2,3 are OUTPUT ; pin 4,5,6,7 are INPUT

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


173
Exercises
Ex. 1: Blink LED
Blink LED with frequency of 1 Hz

Ex. 2: Control 8 LEDs


8 LED is on/off in the consecutive way with frequency of 1 Hz

Ex. 3: Switch
LED is on/off according to the switch (press/release)

Ex. 4: 7-segment LED


Display value from 0 to 9 in a 7-segment LED

Ex. 5: Switch and 7-segment LED


Display value on a 7-segment LED according to the button.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


Chapter 4
Timer
Firma convenzione
Politecnico di Milano e Veneranda Fabbrica
del Duomo di Milano
Aula Magna – Rettorato
Mercoledì 27 maggio 2015
175
Characteristics
PIC16F877A has three timer modules
▪ Timer 0: timer/counter 8 bit, prescaler

▪ Timer 1: timer/counter 16 bit, prescaler, it can continue to


run during Sleep and can generate an interrupt-on-overflow
which will wake-up the processor

▪ Timer 2: timer/counter 8 bit, prescaler & postscaler

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


TIMER 0
Firma convenzione
Politecnico di Milano e Veneranda Fabbrica
del Duomo di Milano
Aula Magna – Rettorato
Mercoledì 27 maggio 2015
177
Features
✓ 8-bit timer/counter

✓ Readable and Writable

✓ 8-bit software programmable prescaler

✓ Internal or external clock select

✓ Interrupt on overflow from FFh to 00h

✓ Edge select for external clock

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


178
Registers
✓TMR0 (101h): Timer0 module register (increment value)

✓INTCON (0Bh): Interrupt control


GIE PEIE TMR0IE INTE RBIE TMR0IF INTF RBIF

✓OPTION_REG (81h): Use to configure the TIMER0 Prescalar


RBPU INTEDG T0CS T0SE PSA PS2 PS1 PS0

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


179
OPTION_REG

RBPU INTEDG T0CS T0SE PSA PS2 PS1 PS0

T0CS: Timer0 Clock Source Select bit → select Timer or


Counter mode

▪ T0CS = 1: (Counter Mode) Timer0 will increment either on


every rising or falling edge of pin RA4/T0CKI

▪ T0CS = 0: (Timer Mode) Timer0 module will increment every


instruction cycle (without prescaler)

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


180
Timer Mode – T0CS = 0
▪ Timer0 will increase in every instruction cycle
✓ Freq. of Timer0 = ¼ crystal Freq.

▪ Value of TMR0: FFh → 00h → TMR0IF (INTCON<2>) = 1


→ Timer0 interrupt is generated
✓ Bit TMR0IF must be cleared in software by the Timer0
module Interrupt Service Routine before re-enabling this
interrupt.
✓ The TMR0 interrupt cannot awaken the processor from
Sleep since the timer is shut-off during Sleep

TMR0 is readable or writable → easy for identification


the interrupt period.
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
181
OPTION_REG
RBPU INTEDG T0CS T0SE PSA PS2 PS1 PS0

T0SE: Timer0 Source Edge Select bit


▪ T0SE = 1: Increment on high-to-low transition on T0CKI pin
▪ T0SE = 0: Increment on low-to-high transition on T0CKI pin

PSA: Prescaler Assignment Select bit


▪ PSA = 1: Prescaler is assigned to the WDT
▪ PSA = 0: Prescaler is assigned to the Timer 0

PS2-PS0: Prescaler Rate Select bit


▪ Prescaler is not accessible but can be configured using PS2:PS0

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


182
Prescaler Rate
PS2-PS1-PS0 TMR0 Rate WDT Rate
000 1:2 1:1
001 1:4 1:2
010 1:8 1:4
011 1:16 1:8
100 1:32 1:16
101 1:64 1:32
110 1:128 1:64
111 1:256 1:128
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
183
Prescaler Rate

Without Prescaler

Dr.With Prescaler
Dang Phuoc Vinh Faculty of Mechanical Engineering
184
Block Diagram

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


185
Delay Calculation
T = 4 × (1/Fosc) * Prescaler
▪ Fosc : Crystal Freq.
▪ Prescaler: prescaler value

In CCS
setup_timer_0(int8 mode)
set_timer0(int8 value)
Ex: setup_timer_0(T0_INTERNAL|T0_DIV_64);
set_timer0(1);
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
186
Example
Blink LED with cycle of 1 second using Timer0

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


TIMER 1
Firma convenzione
Politecnico di Milano e Veneranda Fabbrica
del Duomo di Milano
Aula Magna – Rettorato
Mercoledì 27 maggio 2015
188
Features
✓ 16-bit timer/counter consisting of two 8-bit registers
(TMR1H & TMR1L)
▪ Readable and Writable
▪ Increments from 0000h to FFFFh
✓ Interrupt flag bit of Timer1: TMR1IF (PIR<0>)
✓ Interrupt control bit of Timer1: TMR1IE (PIE<0>)
✓ Timer1 can operate in one of two modes (Timer or Counter)
✓ The operating mode is determined by the clock select
bit TMR1CS (T1CON<1>)

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


189
Registers

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


190
T1CON Registers
- - T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON

✓ T1CKPS1 – T1CKPS0: Timer1 Input Clock Prescaler Select bit

T1CKPS1 - T1CKPS0 Value


00 1:1
01 1:2
10 1:4
11 1:8
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
191
T1CON Registers
- - T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON

✓T1OSCEN: Timer1 Oscillator Enable Control bit


▪ T1OSCEN = 0: Oscillator is shut-off (the oscillator inverter is
turned off to eliminate power drain)
▪ T1OSCEN = 1: Oscillator is enabled

✓TMR1CS: Timer1 Clock Source Select bit


▪ 1: Counter: External clock from pin RC0/T1OSO/T1CKI
▪ 0: Timer: Internal clock (FOSC/4)

✓TMR1ON: Timer1 On bit


▪ 1: Enables Timer1
▪ 0: Stops Timer1

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


192
T1CON Registers
- - T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON

✓ T1SYNC: Timer1 Internal Clock Input Synchronization


Control bit
✓ When TMR1CS = 1
▪ 0: Synchronize external clock input
▪ 1: Do not synchronize external clock input
✓ When TMR1CS = 0: do not care

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


193
Timer1: Counter Mode
✓ Timer1 is being incremented via an external source
(increments occur on a rising edge)
✓ Counter must first have a falling edge before the counter
begins to increment

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


194
Synchronized Counter Mode
✓ When TMR1CS = 1 & T1SYNC = 0

✓ The external clock input is synchronized with internal phase


clocks

✓ The synchronization is done after the prescaler stage

✓ Timer1 will not increment even if the external clock is


present since the synchronization circuit is shut-off → can
not wake-up PIC during SLEEP mode

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


195
Asynchronized Counter Mode
✓ When TMR1CS = 1 & T1SYNC = 1

✓ The external clock input is not synchronized. The timer


continues to increment asynchronous to the internal phase
clocks

✓ The timer will continue to run during Sleep and can generate
an interrupt-on-overflow which will wake-up PIC

✓ In Asynchronous Counter mode, Timer1 cannot be used as a


time base for capture or compare operations

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


196
Timer1 Oscillator
✓ A crystal oscillator circuit is built-in between pins T1OSI (input)
and T1OSO (amplifier output)
✓ It is enabled by setting control bit: T1OSCEN = 1
✓ The oscillator is a low-power oscillator, rated up to 200 kHz.
✓ It will continue to run during Sleep
✓ The Timer1 oscillator is identical to the LP oscillator

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


197
Block Diagram

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


198
Delay Calculation
T = 4 × (1/Fosc) * Prescaler
▪ Fosc : Crystal Freq.
▪ Prescaler: prescaler value
In CCS
setup_timer_1(int16 mode)
set_timer1(int16 value)
Ex: setup_timer_1(T1_INTERNAL|T1_DIV_BY_1);
set_timer1(55536);
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
TIMER 2
Firma convenzione
Politecnico di Milano e Veneranda Fabbrica
del Duomo di Milano
Aula Magna – Rettorato
Mercoledì 27 maggio 2015
200
Features
✓ 8-bit timer/counter with the prescaler & postscaler
✓ It can be used as the PWM time base for the PWM mode of
the CCP module(s).
✓ The TMR2 register is readable and writable and is cleared
on any device Reset.
✓ Prescale option based on the T2CKPS1 & T2CKPS0
✓ 8-bit period register: PR2 (thanh ghi đỉnh)
▪ Readable and Writable
▪ Initialized to FFh upon Reset → PR2 = FFh

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


201
Features
✓ 8-bit period register: PR2 (thanh ghi đỉnh)
▪ Readable and Writable
▪ Initialized to FFh upon Reset → PR2 = FFh
✓ Timer2 increments from 00h until it matches PR2 and then
resets to 00h on the next increment cycle.
✓ The match output of TMR2 goes through a 4-bit postscaler
(which gives a 1:1 to 1:16 scaling inclusive) to generate a
TMR2 interrupt.
✓ Timer2 can be shut-off by clearing control bit, TMR2ON
(T2CON<2>), to minimize power consumption.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


202
Registers

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


203
T2CON Registers
- TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0

✓ TMR2ON: Timer2 On bit


▪ 1: Timer2 is on
▪ 0: Timer2 is off

PS1-PS0 Value
✓ T2CKPS1 – T2CKPS0: Timer2 00 1:1
Input Clock Prescaler Select bit
01 1:4
1x 1:16

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


204
Postscaler
- TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0

✓ TOUTPS3 – TOUTPS0: Timer2 Output Postscaler Select bits

TOUTPS3 – TOUTPS0 Value


0000 1:1
0001 1:2
0010 1:3
… …
1111 1:16
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
205
Block Diagram

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


206
Delay Calculation
In CCS
Prescaler PR2 Generate a TMR2
interrupt after number
of postscaler

setup_timer_2(int8 mode, int8 period, int8 postscaler)


set_timer2(int8 value)
Ex: setup_timer_2(T2_DIV_BY_4,250,10);
set_timer2(1);

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


207
Attention

✓ The prescaler and postscaler counters are cleared when


any of the following occurs:
▪ a write to the TMR2 register
▪ a write to the T2CON register
▪ any device RESET

✓ TMR2 is not cleared when T2CON is written

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


208
Summary
TIMER 0 TIMER 1 TIMER 2
16 bit
Timer register size 8 bit (TMR0) 8 bit (TMR2)
(TMR1H-TMR1L)
Oscillator
FOSC/4 FOSC/4 FOSC/4
(internal)

Oscillator ▪ Pin T1CKI


Pin T0CKI None
(external) ▪ Timer1 (T1OSC )

▪ Prescaler
2 bit 3 bit (1:1, 1:4, 1:16)
Scaler
(1:2 → 1:256) (1, 2, 4, 8) ▪ Postscaler
(1:1 → 1:16)
FFh → 00h FFFFh → 0000h TMR2 = PR2
Interrupt
TMR0IF (INTCON) TMR1IF (PIR1) TMR2IF (PIR2)

Dr. Dang
Wake PICPhuoc Vinh
from SLEEP NO Faculty of Mechanical
YES Engineering NO
209
Example
Blink LED with a frequency of 1 Hz using Timer 2

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


210
CCP: Capture/Compare/PWM
✓ PIC16F877A has two CCP (Capture/Compare/PWM) module
✓ Each CCP module contains a 16-bit register which can operate
as a:
• 16-bit Capture register
• 16-bit Compare register
• PWM Master/Slave Duty Cycle register
✓ Both the CCP1 and CCP2 modules are identical

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


211
Capture Mode
✓ CCPR1H:CCPR1L captures the 16-bit value of the TMR1 register
when an event occurs on pin RC2/CCP1.
✓ The type of event is configured by control bits, CCP1M3:CCP1M0
(CCPxCON<3:0>)
▪ Every falling edge → 0100
▪ Every rising edge → 0101
▪ Every 4th rising edge → 0110
▪ Every 16th rising edge → 0111

- - CCPxX CCPxY CCPxM3 CCPxM2 CCPxM1 CCPxM0

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


212
Capture Mode
✓ When a capture is made, the interrupt request flag bit,
CCP1IF (PIR1<2>), is set.
✓ The RC2/CCP1 pin should be configured as an input
✓ Timer1 must be running in Timer mode, or Synchronized
Counter mode
✓ Interrupt enable bit: CCPxIE (PIE1)
✓ The interrupt flag CCPxIF must be cleared in software
✓ If another capture occurs before the value in CCPR1 is read,
the old captured value is overwritten by the new value

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


213
Capture Block Diagram

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


214
Compare Mode
✓ In Compare mode, the 16-bit CCPR1 register value is constantly
compared against the TMR1 register pair value
✓ Khi CCPRx = TMR1, the state of RC2/CCP1 pin is based on the
value of control bits, CCP1M3:CCP1M0 (CCP1CON<3:0>):
▪ Driven high Interrupt Flag bit
▪ Driven low CCP1IF is set
▪ Remains unchanged
✓ Timer1 must be running in Timer mode, or Synchronized
Counter mode
✓ The Special Event Trigger can be generated to reset the TMR1
and starts ADC (if use CCP2)
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
215
Comparator Block Diagram

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


216
PWM
▪ Pulse sequences with varying pulse frequency and duty cycle have
a wide range of application in automation
▪ “0” → switch-off state ; “1” → switch-on state
▪ Electrical power to feed a consumer with will be directly proportional
to the pulse duration.
▪ This ratio is called Duty Cycle

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


217
PWM Mode
✓ Pulse Width Modulation
✓ The CCPx pin produces up to a 10-bit resolution PWM output
✓ CCP1: pin RC2 & CCP2: pin RC1
✓ CCPx must be output in this mode

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


218
PCA9685
16-Channel 12-bit PWM
I2C interface

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


219
Price

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


220
CCPxCON (x = 1, 2)

- - CCPxX CCPxY CCPxM3 CCPxM2 CCPxM1 CCPxM0

✓ CCPxX, CCPxY: two lowest bits of 10-bit register for calculation


of duty cycle of the PWM mode

✓ CCPxM3:CCPxM0: set working mode of the CCPx module


→ 11xx : CCPx operates as PWM mode

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


221
PWM – Configuration Steps
1. Set the PWM period
→ writing to the PR2 register

1. Set the PWM duty cycle


→ writing to the CCPRxL register and CCPxCON<5:4> bits

3. Make CCP1,2 pin is output

4. Set the configuration of Timer2


→ setup_timer_2(T2_DIV_BY_1,99,1);

5. Configure the CCPx module for the PWM operation


→ setup_ccp2(CCP_PWM);
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
222
1. Set PWM period
✓ PWM Period (in second):

TPWM =  PR2 + 1  4  TOSC  TMR2 Prescale Value

✓ PR2 value:
1
PR2 = −1
f PWM  4  TOSC  Pre

Ex: Generate a pulse with freq. of 10kHz, OSC = 4Mhz, Prescale = 1


1
PR2 = − 1 = 99
1
10  103  4  1
4  10 6

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


223
2. PWM duty cycle
✓ PWM duty cycle:

PWM duty cyle = ( CCPRxL:CCPxCON<5:4> )  TOSC  Prescale


10-bit resolution is available
✓ CCPRxL register
7 6 5 4 3 2 1 0

✓ CCPxCON register
- - CCPxX CCPxY CCPxM3 CCPxM2 CCPxM1 CCPxM0

7 6 5 4 3 2 1 0 CCPxX CCPxY

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


224
PWM Block Diagram
When TMR2 = PR2:
▪ TMR2 is cleared
▪ CCPx pin is set
▪ CCPR1L → CCPR1H

When TMR2 = CCPR1H


&
CCP1CON<5:4> = T2CKPS<1:0>
▪ CCPx pin is cleared

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


225
Notes
▪ Only Timer2 is used for the PWM operation
▪ The Timer 2 postscaler is not used in the PWM mode
▪ If PWM duty cycle > PWM period: ouput is still in HIGH logic
when PR2 = TMR2

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


226
Example
Generate a pulse with freq. of 10kHz, duty = 25%, OSC = 4Mhz, Pre = 1

𝑓𝑃𝑊𝑀 = 10kHz → 𝑇𝑃𝑊𝑀 = 10−4 s

PWM duty cyle = ( CCPRxL:CCPxCON<5:4> )  TOSC  Pre

−4 1
0.25  10 = Value  1
4  10 6

Value = 100 CCPRxL:CCPxCON<5:4> = 0001 1001 . 00

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


227
Example
Generate a pulse with freq. of 10kHz, duty = 25%, OSC = 4Mhz, Pre = 1

PR2 = 99; // Freq. of 10kHz (T = 10−4 s)

T2CKPS0:1 = 00; // prescaler = 1

CCPR2L = 00011001;

CCP2CON = 00001100;

TMR2ON = 1; // Timer 2 is ON

- - CCPxX CCPxY CCPxM3 CCPxM2 CCPxM1 CCPxM0

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


228
In CCS
Generate a pulse with freq. of 10kHz, duty = 25%, OSC = 4Mhz, Pre = 1

setup_timer_2(T2_DIV_BY_1,99,1);
setup_ccp2(CCP_PWM);
value may be an 8 or 16
set_pwm2_duty(value); bit constant or variable.

value
duty_cycle = value = 0.25  ( 99 + 1) = 25
PR2 + 1

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


229
Pulse with f = 10 kHz
U1
13 33
OSC1/CLKIN RB0/INT
14 34
OSC2/CLKOUT RB1
35
RB2
2 36
RA0/AN0 RB3/PGM
3 37
RA1/AN1 RB4
4 38
RA2/AN2/VREF-/CVREF RB5
5 39
RA3/AN3/VREF+ RB6/PGC
6 40
RA4/T0CKI/C1OUT RB7/PGD
7
RA5/AN4/SS/C2OUT
15 A
RC0/T1OSO/T1CKI
8 16
RE0/AN5/RD RC1/T1OSI/CCP2
9 17 B
RE1/AN6/WR RC2/CCP1
10 18
RE2/AN7/CS RC3/SCK/SCL
23 C
RC4/SDI/SDA
1 24
MCLR/Vpp/THV RC5/SDO
25 D
RC6/TX/CK
26
RC7/RX/DT
19
RD0/PSP0
20
RD1/PSP1 CLK
21
RD2/PSP2 CE
22
RD3/PSP3 RST
27
RD4/PSP4
28
RD5/PSP5
29
RD6/PSP6
Dr. Dang Phuoc Vinh 30 Faculty of Mechanical Engineering
RD7/PSP7
230
Duty cycle: 25% & 50%

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


Chapter 5

InterruptFirma convenzione
Politecnico di Milano e Veneranda Fabbrica
del Duomo di Milano
Aula Magna – Rettorato
Mercoledì 27 maggio 2015
232
Introduction
Time

Main
(a) Program without interrupt

ISR ISR ISR

Main Main Main Main

Time
(b) Program with interrupt
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
233
Introduction
✓ 15 sources of interrupt
▪ Timer interrupt (0, 1, 2)
▪ RB0/INT external interrupt
▪ RB port change interrupt (ở các bit PORTB<4:7>)
▪ Peripheral interrupt

✓ Interrupt control register: INTCON (with Global bit GIE)

✓ Individual interrupt bits are set regardless of the status of


the GIE bit. The GIE bit is cleared on Reset

✓ Return from interrupt → RETFIE instruction

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


234
Conditions
To one interrupt occurs, following 3(4) conditions must be meet

▪ Global interrupt enable bit (GIE) = 1


3 sources 12
▪ Interrupt’s flag bit = 1 of interrupt sources
of
▪ Mask bit = 1 interrupt

▪ Peripheral interrupt bit (PEIE) = 1

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


235

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


236
Conditions

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


237
Process
▪ When an interrupt is
responded to, the GIE is cleared
to disable any further interrupt.
▪ The interrupt flag bit(s) must
be cleared in software before
re-enabling interrupts to avoid
recursive interrupts.
▪ As the interrupt routine is
finished → sets the GIE bit,
which re-enables interrupts.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


238
Process
✓ The return address is pushed
onto the stack.
▪ 8 stack
▪ Closed loop
▪ No warning bit for the full
stack condition

✓ The Program Counter is


loaded with 0004h

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


239
Interrupt Process
MAIN #1 STACK
#2
0004h
0010h
0090h
0020h 0020h
0030h
0010h #9 0030h
0040h
#7
#8 0090h 0050h
0060h
0080h 0070h
0090h
0080h
1FFFh
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
240
INTCON Register
GIE PEIE TMR0IE INTE RBIE TMR0IF INTF RBIF

GIE: Global Interrupt Enable bit


1: Enables all unmasked interrupts
0: Disables all interrupts

PEIE: Peripheral Interrupt Enable bit

TMR0IE: TMR0 Overflow Interrupt Enable bit


1: Enable
INTE: RB0/INT External Interrupt Enable bit 0: Disables

RBIE: RB Port Change Interrupt Enable bit

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


241
INTCON Register
GIE PEIE TMR0IE INTE RBIE TMR0IF INTF RBIF

TMR0IF: TMR0 Overflow Interrupt Flag bit


1: TMR0 register has overflowed (must be cleared in software)
0: TMR0 register did not overflow

INTF: RB0/INT External Interrupt Flag bit


1: The RB0/INT external interrupt occurred (must be cleared in software)
0: The RB0/INT external interrupt did not occur

RBIF: RB Port Change Interrupt Flag bit


1: At least one of the RB7:RB4 pins changed state; a mismatch condition will
continue to set the bit (must be cleared in software)
0: None of the RB7:RB4 pins have changed state

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


242
PIE1 Register (8Ch)
PSPIE ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE

PSPIE: Parallel Slave Port Read/Write Interrupt Enable bit (PSP)


ADIE: A/D Converter Interrupt Enable bit
RCIE: USART Receive Interrupt Enable bit
TXIE: USART Transmit Interrupt Enable bit
SSPIE: Synchronous Serial Port Interrupt Enable bit 1: Enable
0: Disables
CCP1IE: CCP1 Interrupt Enable bit
TMR2IE: TMR2 to PR2 Match Interrupt Enable bit
TMR1IE: TMR1 Overflow Interrupt Enable bit
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
243
PIE2 Register (8Dh)
- CMIE - EEIE BCLIE - - CCP2IE

CMIE: Comparator Interrupt Enable bit

EEIE: EEPROM Write Operation Interrupt Enable bit 1: Enable


0: Disables
BCLIE: Bus Collision Interrupt Enable bit

CCP2IE: CCP2 Interrupt Enable bit

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


244
PIR1 Register (0Ch)
PSPIF ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF

PSPIF: Parallel Slave Port Read/Write Interrupt Flag bit


1: A read or a write operation has taken place (must be cleared in software)
0: No read or write has occurred

ADIF: A/D Converter Interrupt Flag bit


1: An A/D conversion completed
0: The A/D conversion is not complete

RCIF: USART Receive Interrupt Flag bit


1: The USART receive buffer is full
0: The USART receive buffer is empty

TXIF: USART Transmit Interrupt Flag bit


1: The USART transmit buffer is empty
0: The USART transmit buffer is full

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


245
PIR1 Register (0Ch)
PSPIF ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF

SSPIF: Synchronous Serial Port (SSP) Interrupt Flag bit


1: The SSP interrupt condition has occurred
0: No SSP interrupt condition has occurred

CCP1IF: CCP1 Interrupt Flag bit


1: A TMR1 register capture/compare occurred (must be cleared in software)
0: No TMR1 register capture/compare occurred

TMR2IF: TMR2 to PR2 Match Interrupt Flag bit


1: TMR2 to PR2 match occurred (must be cleared in software)
0: No TMR2 to PR2 match occurred

TMR1IF: TMR1 Overflow Interrupt Flag bit


1: TMR1 register overflowed (must be cleared in software)
0: TMR1 register did not overflow

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


246
PIR2 Register (0Dh)
- CMIF - EEIF BCLIF - - CCP2IF

CMIF: Comparator Interrupt Flag bit


1: The comparator input has changed (must be cleared in software)
0: The comparator input has not changed

EEIF: EEPROM Write Operation Interrupt Flag bit


1: The write operation completed (must be cleared in software)
0: The write operation is not complete or has not been started

BCLIF: Bus Collision Interrupt Flag bit


1: A bus collision has occurred in the SSP when configured for I2C Master mode
0: No bus collision has occurred

CCP2IF: CCP2 Interrupt Flag bit


1: A TMR1 register capture/compare occurred (must be cleared in software)
0: No TMR1 register capture/compare occurred

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


247
Context Saving During Interrupts
▪ During an interrupt, only the return PC value is saved on
the stack.

▪ Some important registers (STATUS, PCLATH) may be


affected, so:
✓ Save their values before interrupt → store in the temporary
register
✓ Return these values after return from interrupt

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


248

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


249
Timer Interrupt
✓ Timer0
▪ Interrupt occur: TMR0 overflows from FFh → 00h
▪ Interrupt enable bit: TMR0IE (INTCON<5>)
▪ Interrupt flag: TMR0IF (INTCON<2>)
✓ Timer1
▪ Interrupt occur: TMR1 overflows from FFFFh → 0000h
▪ Interrupt enable bit: TMR1IE (PIE1<0>)
▪ Interrupt flag: TMR1IF (PIR1<0>)
✓ Timer2
▪ Interrupt occur: TMR2 increases to PR2 and through postscaler
▪ Interrupt enable bit: TMR2IE (PIE1<1>)
▪ Interrupt flag: TMR2IF (PIR1<1>)
▪ Disable Timer2 interrupt by clearing TMR2ON(T2CON<2>)

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


250
Timer Interrupt

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


251
Timer Interrupt
In CCS
#int_TIMER0
void ngat_timer0(){

}

void main() {
enable_interrupts(INT_TIMER0); → TMR0IE = 1
enable_interrupts(GlOBAL); → GIE = 1
}

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


252
Example
Blink the LED with freq. of 1 Hz using Timer interrupt

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


253
Traffic Light

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


254
External interrupt - INT
✓ Interrupt occurs when pin RB0/INT is edge triggered (rising or
falling edge) → INTF = 1 (INTCON<1>).
✓ The flag bit INTF must be cleared in software in the Interrupt Service
Routine before re-enabling this interrupt
✓ Enable bit: INTE (INTCON<4>)

✓ Edge bit: INTEDG (OPTION_REG<6>)


▪ INTEDG = 1: Rising edge triggered
▪ INTEDG = 0: Falling edge triggered

𝐑𝐁𝐏𝐔 INTEDG T0CS T0SE PSA PS2 PS1 PS0

✓ The INT interrupt can wake-up the processor from Sleep

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


255
External interrupt - INT
#INT_EXT
void isr() {

}

void main() {
set_tris_b(0x01);
ext_int_edge(h_to_l); → Falling edge
enable_interrupts(int_ext); → INTE = 1
enable_interrupts(global); → GIE = 1
}
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
256
RB port change interrupt
▪ This interrupt occurs when an input change on pins RB4÷RB7
→ The interrupt flag bit RBIF (INTCON<0>) will be set.
▪ Only pins configured as inputs can cause this interrupt to occur.
▪ This interrupt can wake the device from Sleep.
▪ Condition: bit GIE and RBIE (INTCON<4>) must be set.
▪ This interrupt can be clear the in the following manner:
✓ Any read or write of PORTB. This will end the mismatch
condition.
✓ Clear flag bit RBIF.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


257
Attention

✓ The interrupt on-change is different from the external interrupt


RB0/INT: edge triggered (rising or falling edge).

✓ The interrupt on-change will occurs when there is a state


change in any of pins RB4÷RB7.
▪ Either rising or falling edge → an interrupt will occur
▪ Be careful: if a switch connected to RB4÷RB7 pin is pressed
and released the on-change interrupt may be occurs twice.
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
258
Notes
Example: RB7 pin is
connected with a switch
✓ Switch open: RB7 = ‘1’
✓ Switch close: RB7 = ‘0’
By pressing and releasing
switch → Generating
2 interrupt events on
RB7.
The on-change interrupt may be occurs twice if a switch
is pressed and released.
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
259
Notes
▪ The input pins (of RB7:RB4) are compared with the old
value latched on the last read of PORTB.

▪ The “mismatch” outputs of RB7:RB4 are OR’ed together to


generate the RB port change interrupt with flag bit RBIF
(INTCON<0>).

▪ A mismatch condition will continue to set flag bit RBIF.

▪ Reading PORTB will end the mismatch condition and


allow flag bit RBIF to be cleared
Page 44 – datasheet PIC16F877A

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


260
RB port change interrupt
#INT_RB
void NGAT_RB_ON_CHANGE () {

}

void main() {
set_tris_b(0xF0);
enable_interrupts(INT_RB); → RBIE = 1
enable_interrupts(global); → GIE = 1
}

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


261
Encoder – Construction

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


262
Applications
✓ Intergated in the motor

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


263
Price

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


264
Motor speed measurement

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


265
1-3: Using Timer 0, 1, 2

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


266
4: Switch - INT

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


267
5: Speed measurement

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


268
6: PWM + INT + Timer

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


269
7 ≡ 5: On-Change RB

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


270
Problems
2 LED 7-segment Switch Encoder: PWM + INT0
Interrupt INT Timer & INT0 + Timer

1 2 3 4 5 6
Timer 0 Timer 1 Timer 2 Speed meas. PWM - Speed

Group 1 0.1 s 0.1 s 0.1 s Switch 1V – T0 – 0.1s T0 – 0.1s


connect to
Group 2 0.2 s 0.2 s 0.2 s 2V – T0 – 0.2s T0 – 0.2s
pin RB0
Group 3 0.3 s 0.3 s 0.3 s 3V – T0 – 0.3s T0 – 0.3s
Group 4 0.4 s 0.4 s 0.4 s LED 7- 4V – T0 – 0.4s T0 – 0.4s
segment
Group 5 0.5 s 0.5 s 0.5 s 5V – T1 – 0.1s T0 – 0.5s
increases
Group 6 0.6 s 0.6 s 0.6 s when 6V – T1 – 0.2s T1 – 0.1s
Group 7 0.7 s 0.7 s 0.7 s switch is 7V – T1 – 0.3s T1 – 0.2s
on
Group 8 0.8 s 0.8 s 0.8 s 8V – T1 – 0.4s T1 – 0.3s
Group 9 0.9 s 0.9 s 0.9 s 00 – 99 9V – T2 – 0.1s T1 – 0.4s
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
Group 10 1.0 s 1.0 s 1.0 s 10V – T2 – 0.2s T1 – 0.5s
Chapter 6
Analog-to-Digital
Firma convenzione
PolitecnicoConverter
di Milano e Veneranda Fabbrica
del Duomo di Milano
ADC
Aula Magna – Rettorato
Mercoledì 27 maggio 2015
272
Introduction
✓ Analog-to-Digital-Converter

✓ Why we need the ADC?


✓ Signal in the real World: Analog
✓ Digital IC/Chip: Digital

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


273
Introduction
ADC Block Diagram

ADC0802-ADC0804

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


274
ADC on PIC 16F877A
✓ There are 8 ADC channels with 10-bit resolution → 𝟐𝟏𝟎 digital numbers
✓ The A/D module has high and low-voltage reference input
▪ Software → generate combination of VDD, VSS, RA2 or RA3
✓ The A/D converter has a unique feature of being able to operate while the
device is in Sleep mode.
✓ To operate in Sleep, the A/D clock must be derived from the A/D’s
internal RC oscillator.
✓ PIC16F877A has 4 registers:
▪ ADRESH (A/D Result High Register)
▪ ADRESL (A/D Result Low Register)
▪ ADCON0 (A/D Control Register 0)
▪ ADCON1 (A/D Control Register 1)

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


ADCON0 275

ADCON1

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


Not available on 28-pin devices
276
ADCON0: A/D Control Register 0

ADCS1 ADCS0 CHS3 CHS2 CHS1 CHS0 GO/DONE ADON

bit 7-6 ADCS<1:0>: A/D Conversion Clock Select bits


ADCON1 ADCON0
Clock Conversion
<ADCS2> <ADCS1:ADCS0>
0 00 FOSC/2 = 2 × TOSC
0 01 FOSC/8 = 8 × TOSC
0 10 FOSC/32 = 32 × TOSC
0 11 FRC (clock derived from the internal A/D RC oscillator)
1 00 FOSC/4 = 4 × TOSC
1 01 FOSC/16 = 16 × TOSC
1 10 FOSC/64 = 64 × TOSC
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
1 11 FRC (clock derived from the internal A/D RC oscillator)
277
ADCON0: A/D Control Register 0

ADCS1 ADCS0 CHS2 CHS1 CHS0 GO/DONE - ADON

bit 5-3 CHS<2:0>: A/D Channel Select bits


CHS<2:0> Channel Select
000 Channel 0 (AN0)
001 Channel 1 (AN1)
010 Channel 2 (AN2)
011 Channel 3 (AN3)
100 Channel 4 (AN4)
101 Channel 5 (AN5)
110 Channel 6 (AN6)
111 Channel 7 (AN7)

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


278
ADCON0: A/D Control Register 0

ADCS1 ADCS0 CHS2 CHS1 CHS0 GO/𝐃𝐎𝐍𝐄 - ADON

bit 2 GO/ 𝐃𝐎𝐍𝐄 : A/D Conversion Status bit


When ADON = 1
1: A/D conversion in progress (setting this bit starts the A/D conversion
which is automatically cleared by hardware when the A/D conversion is
complete)
0: A/D conversion not in progress

bit 0 ADON: A/D On bit


1: A/D converter module is powered up
0: A/D converter module is shut-off and consumes no operating current

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


279
ADCON1: A/D Control Register 1

ADFM ADCS2 - - PCFG3 PCFG2 PCFG1 PCFG0

bit 7 ADFM: A/D Result Format Select bit


0: Right justified, 6 LSB bit of ADRESL are read as ‘0’
1: Left justified, 6 MSB bit of ADRESH are read as ‘0’

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


280
ADCON1: A/D Control Register 1
ADFM ADCS2 - - PCFG3 PCFG2 PCFG1 PCFG0

bit 3-0 PCFG<3:0>: A/D Port Configuration Control bits

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


281
Conversion Steps
1. Set ADC configuraion
▪ Configure analog pins/voltage reference and digital I/O
(ADCON1)
▪ Select A/D input channel (ADCON0)
▪ Select A/D conversion clock (ADCON0)
▪ Turn on A/D module (ADCON0)
2. Configure A/D interrupt (if desired)
▪ Clear ADIF bit; Set ADIE bit; Set PEIE bit; Set GIE bit
3. Wait the required acquisition time

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


282
Conversion Steps
4. Start conversion: set GO/ 𝐃𝐎𝐍𝐄 = 1
5. Wait for A/D conversion to complete by either:
▪ Polling for the GO/ 𝐷𝑂𝑁𝐸 bit to be cleared (interrupts disabled);
OR
▪ Waiting for the A/D interrupt
6. Read results from ADRESH-ADRESL, clear bit ADIF if
required.
7. For the next conversion, go to step 1 or step 2as required.
The A/D conversion time per bit is defined as 𝐓𝐀𝐃

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


283
Conversion Time
✓ The A/D conversion time per bit is defined as TAD
✓ To convert 10 bit → require a minimum 12 TAD
✓ The source of the A/D conversion clock is software selected
✓ To ensure the A/D conversion is correct → TAD ≥ 1.6 µs
ADCON1 ADCON0
Clock Conversion
<ADCS2> <ADCS1:ADCS0>
0 00 FOSC/2
0 01 FOSC/8
0 10 FOSC/32
1 00 FOSC/4
1 01 FOSC/16
1 10 FOSC/64
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
x 11 FRC (clock derived from the internal A/D RC oscillator)
284
Acquisition Time

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


285
Notes
✓ The port pins that are desired as analog inputs must have their
corresponding TRIS bits set (input).

✓ If the TRIS bit is cleared (output) → digital output

✓ To begin the A/D conversion → set GO/DONE = 1

✓ Clearing the GO/DONE bit during a conversion will


▪ Abort the current conversion

▪ The A/D Result register pair will NOT be updated with the
partially completed A/D conversion sample

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


286
ADC Cycles
• The GO/DONE bit can be set to start the conversion
• After the GO/DONE bit is set, the first time segment has a
minimum of TCY and a maximum of TAD
• Note: The GO/DONE bit should NOT be set in the same
instruction that turns on the A/D

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


287
Registers/bits associated ADC
▪ The A/D module to be turned off and any conversion is aborted.
▪ All A/D input pins are configured as analog inputs.
▪ The ADRESH:ADRESL registers will contain unknown data after a Power-on Reset.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


288
In CCS

#device ADC = 10
SETUP_ADC(ADC_CLOCK_DIV_2);

SETUP_ADC_PORTS(AN0_AN1_AN2_AN3_AN4);
SET_ADC_CHANNEL(0);
DELAY_US(10);
VALUE = READ_ADC();

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


289
In CCS

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


290
LM35 Sensor

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


291
Variable Resistor voltage

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


Chapter 7
Serial Firma convenzione

Communication
Politecnico di Milano e Veneranda Fabbrica
del Duomo di Milano
Aula Magna – Rettorato
Mercoledì 27 maggio 2015
293
Serial Communication Type
1. Master Synchronous Serial Port (MSSP)
❖ SPI (Serial Peripheral Interface)
❖ I2C (Inter-Intergrated Circuit)
o I2C Master Mode

2. Universal Synchronous Asynchronous


Receiver Transmitter (USART)
❖ USART is also known as a Serial
Communications Interface or SCI

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


I2C
Communication
295
I2C (Inter-Intergrated Circuit)
Device addressing: 7-bit or 10 bit
+5V
Rpull: 1.8 – 47kΩ 1 Master +3.3V
1.8kΩ , 4.7kΩ ,10kΩ 128 devices
127 Slaves Power

Note: need 16 1 Master RC3/SCK/SCL


Rp reversed addresses 111 Different Slaves Serial Clock
→ max. 112 addresses
SCL

RC4/SDI/SDA
I2C bus Serial
Data
MCU Sensor ADC EEPROM MCU Line
Master Slave Slave Slave Slave
SDA

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


296
I2C Communication

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


297
Operation Modes
Mode Speed
Standard Mode: 100 kbit/s
1 Master – 1 Slave
Low-speed Mode: 10 kbit/s

1 Master – multi-Slave Fast Mode: 400 kbit/s

Fast Mode Plus: 1 Mbit/s


Multi-Master – Multi-Slave
High-speed Mode : 3.4 Mbit/s

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


298
Timing Diagram

Idle Idle
Status Status

SDA SDA

SCL SCL

Start Transper data Stop


Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
299
I2C Communication

Read 1 byte
Read
Read multi-byte

Write 1 byte
Write
Write multi-byte

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


300
Read 1 byte ▪ Master send to Slave
▪ By software
Stop
Start Re-Start Sequence
Sequence Write Sequence Read
NAK

ST Device Add. (7 bit) W Register Add (8 bit) SR Device Add. (7 bit) R NAK SP
Master

AK AK AK Data (8 bit)
Slave
AK AK AK

▪ Slave send to Master


AK (ACK) : Acknowledge = ‘0’ ▪ Automatic
NAK (NACK) : Not Acknowledge = ‘1’
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
301
Read multi-byte
Start Write Re-Start Read AK

ST Device Add. (7 bit) W Register Add (8 bit) SR Device Add. (7 bit) R AK


Master

AK AK AK Data (8 bit)
Slave
AK AK AK
NAK Stop

AK AK NAK SP
Master

Data (8 bit) Data (8 bit) Data (8 bit)


Slave
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
302
Write 1 byte
Start Stop
Sequence Write Sequence

Master ST Device Add. (7 bit) W Register Add (8 bit) Data (8 bit) SP

Slave AK AK AK

AK AK AK

AK (ACK) : Acknowledge = ‘0’


NAK (NACK) : Not Acknowledge = ‘1’
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
303
Write multi-byte
Start Stop
Sequence Write Sequence

ST Device Add. (7 bit) W Register Add (8 bit) Data (8 bit) Data (8 bit) SP
Master

AK AK AK AK
Slave
AK AK AK AK

AK (ACK) : Acknowledge = ‘0’


NAK (NACK) : Not Acknowledge = ‘1’
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
304
7-bit Addressing
Slave Address R/W

A6 A5 A4 A3 A2 A1 A0

MSB LSB
✓ In the 7-bit addressing procedure, the slave address is
transferred in the first byte after the Start Condition.

✓ The first seven bits of the byte comprise the slave address.

✓ The 8th bit is the read/write flag where 0 indicates a write


and 1 indicates a read.
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
305
Important Note
Write Address: 0×92 Read Address: 0×93
1 0 0 1 0 0 1 0 1 0 0 1 0 0 1 1

1 0 0 1 0 0 1
Slave Address: 0×49
• Vendors incorrectly provide two 8-bit slave addresses: one to
write and one to read from the device.
• This 8-bit number actually encodes the 7-bit slave address and
the read/write bit.
• 7-bit addressing: only use the top 7 bits of the address as the
slave address
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
306
Important Note
Reserved Address Reserved Address
Valid Address Range
000 0XXX 111 1XXX
0×08 to 0×77
0×00 to 0×07 0×78 to 0×7F

✓ Another way to determine if a vendor is using 8-bit


addresses instead of 7-bit addresses is to see if the slave
address falls within the correct range.

✓ All 7-bit addresses should be greater than 0×07 and less


than 0×08.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


307
I2C Communication

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


308
I2C Module for LCD

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


309
I2C Module for LCD

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


310
I2C Module for LCD

I2C address of the PCF8574 is: 0 1 0 0 A2 A1 A0 0


Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
311
I2C Module for LCD

RS
PIC RW
E

Device Address D4 – D7
Selection

I2C address of the PCF8574 is: 0 1 0 0 A2 A1 A0 0


Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
312
I2C Module for LCD

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


313
I2C Module for Sensors

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


314
I2C Module for Sensors

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


315
Registers
1. SSPCON1, SSPCON2
❑ MSSP Control register
❑ Readable and Writable
2. SSPSTAT
❑ MSSP Status register
❑ LSB and MSB bit is readable and writable, 6 remaining bit is
only readble.
3. SSPBUF: Serial Receive/Transmit Buffer Register
4. SSPSR: MSSP Shift Register - Not directly accessible
5. SSPADD: MSSP Address Register

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


316
SSPCON1 Register
WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0

bit 7 WCOL: Write Collision Detect Bit


1: A write to the SSPBUF register was attempted while the I2C
conditions were not valid for a transmission to be started.
(Must be cleared in software.)
0: No collision

bit 6: SSPOV: Receive Overflow Indicator bit


This bit is only valid in the case of Receive mode
1: A byte is received while the SSPBUF register is still holding the
previous byte. (Must be cleared in software.)
0: No Overflow

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


317
SSPCON1 Register
WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0

bit 5: SSPEN: Synchronous Serial Port Enable bit


1: Enables the serial port and configures the SDA and SCL
pins as the serial port pins
0: Disables the serial port and configures these pins as I/O
port pins

bit 4: CKP: Unused in the I2C Master Mode

bit 3:0 SSPM<3:0>: Synchronous Serial Port Mode Select bits


1000 I2C Master mode, clock = FOSC/(4*(SSPADD + 1))

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


318
SSPCON2 Register
GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN

bit 7: GCEN: General Call Enable bit


1: Enable interrupt when a general call address (0000h) is
received in the SSPSR
0: General call address disabled

bit 6: ACKSTAT: Acknowledge Status bit (Master Transmit


mode only)
1: Acknowledge was not received from slave
0: Acknowledge was received from slave

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


319
SSPCON2 Register
GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN

bit 5: ACKDT: Acknowledge Data bit (Master Receive mode only)


1: Not Acknowledge
0: Acknowledge

bit 4: ACKEN: Acknowledge Sequency Enable bit (Master Receive


mode only)
1: Initiate Acknowledge sequence on SDA and SCL pins and
transmit ACKDT data bit. Automatically cleared by hardware.
0: Acknowledge sequence Idle

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


320
SSPCON2 Register
GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN

bit 3: RCEN: Receive Enable bit (Master mode only)


1: Enables Receive mode for I2C
0: Receive Idle

bit 2: PEN: Stop Condition Enable bit (Master mode only)


1: Initiate Stop condition on SDA and SCL pins. Automatically
cleared by hardware
0: Stop condition Idle

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


321
SSPCON2 Register
GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN

bit 1: RSEN: Repeated Start Condition Enable bit


1: Initiate Repeated Start condition on SDA and SCL pins.
Automatically cleared by hardware.
0: Repeated Start condition Idle

bit 0: SEN: Start Condition Enable bit


Master Mode:
1: Initiate Start condition on SDA and SCL pins. Automatically
cleared by hardware
0: Start condition Idle

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


322
SSPSTAT Register
SMP CKE D/A P S R/W UA BF

bit 7: SMP: Slew Rate Control bit


1: standard speed mode (100 kHz and 1 MHz)
0: high-speed mode (400 kHz)

bit 4: P: Stop bit


1: Indicates that a Stop bit has been detected last
0: Stop bit was not detected last

bit 3: S: Start bit


1: Indicates that a Start bit has been detected last
0: Start bit was not detected last
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
323
SSPSTAT Register
SMP CKE D/A P S R/W UA BF
bit 2: R/𝐖 : Read/Write bit information (I2C mode only)
1: Transmit is in progress
0: Transmit is not in progress

bit 0: BF: Buffer Full Status bit


In Transmit mode:
1: Receive complete, SSPBUF is full
0: Receive not complete, SSPBUF is empty
In Receive mode:
1: Data Transmit in progress, SSPBUF is full
0: Data Transmit complete, SSPBUF is empty
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
324
Block Diagram

RC4

RC3

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


325
Baud Rate Generator
▪ BRG reload value is placed in the lower 7 bits of the SSPADD register.
▪ When a write occurs to SSPBUF, BRG will automatically begin counting.
▪ BRG counts down to 0 and stops until another reload has taken place
In I2C Master mode, BRG is reloaded automatically.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


326
START Condition Timing

The START condition will be aborted if:


▪ At the beginning of the Start condition, the SCL and SDA pin is sampled “LOW”,
OR
▪ During the Start condition, the SCL line is sampled low before the SDA line is
driven low.
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
327
RE-START Condition Timing

• SDA is sampled low when SCL goes from low to high A bus collision
• SCL goes low before SDA is asserted low occurs

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


328
STOP Condition Timing

• A Stop bit is asserted on the SDA pin at the end of a receive/transmit by


setting the Stop Sequence Enable bit, PEN (SSPCON2<2>).
• At the end of a receive/transmit, the SCL line is held low after the falling
edge of the 9th clock.
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
329
Digital Clock

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


330
DS1307 Module

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


331
DS1307 Module

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


332
IC DS1307

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


333
Digital clock - LED 7-segment

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


334
Digital clock - LCD

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


USART
336
USART
PIC16F877A comes with inbuilt USART

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


337
USART
✓ USART: Universal Synchronous
Asynchronous Receiver Transmitter
✓ Another name: Serial Communications
Interface - SCI

✓ Two pins using for USART:


▪ RC6/TX/CK
▪ RC7/RX/DT

✓ Mode:
▪ Asynchronous
▪ Master mode
▪ Slave mode
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
338
Transmission Mode
One-way
communication

Two-way,
simultaneously
communication

Two-way, not
simultaneously
communication
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
339
Transmission Mode
One direction only

Both directions
Only one at a time

Both directions
At the same time

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


340
Communication Speed
✓ Bit rate
▪ The transmission of number of bits per second (bps)

✓ Baud rate
▪ The number of signal units (word) changes per
second
▪ Word can be one bit or multi-bits
▪ USART in PIC 16F877A, 1 word = 1 bit

Bit rate ≡ baud rate

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


341
Synchronous & Asynchronous
Synchronous TX RX
✓ Data is sent in form of blocks or frames
RX TX
✓ Full-duplex transmission mode
✓ Need synchronized clocks from master to slave CLK
✓ Transmission in a short distance
✓ START, STOP bit is not compulsory

TX RX
Asynchronous
✓ Data is sent in form of byte or character RX TX
✓ Half-duplex transmission mode
✓ No need synchronized clocks
✓ START and STOP is a must

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


342
Synchronous & Asynchronous
Synchronous Asynchronous
Number of Tasks

Number of Tasks
20 seconds
20 seconds
7 seconds
7 seconds
10 seconds
10 seconds
8 seconds
8 seconds

Total time taken by the tasks. Total time taken by the tasks.
45 seconds 20 seconds
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
343
Synchronous & Asynchronous

Synchronous

Asynchronous

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


344
Parity bit
✓ Parity bit (Bit chẵn lẻ) is a bit added to a string of binary
code which ensure that the total number of 1-bits in the
string is even or odd.
✓ Parity bits are a simple form of error detecting code.
✓ There are two variants of parity bits:
▪ Even parity bit (bit chẵn lẻ dùng quy tắc số chẵn)
▪ Odd parity bit (bit chẵn lẻ dùng quy tắc số lẻ)

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


345
Parity bit

8 bits including parity


7 bits of data (count of 1-bits)
even odd
000.0000 0 0.000.0000 1.000.0000
101.0001 3 1.101.0001 0.101.0001
110.1001 4 0.110.1001 1.110.1001
111.1111 7 1.111.1111 0.111.1111

Parity Generator and Checker

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


346
Parity bit
SENDER RECEIVER

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


347
Data Frame
In serial communication, the most common data frame
1 bit START + 7 bit DATA + 1 bit Parity + 1 bit STOP

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


348
ASCII Table

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


349
Asynchronous Mode
✓ Working with NRZ standard (None-Return-to-Zero)
→1 bit START (0) + 8 bit DATA + 1 bit STOP (1)

✓ Bit LSB will be sent first


✓ Both the devices Rx/Tx should be set to same baud rate for
successful communication
✓ Both the devices Rx/Tx must have same data format

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


350
TRANSMIT Block Diagram

TXSTA

RCSTA

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


351
TXSTA Register
CSRC TX9 TXEN SYNC - BRGH TRMT TX9D
bit 5: TXEN: Transmit Enable Bit
1: Transmit enable
0: Transmit disable
bit 4: SYNC: USART Mode Select bit
1: Synchronous mode
0: Asynchronous mode
bit 2: BRGH: High Baud Rate Select Bit
Only use in Asynchronous mode
1: High speed
0: Low speed
bit 1: TRMT: Transmit Shift Register Status bit
1: TSR empty
0: TSR full
bit 0: TX9D: 9th bit of Transmit Data, can be Parity bit

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


352
RCSTA Register
SPEN RX9 SREN CREN ADDEN FERR OERR RX9D

bit 7: SPEN: Serial Port Enable Bit


1: Enable serial port
0: Disable serial port

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


353
Transmit data
✓ The heart of the transmitter is the TSR (Transmit Shift Register)

✓ Data is stored in the TXREG before transmitting

✓ TSR will collect data from TXREG


▪ TXREG will be empty
▪ TXIF flag bit (PIR1<4>) will be set
▪ TXIF flag bit cannot be cleared in software
▪ TXIF flag bit will reset only when new data is loaded into the
TXREG register

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


354
Transmit data
✓ Status of the TSR is indicated by the TRMT flag bit (TXSTA<1>)

✓ TMRT = 1 → TSR is empty


▪ This bit is read only

✓ The TSR register is not mapped in data memory so it is not


available to the user; it is controlled by CPU

✓ TXEN = 1: enable the transmit system

✓ Transmission is enabled only:


▪ Data is available in the TXREG
▪ The Baud Rate Generator (BRG) has produced a shift clock

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


355
TRANSMIT Block Diagram

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


356
Steps for TRANSMIT data
1. Initialize the SPBRG register for the appropriate baud rate.
2. Enable the asynchronous serial port by clearing bit SYNC and setting
bit SPEN.
3. If interrupts are desired, then set enable bit TXIE.
4. If 9-bit transmission is desired, then set transmit bit TX9.
5. Enable the transmission by setting bit TXEN, which will also set bit
TXIF.
6. If 9-bit transmission is selected, the 9th bit should be loaded in bit
TX9D.
7. Load data to the TXREG register (starts transmission).
8. If using interrupts, ensure that GIE and PEIE (bits 7 and 6) of the
INTCON register are set.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


357
RECEIVE Block Diagram

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


358
RCSTA Register (18h)
SPEN RX9 SREN CREN ADDEN FERR OERR RX9D

bit 7 SPEN: Serial Port Enable Bit


1: Serial port enable
0: Serial port disable

bit 4 CREN: Continuous Receive Enable bit


Asynchronous mode:
1: Enables continuous receive
0: Disables continuous receive

Synchronous mode:
1: Enables continuous receive until enable bit CREN is cleared (CREN
overrides SREN)
0: Disables continuous receive

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


359
RCSTA Register (18h)
SPEN RX9 SREN CREN ADDEN FERR OERR RX9D

bit 2 FERR: Framing Error Bit (lỗi khung truyền)


1: Framing error
0: No framing error

bit 1 OERR: Overrun Error bit (lỗi tràn dữ liệu)


1: Overrun error (can be cleared by clearing bit CREN)
0: No overrun error

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


360
“Framing” Error
✓ This error occurs when the RSR register (receive block) does
not receive STOP bit on time
→ The Receive and Transmit operate with different baud rate

✓ When framing error occurs → FERR = 1


✓ During the framing error, the new data is still transmitted
✓ When the new data is transmitted → FERR = 0
✓ FERR bit must be checked before reading new data
✓ FERR bit can not be clear in software.
✓ Clear FERR bit by clearing SPEN bit (RCSTA<7>)

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


361
RECEIVE Block Diagram

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


362
Receive data
✓ The data is received on the RC7/RX/DT pin and drives the data recovery
block
▪ This block is actually a high-speed shifter, operating at 16 times the
baud rate
✓ The heart of the receiver is the RSR (Receive Shift Register)
✓ Once Asynchronous mode is selected, reception is enabled by setting bit
CREN (RCSTA<4>)
✓ The received data in the RSR is transferred to the RCREG register (if it is
empty)
▪ If the transfer is complete, flag bit, RCIF (PIR1<5>), is set.
▪ The corresponding interrup occurs (if available)
▪ Flag bit RCIF is a read-only bit which is cleared by the hardware
▪ It is cleared when the RCREG register has been read and is empty
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
363
Receive data
✓ RCREG is a double-buffered register with the working mode of
FIFO (First In First Out)
▪ RCREG is possible for two bytes of data to be received
▪ Third byte to begin shifting to the RSR register

✓ On the detection of the Stop bit of the third byte, if the RCREG
register is still full:
▪ The Overrun Error bit, OERR, will be set
▪ The data in the RSR will be lost
▪ The RCREG register can be read twice to retrieve the two bytes in
the FIFO

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


364
Receive data
✓ If OERR = 1 → Transfers from the RSR register to the RCREG
register are inhibited and no further data will be received
✓ Bit OERR has to be cleared in software: CREN is cleared and then
set
✓ Bit FERR and the 9th receive bit are buffered the same way as the
receive data
✓ Reading the RCREG will load bits RX9D and FERR with new
values
It is essential for the user to read the RCSTA register before reading the
RCREG register in order not to lose the old FERR and RX9D information

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


365
Steps for RECEIVE data
1. Initialize the SPBRG register for the appropriate baud rate

2. Enable the asynchronous serial port by clearing bit SYNC and


setting bit SPEN.

3. If interrupts are desired, then set enable bit RCIE.

4. If 9-bit reception is desired, then set bit RX9.

5. Enable the reception by setting bit CREN.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


366
Steps for RECEIVE data
6. Flag bit RCIF will be set when reception is complete and an
interrupt will be generated if enable bit RCIE is set.
7. Read the RCSTA register to get the ninth bit (if enabled) and
determine if any error occurred during reception.
8. Read the 8-bit received data by reading the RCREG register.
9. If any error occurred, clear the error by clearing enable bit
CREN.
10. If using interrupts, ensure that GIE and PEIE (bits 7 and 6) of
the INTCON register are set.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


367
UART – RS232
✓ Mircrocontroller: UART (or TTL)
▪ Logic “0” → 0 V
▪ Logic “1” → from 3.3 V to 5 V

✓ Computer: RS232 (Recommeded Standard 232)


▪ COM port on computer
▪ Logic “0” → from +3.5 V to +25 V
▪ Logic “1” → from –3.5 V to –25 V

IC MAX232

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


368
9-pin COM Port

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


369
VGA Port

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


370
9-pin COM Port – Male & Female

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


371
Price

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


372
RS232 Cable

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


373
25-pin COM Port
1 13

14 25

13 1

25 14

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


374
Parallel Port

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


375
Ports on PC

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


376
Control system for CNC

https://machviet.com/bo-dieu-khien-may-cnc-
2-truc-v5-1.html

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


377
MAX 232

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


378

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


379
IC MAX 232

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


380
MAX 232 Module

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


381
MAX 232 Module

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


382
Features & Applications
✓ PCs use the RS232 (COM port)
✓ High speed is not required
✓ Cheap
✓ Simple hardware
✓ Maximum speed: 20kbit/s
✓ Maximum working distance: 15m
✓ However, COM port is not popular now
→ Replaced by the modern ports such as USB, Ethernet.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


383
Electronic Weight Scale

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


384
Indicator

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


385
PLC

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


386
Card PCI for PC

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


387
Card PCI for PC

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


388
Price

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


389
Applications

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


390
UHF201: RFID Reader

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


391
Toll Plaza

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


392
Toll Plaza

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


393
UART – RS232

RS232 cable

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


394
USB to COM

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


395
USB to COM

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


396
USB to COM

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


397
UART – RS232

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


398
COM port

Arduino Uno
connect with PC
through COM 1

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


399
Change COM port name
2

1 5

4
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
400
Virtual Serial Port Driver

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


401
HyperTerminal

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


402
HyperTerminal

Terminal Software

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


403
RealTerm: Serial Capture

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


404
In CCS
#use rs232(baud = 9600, parity = N, xmit = PIN_C6, rcv = PIN_C7)

▪ #use rs232: Pre-process instruction

▪ baud = 9600: set baud rate

▪ parity = N: indicate parity bit during the communication

▪ xmit = PIN_C6: pin for transmitting data is PIN C6

▪ rcv = PIN_C7: pin for receiving data is PIN C7

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


405
In CCS

To receive data from PCs


through RS232, we can
use getch()

char c;
c = getch();

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


406
MATLAB
✓ Matlab: MATrix LABoratory
✓ Design by MathWorks.
✓ Matlab functions: matrix
calculation, plot function,
signal processing, image
processing, GUI,…
✓ Version of Matlab is
symbolized with published
year with letter “a” or “b”.

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


407
MATLAB Cost

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


408
MATLAB

Tools

Command window Workspace

Current
Folder

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


409
MATLAB - Script

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


410
MATLAB - GUIDE
GUI (Graphical User Interface) can be used to connect PIC and PC

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


411
MATLAB – COM port
Create a COM port
ten_bien = serial(‘ten_cong_com’);
s = serial(‘COM1’);

Query parameters of COM port


get(tenbien);
get(s);

Modify parameters of COM port


set(ten_bien, ‘ten_thong_so’, gia_tri);
set(s,‘BaudRate’, 9600);

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


412
MATLAB – COM port
Open COM port
fopen(ten_bien);
fopen(s);
Close COM port
fclose(ten_bien);
fclose(s);
Returns all valid serial port objects (workspace)
object = instrfind;
Write data
fwrite(tenbien, gia_tri gia_tri);
fwrite(s, 1);

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


413
MATLAB GUI – Ví dụ

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


414
MATLAB GUI

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


415
MATLAB GUI

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


416
MATLAB GUI

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


417
Visual Studio 2013

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


418
Visual Studio – C#

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


419
Visual Studio – C#

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


420
Visual Studio – COM port
Create a COM1
private SerialPort comport_1 = new SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);

Open/Close COM port


comport_1.Open();
comport_1.Close();

Write data
serialPort1.Write("1");

Read data
String docdulieu = comport_1.ReadExisting().ToString();

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


421
Visual Studio – C#

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


422
Smart Parking – C#

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


423
Concrete mixer – C#

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


424
Weight Scale – C#

Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering


the END !
Firma convenzione
Politecnico di Milano e Veneranda Fabbrica
del Duomo di Milano
Aula Magna – Rettorato
Mercoledì 27 maggio 2015

You might also like