Professional Documents
Culture Documents
Vi Dieu Khien Pic - 21cdt
Vi Dieu Khien Pic - 21cdt
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
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
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.
PICKit 3 HyperTerminal
3. Workshop 2
4. PBL4-5
5. Final Project
BCD 8421
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
30
Analog vs. Digital
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
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
Microcontroller
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
36
CPU
3. Reliable Suppliers
✓ Programmable Intelligent
Computer
✓ PIC made by Microchip
Technology
✓ PIC1650 originally developed
by General Instrument's
Microelectronics Division
✓ PIC 8-bit was developed in
1976
✓ Cheap price
Flash memory
▪ One kind of EEPROM
▪ Can be erased and re-programmed
▪ Can be read/write with different sector
Chân nạp
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.
Port A Port B
Port E Power
Power
Port D
Oscillator
Port C Port C
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
PICkit 3
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
RE0/𝐑𝐃/AN5 (8)
✓ RE0: Digital Input/Output
✓ 𝐑𝐃: Read in parallel slave port
✓ AN5: Analog input of 5th channel
RE2/𝐂𝐒/AN7 (10)
✓ RE2: Digital Input/Output
✓ 𝐂𝐒: Chip select in parallel slave port
✓ AN7: Analog input of 7th channel
10 Ohm/5W
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
RC5/SDO (24)
✓ RC5: Digital Input/Output
✓ SDO: Output in SPI mode
RB3/PGM (36)
✓ RB3: Digital Input/Output
✓ PGM: Low-Voltage Programming
function
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
CPU EEPROM
CCP1 , CCP2 35 instructions (256 byte)
ADC
Module PWM
Memory
CCP/PWM Interrupt WDT
Vref
Modules
RESET
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
CALL, RETURN,
Stack Level 1
– Stores the contents of the PC
• PUSHES
– CALL/Interrupt
• POPS Stack Level 8
– RETURN, RETFIE, RETLW
Program Memory
✓ EEPROM memory
✓ Divided in 4 banks.
✓ Each bank has 128 byte
▪ Special Function Registers
(SFR) located in low-
address memory
01Fh 09Fh
020h 0A0h
128 Bytes
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
Output
Output
Output
Output
CPU Input
Input
Input
Input
1 1 0 1 0 1 0 1 PORT
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
72ms
Holds PICmicro® MCU Internal
Reset
in reset until ~72ms
VDD
after VDD rises back BVDD
VDD
BVDD
72ms
Internal
Reset
16-bit Multiplexer
– 1.8V up to 4.5V in 0.1 to 0.2V steps
– External analog input LVDIF
• Internal VREF
VREF
LVDIN
MCLR/VPP
Pin Function ICSP™ Connector
ICSP Connector
PIC16Fxxx
VPP Programming Voltage = 13V
VDD Supply Voltage VDD
VSS Ground VSS
Isolation
To application circuit
circuits
Process
Output
Decision
Flow lines
Procedure, Function…
Begin, End
Draw.io
//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
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
int a = 9, b = 2;
int c = a/b; →c=5
float d = (float)a/b; → d = 4.5
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
}
Không
break;
Đúng
Giá trị = 2? Lệnh/khối lệnh 2
case constant 2: statement;
Có
break; Sai
break?
Không
…………….
Đúng
Giá trị = n? Lệnh/khối lệnh n
case constant n: statement;
Có
break; break?
Sai
Không
}
Ra
break; break?
Có
Sai
……………. Không
Đúng
Giá trị = n? Lệnh/khối lệnh n
case constant n: statement;
break; Sai
break?
Có
Không
default: statement;
default: Lệnh/khối
break; lệnh n+1
} Ra
code(s)
}
Đúng Khối lệnh
while (testExpression)
#int_TIMER1{ // interrupt
…}
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; }
}
#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
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
✓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
✓ 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
Ex. 3: Switch
LED is on/off according to the switch (press/release)
Without Prescaler
Dr.With Prescaler
Dang Phuoc Vinh Faculty of Mechanical Engineering
184
Block Diagram
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
✓ The timer will continue to run during Sleep and can generate
an interrupt-on-overflow which will wake-up PIC
PS1-PS0 Value
✓ T2CKPS1 – T2CKPS0: Timer2 00 1:1
Input Clock Prescaler Select bit
01 1:4
1x 1:16
▪ 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
✓ PR2 value:
1
PR2 = −1
f PWM 4 TOSC Pre
✓ CCPxCON register
- - CCPxX CCPxY CCPxM3 CCPxM2 CCPxM1 CCPxM0
7 6 5 4 3 2 1 0 CCPxX CCPxY
−4 1
0.25 10 = Value 1
4 10 6
CCPR2L = 00011001;
CCP2CON = 00001100;
TMR2ON = 1; // Timer 2 is ON
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
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
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
void main() {
enable_interrupts(INT_TIMER0); → TMR0IE = 1
enable_interrupts(GlOBAL); → GIE = 1
}
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.
void main() {
set_tris_b(0xF0);
enable_interrupts(INT_RB); → RBIE = 1
enable_interrupts(global); → GIE = 1
}
1 2 3 4 5 6
Timer 0 Timer 1 Timer 2 Speed meas. PWM - Speed
ADC0802-ADC0804
ADCON1
▪ The A/D Result register pair will NOT be updated with the
partially completed A/D conversion sample
#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();
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
RC4/SDI/SDA
I2C bus Serial
Data
MCU Sensor ADC EEPROM MCU Line
Master Slave Slave Slave Slave
SDA
Idle Idle
Status Status
SDA SDA
SCL SCL
Read 1 byte
Read
Read multi-byte
Write 1 byte
Write
Write multi-byte
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
AK AK AK Data (8 bit)
Slave
AK AK AK
NAK Stop
AK AK NAK SP
Master
Slave AK AK AK
AK AK AK
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
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.
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
RS
PIC RW
E
Device Address D4 – D7
Selection
RC4
RC3
• SDA is sampled low when SCL goes from low to high A bus collision
• SCL goes low before SDA is asserted low occurs
✓ 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
✓ 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
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
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
TXSTA
RCSTA
Synchronous mode:
1: Enables continuous receive until enable bit CREN is cleared (CREN
overrides SREN)
0: Disables continuous receive
✓ 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
IC MAX232
14 25
13 1
25 14
https://machviet.com/bo-dieu-khien-may-cnc-
2-truc-v5-1.html
RS232 cable
Arduino Uno
connect with PC
through COM 1
1 5
4
Dr. Dang Phuoc Vinh Faculty of Mechanical Engineering
400
Virtual Serial Port Driver
Terminal Software
char c;
c = getch();
Tools
Current
Folder
Write data
serialPort1.Write("1");
Read data
String docdulieu = comport_1.ReadExisting().ToString();