1
PIC PIC PIC PIC MicroControllerMicroControllerMicroControllerMicroController TrainingTrainingTrainingTraining
Conduct by : Bill Conduct by : Bill Conduct by : Bill Conduct by : Bill Sim Sim Sim Sim [email protected]@[email protected]@yahoo.com
2
PracticalMicrochip PIC16F877A
Development using MikroC( Software/Hardware)
Date : 28 Aug 08
PICDEM 2 Plus Board
Conduct by : Bill Conduct by : Bill Conduct by : Bill Conduct by : Bill Sim Sim Sim Sim [email protected]@[email protected]@yahoo.com
3
Topics covered
Digital I/O
Hardware interrupt
Timers interrupt
Serial port
Read/Write Internal EEProm
ADC Measurement
LCD display
Pulse Width Modulation - PWM
IIC
Support
Boot loader download
Serial port programmer
External EEProm programming
Real Time Clock
DAC Measurement
QL200 PIC Development Board ( China )
PICDEMO2 Development Board
4
PICDEMO2 PIC Development Board
9V Power
Serial Port
Program download port
LED displayRB4-RB1
Resetbutton
RA4 Button
RB0/Interrupt Button
LCD Display
Analog input RA0
20MHZ Crystal
5
PICDEMO2 PIC Development Board
Interface wiring position
6
General Information
7
Why Need Microcontroller
� Need intelligent in the hardware
� Simplify hardware circuit by firmware
� Easy to modify/upgrade for new requirement
� Use less external components ( e.g. build in Analog-to-Digital converter )
Microcontroller
( Intelligent )Output
(control)
Sensors(Analog/Digital Input)
� Type of microcontrollers:
- Microchip – PIC series such as PIC84, PIC16F877
- Intel – 8051
- Atmel – AT90S8535
- Motorola – 68HC11
- Others
8
Microcontroller
� A single-chip( semiconductor) computer
� Incorporate the supporting chip such memories, input/out, ADC, clock
circuit … into a single chip
� For simple application, it can operate by itself with minimum components.
� Operate on a set of instructions ( “program”). It fetches the instructions from
it program memory , decode the instruction and then execute the required
operation.
� Traditionally programmed by assembly language, but difficult to learn and
maintain. Also assembly language different significantly from controller to
controller.
� High level programming language use are C-language or BASIC
� Mostly are 8 bits , but 16bit or 32 bit microcontroller also available
9
Microcontroller
� Operate in RISC ( reduced instruction set computer) – data is 8 bits, but
instruction word in 12, 14 or 16 bits to allow the instructions to fetch and
execute in one cycle thus speed up the execution process
[ CISC ( Complex Instruction Set Computer) – both data and instructions are
8 bits wide. CISC microcontroller usually has more than 200 instruction.
Code and data are on the same bus and cannot be fetched simultaneously ]
microprocessor
Address decoder
data
addressA
ddre
ss
Inp
uts
/ O
utp
uts
cir
cu
it
Memory bank
Mem
ory
Control signal
Read/write
A microprocessor system
CPUROM
RAM
I /O PortsDigital / ADC / UART … etc
microcontroller
Timer
10
Why use PIC ?
� Supported by C language, BASIC
� Have build in Digital I/O and Analog inputs
� Digital/Analog pins are configurable
� Build in flash program memory, EERPOM data memory and data memory
� Build in oscillator circuit( R/C – low speed ) or external oscillator
� Low power and flexible in supply voltage
� 1K to 32K bytes of flash EEProm program memory
� Timers, interrupts
� 33 input ( Analog/Digital ) or output pin
� Support USART, SPI and I2C
� Operating clock from 4MHZ to 40 MHZ
� Flexible voltage supply from 2V (battery) to 5.5V
11
PIC Microcontroller Architecture
� Power supply – range from 2V to 5.5 Volt. Some may have standby feature
(in uA current) to allow operate by standby battery.
� Power Reset/Reset input – use to reset or initialize the microcontroller
externally. It is connected to an R/C circuit which create a reset pulse at
power up. It also include a push button for user to reset the circuit if required.
� Clock – the heart beat of a microcontroller. Can be internal R/C, external
R/C , crystal (high speed and accurate ). All instruction set execution speed
is a multiple of the clock cycle. For PIC, an instruction cycle takes 4 clock
periods.
� Memory – RAM, Flash EEProm ( program and data memory)
RAM – general purpose memory to store data in a program
Flash EEProm( program memory ) – use to store user program. Nonvolatile
and fast. Can be reprogrammed . Normally range from 1K to 32K or higher
depending on the microcontroller.
Flash EEprom (data memory ) – use to store data that required for next
power up operation. Range from 256 to few Kbytes. Can be programmed by
application software.
12
� Timer/counter ( general purpose ) – a counter that is driven from external or
internal clock. It can be 8 bit or 16 bit and can be software controlled. The
counter initial value can be preloaded. After start counting and reaches
overflow, an interrupt will occur or an internal bit will change state to allow
user to write application. User will then reprogram the counter , do all the
necessary bits reset and start counter/timer again.
� Watchdog timer – use to detect a system problem, such as hang up.
Commonly use in real time system where the successful termination of one
or more activities must be check regularly.
PIC Microcontroller Architecture
13
� Interrupt – an interrupt causes the microcontroller to response to
external/internal events immediately when it occurs without the need to
check on the events. When interrupt occur, the microcontroller will stop its
normal operation, save up all the required information and go to execute an
special portion of program called interrupt service routine (ISR). After the
execution of the ISR, the microcontroller will resume its normal operation.
For bigger system, there is different level of priority for interrupt from
different devices which can be programmed.
� Brown-out Detector – reset the microcontroller when the power supply
voltage falls below a certain value. This prevents the unpredictable operation
at abnormal power supply and also prevent the EEprom from corrupted.
PIC Microcontroller Architecture
� Sleep mode
consume minimum power ( in uA ) , only certain intended monitoring is
working to allow the circuit to work with battery. Wake up from sleeping
mode when there is a reset or the monitoring device is activate.
14
� Input/Outputs (build in)
Digital I/Os
Analog to Digital converters
Serial interfaces : UART, SPI, I2C
Pulse Width Modulation output
USB interface
LCD driver
Ethernet interface
Motor controller interface
PIC Microcontroller Architecture
15
Feature of PIC16F877
8ADC ( 10 bits )
2CCP(PWM)
YesI2C
YesSPI
1 hardwareUSART (Serial Port)
2Comparator
1RB0, 4 in groupExternal Interrupt
2x 8bit, 1x16bitTimers
33I/O Ports
256 byteEEProm
368 byteData Memory
8K x 14 bitProgram Memoryn (Flash EEProm)
PIC16F877AFeatures
16
Pin out of PIC16F877
ADC
Flash
Programing
RS232
Crystal
I2CPWM
Hardware
Interrupt
17
� Programming languages ( in additional to assembly language)
there are two languages : C – language and Basic Language
Recommend to use C- Language for better hardware control.
� Compiler to use
If you choose C-language, you have to use C-compiler
mikroElektronika offer a free ( with size limitation ) and easy to use
compiler with lot of examples.
Design Consideration – Programming Language
18
� Programmer to use
After compiled the program to the Hex code, you need a programmer to
download the Hex code to the microcontroller’s code memory (flash) .
3 methods :
* buy the programmer from the chip suppler
* design your own programmer.
* boot loader method
Design Consideration – Program Download
the programmer uses USB as interface to the PC.
Application program is provided for
downloading program from PC to the PIC
microcontroller.
Buy programmer PICkit2 from Microchip company
It come with the hardware and software. There is also another development
board for starter using 16F690 that you can use in conjunction with this
programmer.
19
Software
After you have the hardware made, you need to have the programmer’s
software. A free software called WinPic is the best programmer software
found so far. You can download from the following site :
http://www.nthkits.com.sg
Design your own programmer ( hardware & software )
Hardware
there are many information on internet on how to design the serial
programmer for the PIC. A simple one is to use PC’s serial port where you
suppose to get 12V from the serial port pin to program the PIC.
A slightly complicated one is to use external power adapter to provide the
12V but still use serial port for this purpose. This is useful if some PC does
not give you stable 12V
Design Consideration – Program Download
20
Boot loader method
�boot loader is a small piece of firmware that reside inside a
microcontroller’s code memory and is responsible for downloading future
application firmware developed to the microcontroller
�PIC product to use is 16F877A and above
�the boot loader and its application program used is FREEware
�boot loader firmware have to be pre-programmed only once using standard
programmer
�use serial port to download the application firmware developed
�crystal use is 20MHZ, baud rate of the serial port is 38400bps
�Boot loader’s application program , called PICdownloader, is installed on a
PC for downloading purpose
�Select the Hex file to be download, com port and the baud rate and click the
“write” button.
�Power OFF/ON the board and the firmware will be downloaded into the
controller
Design Consideration – Program Download
21
Boot loader method
http://www.microchipc.com/PIC16bootload/index.php
Reset the target board
Design Consideration – Program Download
22
Digital I/O Port A/B/C/D/E
PIC 16F877ADigital IO
A EB C D
23
Digital I/O
Your will learn :
Hardware
How to program digital I/O ports and application
How to use push button Switch and eliminate debounce
How to flash LEDs
Software
How to output byte data to hardware port
How to handle bit wise ( Input/Output ) for a hardware port
How to use delay_ms subroutine
How to make human readable flashing
24
� PortA and PortE can be configured as Digital IO or Analog input (ANx)
� Two registers need to be configured : ADCON1(A/D control register) and
TRISA(data direction register)
� Analog pins need to define as input pins
PortA/E Configuration
ADCON1Register
TRISA/ERegister
Define Digital or analog pin
Define input or output pin
PortA/E pins
Digital input or
Digital output or
Analog pin
Bits configuration
� To define portA as all digital IO,
ADCON1 = 0x06;
� To define portA as all output pins
TRISA = 0x00;
� To define portA as all input pins
TRISA = 0xff;
For RA0 to RA3, RA5, RE0 to RE2
Note : RA4 is open collector pin
25
� The configuration table for ANCON1 is shown below :
only the first 4 bits is used
ANCON1 Configuration
26
� PortA/B/C/D/E can be configured as Digital IO via data direction
registers TRISA, TRISB,TRISC , TRISD & TRISE
PortA/B/C/D/E Configuration
TRISXRegister
Define Digital or analog pin for PORTA/B/C/D/E where X = A or B or C or D
Digital input or
Digital outputBits configuration
For example ,to define Port D , bit 0 to 3 as digital input and bit 4 to 7 as
digital output, TRISD = 0x0f;
27
Some C Programming statements
�Write to a port or register byte wise
TRISB = 0xff;
PORTB = 0x0a;
�Read from a port or register byte wise
If ( PORTB = = 0x38 ) { … }
�Write to port or register bit wise
PORTB.F1 = 1; // bit 1 of PORTB
�Read from a port or register bit wise
If ( PORTB .F0 = = 0 ) { … }
If ( ( PORTB & 0x01) == 0x00 ) { … }
�Complement a port
PORTB = ~PORTB ; // 1 become 0 , 0 become 1
MikroC Statements
28
Some C Programming statements
�Delay time in milliseconds
delay_ms (int number); e.g. delay_ms(500);
�Delay time in microseconds
delay_us(int number); e.g. delay_us(200);
�Variable delay time in milliseconds
int mydelay;
mydelay = 300;
Vdelay_ms( mydelay);
MikroC Statements
29
Interrupts
•Hardware Interrupt
•Timer0 Interrupt
•Multiple Interrupt
30
Your will learn :
Hardware
What is hardware interrupt
How use hardware interrupt in 16F877A
Parameters that need to consider for interrupt
Software
How to write interrupt service routine
How to program INTCON & OPTION_REG registers
Timer 0 interrupt
How to handle multiple interrupt
Hardware Interrupt
31
� Interrupt is used to reduce the workload of the CPU. A special job will
only be done when the interrupt occurs. This special job is placed as part
of the software program called interrupt service routine (ISR) . CPU will
perform its normal operation till an interrupt occur. When it happens, the
CPU will stop its normal operation, save up all the registers and then
execute the interrupt service routine till its completion. It will then back
to its normal operation.
� When enter into ISR, it is a good practice to disable the interrupt . This is
to prevent response to another interrupt when the previous ISR has not
completed yet. Before exit the ISR, the interrupt need to be enabled and
ready for another hardware interrupt.
Interrupt
� For 16F877A, there are 3 user defined interrupts ( in additional to
16F877’s standard peripheral interrupts). They are :
hardware interrupt ( RB0/INT) , Timer0 interrupt and RB4-RB7 group
interrupt
� Other interrupt provided for the feature of 16F877 is called peripheral
interrupt and is important for assembly language or C – library
programmer
32
Perform specialJobs (interrupt
Service routine )
uControllerperforming normal
operation
Interrupt Flow Chart
InterruptOccurs ?
Disable interrupt/ Save all current jobs
Completed ?
Enable interruptResume current jobs
N
Y
Y
Start
Interrupt
N
ISR
33
� registers that involved in the interrupt operation, INTCON (0x0b) register
and OPTION_REG (0x81)
Hardware Interrupt
GIE - Global Interrupt Enable bit
INTE – RB0/INT External interrupt enable bit
INTCON (0x0b)
GIE PEIE T0IE INTE RBIE T0IF INTF RBIF
Bit 0Bit 7 Default : 0000 000x
� INTCON bit 3, known as RBIE, if set to 1, will inform PIC that RB4 to RB7
will be used as interrupt input group. They can not be select individually.
� When interrupt occurs, the interrupt flag , bit 1 of INTCON register is set.
When this occur, the PIC microcontroller will not respond to any further
interrupt .
Enable occur
34
INTCON Register (0x0b)
For External interrupt RB0/INT
GIE PEIE T0IE INTE RBIE T0IF INTF RBIF Bit 0Bit 7
Default : 0000 000x
Enable Occur flagGlobal Interrupt Enable bit
For timer-0 (TMR0) - interrupt
For peripheral interrupt RB7 – RB4 (all) as interrupt
Hardware Interrupt
35
� The Peripheral interrupt enable bit ( PEIE ) have to work with another two
sets of interrupt enable registers and flag for a specific features provided by
PIC 16F877 . they are :
PIE1/ PIR1 for
Parallel Slave Port Read/Write Interrupt (PSPIE)
A/D Converter Interrupt (ADIE)
USART Receive Interrupt ( RCIE)
USART Transmit Interrupt (TXIE)
Synchronous Serial Port Interrupt (SSPIE)
CCP1 interrupt (CCP1IE)
TMR2 to PR2 Match Interrupt (TMR2IE)
TMR1 Overflow Interrupt (TMR1IE)
Hardware Interrupt
INTCON Register (0x0b)
36
� PIE2/ PIR2 for
Comparator Interrupt (CMIE)
EEPROM Write Operation Interrupt (EEIE)
Bus Collision Interrupt (BCLIE)
CCP2 Interrupt (CCP2IE)
� The C language function library provided by vendor will take care of all
these standard feature interrupt. We will focus on non-peripheral related
interrupts.
INTCON Register (0x0b)
Hardware Interrupt
37
� Option register ,OPTION_REG, bit 6 , INTEDG ( Interrupt Edge), when
set, will cause the PIC to be interrupt on rising edge. When clear, the PIC
will be interrupted on falling edge. The default interrupt setting is on rising
edge.
Hardware Interrupt
INTEDG = 1 INTEDG = 0
RBPU INTEDG T0CS T0SE PSA PS2 PS1 PS0
Bit 0Bit 7
INTEDG – Interrupt Trigger Edge
OPTION_REG (0x81)
Default : 1111 1111
� When PB4 to PB7 are used as interrupt ,
you cannot select individual pins on
PORTB to serve as an interrupt input. It
may be not so practical to use them as
interrupt as you can not make use of these
pin as I/O.
RB0/INT
INTEDG = 1 INTEDG = 0
38
� Option register ,OPTION_REG, bit 7 , RBPU, when clear (=0), will turn on
PORTB’s internal pull-up (weak) as a ‘high’. The respective internal pull-up
of the PORTB’s pin will automatically turn-off when the PORTB’ pin is
assign as output.
Hardware Interrupt
RBPU INTEDG T0CS T0SE PSA PS2 PS1 PS0
Bit 0Bit 7
OPTION_REG (0x81)
Default : 1111 1111
16f877
RB0
5V
Depending on circuit designed
/RBPU = 0
39
OPTION_REG Register (0x81)
RBPU INTEDG T0CS T0SE PSA PS2 PS1 PS0 Bit 0Bit 7
Default : 1111 1111
� OPTION_REG register contains various control bits to configure the TMR0
prescaler / WDT postscaler, external interrupt(RB0/INT), TMR0 and weak
pull up on PORTB
Prescaler
PORTB pull-up
RB0/INT interrupt
edge type
TMR0 Clock source
TMR0 Source
edge type
Prescaler assign to
WDT or Timer0
Prescaler rate select
Hardware Interrupt
40INTEDG = 1 INTEDG = 0
RBPU INTEDG T0CS T0SE PSA PS2 PS1 PS0
Bit 0Bit 7
INTEDG – Interrupt Trigger Edge
OPTION_REG (0x81)
Default : 1111 1111
Hardware Interrupt
OPTION_REG Register (0x81)
41
Some MikroC Programming statements
Hardware Interrupt
INTCON.F7=1; //enable global interrupt
INTCON.F6=1; // enable all peripheral interrupt
INTCON.F4=1; //set PB0 as the external interrupt
OPTION_REG.F6=0; //interrupt at negative edge
OPTION_REG.F7=0; //turnon RB0's internal pullup (weak)
void interrupt() // funciton name of interrupt service routine
{
INTCON.F4=0; //disable RB0/INT
… ISR jobs …
INTCON.F1=0; //MUST HAVE -- clear interrupt flag
INTCON.F4=1; //enable global interrupt
}
Hardware Interrupt
42
Timer Interrupt
43
� Timer0 , TMR0, is a 8 bit binary up counter
� Count driven by external or internal clock source.
� TMR0 register stores the counter value which can be reset or preloaded
with value
� Count increase with each input pulse until TMR0 overflow
(from 0xFF to 0x00)
� Overflow triggered timer0 interrupt. The interrupt service routine will then
be executed.
Timer Interrupt
44
� TMR0 register and prescaler relationship
Timer Interrupt
Load TMR0=0Prescale
Set RB1=~RB1Load TMR0=0
After 255 Pulse by timer0
d
For a 20MHZ crystal,
d= ((# of tick) * 4 * Prescaler * 1000 )/(clock frequency)
Case 1 : Prescaler = 1
d = 255 * 4 * 1 * 1000 / 20 000 000 = 51 usCase 2 : Prescaler = 1:2
d = 255 * 4 * 2 * 1000 / 20 000 000 = 102 usCase 3 : Prescaler = 1
d = 255 * 4 * 256 * 1000 / 20 000 000 = 13.6msCase 4 : Prescaler = 1
d = 95 * 4 * 256 * 1000 / 20 000 000 = 4.86 ms
d
Interrupt
45
Multiple Interrupts
46
Multiple Interrupt
� When there is multiple interrupt requirement , the interrupt service function
must check for what interrupt has happen and then execute the respective
interrupt handler. E.g. RB0/INT or TMR0 handler
� The INTCON_REG provide the flag of the interrupt.
GIE PEIE T0IE INTE RBIE T0IF INTF RBIF Bit 0Bit 7
INTCON_REG
47
Some MikroC Programming statements
Timer Interrupt
OPTION_REG = 0x18; // Prescale to WDT i.e TMR0 no prescale
void rb0_interrupt(void)
{ … jobs here …}
void tmr0_interrupt(void)
{ … jobs here …}
Multiple Interrupt
void interrupt() {
INTCON.F7 = 0; // disable further interrupt
if ((INTCON & 0x02)==0x02){rb0_interrupt(); } // check for hardware interrupt
if ((INTCON & 0x04)==0x04){tmr0_interrupt();} //check for timer0 interrupt
INTCON=0xf0; //enable global and the required interrupt
}
Multiple Interrupt
48
USART (Serial / RS232) Communication
49
� USART stands for Universal Synchronous Asynchronous Receiver
Transmitter
� RS232, Serial Port, COM Port … means the same thing
� Most of the desktop PC & engineering instrumentation still support
serial port
� Its family standard RS422 can connect many devices together using 3
wires
� For PIC 16F877, USART is access through RC7 for Receive and
RC6 for Transmit at TTL level ( hardware USART )
� A RS232 line driver need to interface with RC7/RC6 to deliver the
RS232 standard (i.e. high voltage level for long distance driving ) via
a Max232 chip.
Refer to any standard RS232 article for more detail description
USART/Com port/ Serial Port
50
� RC6/RC7 provide signal at TTL level. MAX232 converts TTL high
level to -13V and TTL low level to +13V which is good for data
transmission on long wire.
� When No transmission, the signal is “high”, start bit is “low” , Stop
bit is “high”
16F877Acircuit
RC6
RC7 MAX232(1/2)
RS232
Start bit (0)
D0 D1 D7
Stop bit (1)
t
v
Hardware USART
51
� MikroC support both software USART and hardware USART
Software USART commands
� soft_Uart_Init ( port-number, rx-pin, tx-pin, baud rate, mode)
mode = 0 : data not inverted
e.g Soft_Uart_Init( PORTB, 0,1, 9600,0); PB0 – rx, PB1-tx
� Soft_Uart_Read(&Rx_Error)
e.g do {
mychar = Soft_Uart_Init(&Rx_Error);
} while (Rx_Error);
error is normally 1 and become 0 when a byte is read from the port
� Soft_Uart_Write( character ); e.g. Soft_Uart_Write(‘A’);
MikroC Statements
52
Hardware USART Commands
� Hardware USART can support higher baud rate
� Parameters need to setup for communication – only baud rate is needed
Baud rate : 38400 or others supported baud rate
Rest of parameters are set, by the MikroC as follows :
number of data bit : 8 bits
number of stop bit : 1
Parity bit : N ( no parity )
e.g. USART_init(38400);
� 4 C-statements involve in serial communication
Char USART_Write(char data) - 1 byte
Char USART_Read(Void)
Void USART_init( const long baudrate)
Char USART_data_ready(void)
MikroC Statements
53
Read/Write Internal Data EEProm
54
� 16F877 has 256 byte of data memory and 8K of program memory that
allow data and program remain in the device when power of switch off.
� The 6 SFR ( Special Function Register) use to support these functions are :
EECON1, EECON2( Not a physical register ), EEDATH: EEDATA
( Holds 14 bits of data for Read/Write ) and EEADRH:EEADR ( holds
the 13 bit address of the program memory location being access ).
Read/Write to Internal Data EEProm
55
Read/Write to Internal Data EEProm
56
� In MikroC, to write and read to internal EEProm, use the following
statements :
Unsigned short eeprom_read(unsigned short address);
e.g. char read_data;
read_data = eeprom_read(0x30);
void eeprom_write(unsigned integer address, unsigned short data);
e.g. eeprom_write(0x30, 0x11);
MikroC Statements
57
LCD Display
58
LCD Display
PIC 16F877A
LCD
RD7-RD3
RA1 - RS
RA2 - R/W
RA3 - E
� The interface to LCD display is done through a set of data bit and control bits
� For the demo circuit, it uses 4 bits, RD7-RD3, for data instead of full 8 bits
� For MikroC, there is a predefine hardware interface as specified in the
programming manual page 241, all LCD pins must connected to a single port.
� If you are using different hardware connection, normally the case, you can use
the programming generator ( or you can write your own code ) provided by
MikroC to generate the functions required to program the LCD based on your
hardware connection (e.g. see below)( called LCD4 Optimum Module by Warren Schroeder April 25, 2007 )
59
MiKroC’s LCD Library’s hardware requirement
PIC 16F877A
LCD
RB2-RB5
RB0 - RS
RB1 - E
Lcd_Config (port-name, RS-pin, EN-pin, R/W-pin, D7-pin, D6-pin, D5-pin, D4-pin)
R/W-pin is not use, should connect to ground (always write)
e.g. Lcd_Config ( &PORTB, 0,1,2,3,4,5)
Lcd_Init(Port-name ); Lcd_Init(&PORTB);
Lcd_Out(row, column,text); Lcd_Out(1,2,”MyTest”);
Lcd_Out_Cp(text); Lcd_Out(“Hello); output text from the Current Position
Lcd_Chr ( row, column, character); Lcd_Chr(1,2,’M’);
Lcd_Chr_Cp(character); Lcd_Chr_Cp(‘M’);
All pins must within a Port.
Otherwise cannot use the library
LCD Display
60For PICDEM2
Use when the LCD
interface pins involve more
than one PORT
�Select PIC type
�Define RS pin connection
�Define E pin connection
�Define Data pins ( 4 pins)
connection
�In the software, set
always write mode
( PORTA.F2 = 0 for /W )
Program Generator
LCD Display
61
LCD Application Constant
Lcd_Cmd(command constant);
LCD_SHIFT_RIGHT
LCD_SHIFT_LEFT
LCD_MOVE_CURSOR_RIGHT
LCD_MOVE_CURSOR_LEFT
LCD_TURN_OFF
LCD_TURN_ON
LCD_BLINK-CURSOR-ON
LCD_FORTH_ROW
LCD_THIRD_ROW
LCD_SECOND_ROW
LCD_FIRST_ROW
LCD_RETURN_HOME
LCD_CLEAR
Command constant
62
Analog Measurement
(Analog-to-Digital Converter)
63
Purpose of ADC
� To measure an analog voltage (e.g. sensor) input and convert to digital
for the micro-controller to interpret and make decision
� Sensor/transducer produced very small analog voltage . In some cases it
could be uV ( micro-volt ) and it needs an analog amplifier to amplify
the signal to a measurable analog voltage.
� In order for a computer/microprocessor/micro-controller to interpret the
analog signal, the analog signal need to convert to digital , for at least 8
bits or more. ( 10 bits for PIC16F877 )
� If the analog signal is small, you have to use lower Vref in PIC16F877
ADC measurement in order to get more accurate digital measurement
Sensor A ADC
64
ADC Block Diagram
AN7
AN6
AN5
AN4
AN3
AN2
AN1
AN0
CS2-CS0
ADC Converter
Verf+
Reference Voltage
Verf-
VSS
VDD
10 bits
PCFG<3:0>
65
ADC setup
AN0
AN1
VDD
VDDVSS
VSS
16F877
2
3
� 3 Registers involve in the ADC Operation : TRISA , ADCON1 and
ADCON0
Vref
Vref can be VDD or other value
AN7 AN2AN6 AN5 AN3 AN1 AN0AN4
RE2 RA2RE1 RE0 RA3 RA1 RA0RA5
Symbol
Hardware port
V = (bits value) *(Vref / 1024)
When measure small voltage , it is more accurate to supply own Vref
Due to VDD may vary , it is more accurate to use a Vrefinstead of using VDD as Vref
10 bits ADC converter
66
What need to be set for measurement ?
� How many analog ports to use and Vref to use : PCFG3-PCFG0 in
ANCON1
� Set the respective hardware ports to be input for ADC operation
TRISA and/or TRISE
� Define measurement data to be read is Right justify or Left justify
ADFM bit in ANCON1
� Select AD conversion clock : ADCS2 in ANCON1 and ADCS1 &
ADCS0 in ANCON0( A/D control register 0)
� For each channel to be measured, select the channel number and set
ADC to be ON : CHS2-CHS0 bits and ADON bit in ANCON0
� For each channel selected, set the GO//Done bit in ANCON0 to “1”
and start ADC measurement. When ADC measurement completed,
the GO//Done bit will be set to “0”. 10us Conversion time should be
sufficient ( refer to data sheet for detail calculation)
67
� When use AN0 & AN1 as input, from the configuration table, select PCFG3
to PCFG0 to be 0100
Analog to Digital conversion setup
ADCS1GO//Done
ADCS0 CHS2 CHS1 CHS0 - ADON ADCON0
ADFM PCFG2ADCS2 - PCFG3 PCFG1 PCFG0
ADCON1
-
Select AD conversion clock
110 = FOSC/64 for 20MHZ crystal OK
Right justify
ADRESH,ADRESL = 000000xx,xxxxxxxx
1
1
Select channel 0
1Enable A/D measurement
AN0 ,AN1,AN3– analog, AN2, AN4 – AN7 all digitalVREF+ = VDD, VREF = Vss ( internal )
TRISA = 0x0b; PortA0, PortA1 & PortA3 are inputs, PortA2, PortA4 – PortA7 are outputs
= 1 Start A/D conversion=0A/D conversion completed
1 0 0 0 0
0 1 0 0
68
� The configuration table for ANCON1 is shown below :
only the first 4 bits is used
ANCON1 Configuration
69
� When ports are selected for analog input, the conversion clock rate ( use in
conjunction with ADCON0 ) and the ADC read result format are set
according to the following format :
ANCON1 Configuration
70
ADCON0 Configuration
ADCON1ADCON0
71
/* Read AN1 port , use FOSC/64 */
ADCON0= 0x89; // importnant : switch port first, don't measure
delay_ms(100); // important : for it to stabilize
ADCON0 = 0x8d; // AN1 read
delay_ms(100);
while( ADCON0 & 0x04){} // check conversion completed ?
dataL= ADRESL; // read result
dataH=ADRESH;
write_ADC_result(dataH,dataL); // output result to display
Important ADC Program
ADC Measurement Steps
72
Pulse Width Modulation
73
� PWM stands for Pulse Width Modulation
� PWM is basically sending a pulse with various duty cycle so the receiver
device, which is a PWM operated, can perform a specific function.
Example : Servo motor, beeper, flash light …etc
Pulse Width Modulation
� When the pulse width is longer, the flashing LED will be brighter or the
beeper will have different sound frequency. For PWM servo motor, the
motor will turn in different direction.
� PWM pulse can be generated by pulse a output pin the “Hi” & “Lo” with
time delay to generate the pulse or can be done by a specific PWM output
pins
� For 16F877, it has two pins RC1 ( CCP2 ) and RC2 (CCP1) that response
to generate the PWM pulses
w
T
Duty cycle = W / T * 100%
74
In MiKroC the statements use to generate the PWM are follows :
� void PWM_Init(long freq); - initialize PWM frequency
void PWM_Change_Duty( char duty_ratio ); - set duty cycle
where duty_ratio ranges from 0 to 255
duty cycle = ( % * 255 ) / 100
50% duty cycle , duty_ratio = 127
100% duty cycle, duty_ratio = 255
� void PWM_Start (void) ; - start PWM
� void PWM_Stop (void); - stop PWM
� For 16F877 chip, there is two PWMs, you can use PWM1 and PWM2
syntax to generate two different PWM pulse
Pulse Width Modulation
75
PWM1_Init(5000);
PWM2_Init(5000);
PWM1_Change_Duty(127); // 50% duty cycle
PWM2_change_Duty(20); // 7.84% duty cycle
PWM1_start();
PWM2_start(); // determine PWM to start
while( PORTA.F4 == 0){} // when button release, stop
PWM1_stop();
PWM2_stop();
RC1 ( CCP2- PWM2 ) RC2 ( CCP1- PWM1 )
Pulse Width Modulation
In MiKroC the statements example
76
� For motor control, pulses with various duty cycle are used for DC Motor
speed control and servo motor position control
� For servo motor position control, different pulse width will cause the
motor to rotate at different angle.
� The general guide line for servo motor rotation are as follows :
PWM for Servo Motor Control
1 ms
18 ms
Left
1.5 ms
18 ms
center2.0 ms
18 ms
right
77
IIC Serial Communication
78
� System level serial data communication method
� Need two signal lines : data (SDA) and clock (SCL)
� Allow a master device control up to 1023 other devices
� Signal lines have 5V pull up
� Each data bit is accompany by a clock pulse
� Clock speed is programmed by preload the baud rate generator up to 1MHZ
7 6 5 4 3 1 02
5V
Master Slave Slave
4.7K
4.7K
acknowledgementstart
SDA
SCL
SDA
SCL
IIC Serial Communication
79
Interface to a 256K EEProm
IIC Serial Communication
16F877Acircuit
RC4
RC3
SDA
SCL
5V
A2
A0A1
SDA
SCL
5
6
8
4
24LC256
256K IIC Serial EEProm
5V
4.7K
4.7K
80
In MiKroC the statements use in IIC communication are follows :
� void I2C_Init(long clock);
� char I2C_Start(void);
� void I2C_repeated_Start(void);
� char I2C_Is_Idle(void);
� char I2C_Rd(char ack); ack=0 means no acknowledge
� char I2C_Wr(char data);
� void I2C_Stop(void);
IIC Serial Communication
81
…
I2C_Start();
I2C_Wr(0xA0); //control byte for write
I2C_Wr(addrhighbyte); //address to write - high byte
I2C_Wr(addrlowbyte); //address to write - low byte
I2C_Wr(data); //data
I2C_Stop();
…
Write Byte
IIC Serial Communication
82
…
I2C_Start();
I2C_Wr(0xA0); //control byte for write
I2C_Wr(addrhighbyte); //address to read high - byte
I2C_Wr(addrlowbyte); //address to read low - byte
I2C_Repeated_Start();
I2C_Wr(0xA1); //control byte for read
data = I2C_Rd(0u);
I2C_Stop();
…
Random read address
IIC Serial Communication
83
Read/Write External EEprom93LC46 using I/O Ports
QL200 PIC Development Board ( China )
84
16F877Acircuit
93LC46
RC2
RC4
Functional block diagram
RC3RC5
CS
DO
CLKDI
VCC
VSS
NCNC
Parameters:
38400
8 data bits
1 stop bit
N parityMemory locations to write/read are :
0x01, 0x02 ,0x3f ,0x18 ,0x2a
External EEprom – using I/O
85
� 93LC46 is a 1024-bit non-volatile, serial EEProm.
� 6 bit of address and 16 bit of data –> total = 64 x 16 = 1024 bit
� 4 signal pins : CS – chip select, SK – clock pin, DI – data in,
DO-data out.
� Provide write enable or disable function to protect the data
� All functions such as read, write, write enable … etc required a
predefine function header before the address and/or data – see
datasheet for detail
� Write data to a address – provide 6 bits of address follow by 16 bits
of data to the DI pin
� Read data at address – provide 6 bit of address and read data from the
DO pin
� 4 important functions : Write enable, write disable, read and write
External EEprom – using I/O
86
Write enable
Write disable
Pin Layout
External EEprom – using I/O
87
Write data operationmust have
External EEprom – using I/O
88
Read data operation
External EEprom – using I/O
89
� Program Methodolgy
� DI1, DI0 – input data bit high, low
� CS1, CS0 – chip select bit high, low
� Clk - generate 1 clock pulse
void CS1(void) { PORTC.F2=1; delay_us(200); }
void CS0(void) { PORTC.F2=0; delay_us(200); }
void DI1(void) { PORTC.F5=1; delay_us(200); }
void DI0(void) { PORTC.F5=0; delay_us(200); }
void clk (void) {PORTC.F3 = 0; delay_us(100);PORTC.F3 = 1; delay_us(200);PORTC.F3 = 0; delay_us(100);}
External EEprom – using I/O
90
Real Time Clock
QL200 PIC Development Board ( China )
91
Your will learn :
Hardware
Function of Real Time Clock
Software
How to program the Real Time Clock :
Write Date and Time
Read Date and Time
Protect / Un-Protect RTC for writing
Real Time Clock (RTC)
92
� Program the date and time with the following information :
Date : 23 /07/08 Time : 14:50:00
� Read back the Date and time every seconds and display on LCD and on serial port
Real Time Clock Project
16F877Acircuit
RTC DS1302
RB0
RB4RB5
CLK
I/ORST
Parameters:
38400
8 data bits
1 stop bit
N parity
Date:23/07/08Time:14:59:20
LCD Display
Functional block diagram
93
Real Time Clock (RTC)
� RTC counts Hour:Minute:Second and Day/Month/Year with other features
such as 12/24 hour, AM/PM option
� RTC used here is DS1302, 8 pins IC(3 signal wires), 2V to 5.5V operation
� RTC chip need to work with an crystal oscillator circuit (32.768kHz)
� RTC also provide serial interface for data I/O ( read/write ) and clock
� Two power supplies input for RTC, One for battery and one for normal DC
power
� Date and Time is set through the programming to a set of predefine memory
location with the desire Date and Time value in “human understandable”
value. These value are written directly to the memory location in “HEX”
format without conversion to hex value.
e.g. 14 hr, 20 min, 59 sec write as 0x14, 0x20 and 0x59
94
Real Time Clock (RTC)
� Memory locations for writing and reading of Date and Time
Location
for read
Location
for write
Max = 5 ,need 3 bit Max = 9 , need 4 bit
95
Digital to Analog Converter
TLC5615C
QL200 PIC Development Board ( China )
96
Digital to Analog Converter
TLC5615C
10 bit CMOS voltage output DAC
3 wire interface
High impedance reference input
8 pin package
97
Digital to Analog Converter
� To program the TLC5615C , need to send 16 bits of serial data into the
shift register of TLC5615C
� Only 10 bits are for voltage programming :
Vout = 2 * (V ) * refin
V
1024
10 bits
L7 L6 L5 L4 L3 L2 L1 L00 0 0 0 0 0 H1 H0
Vout = 2 * (2) * V
1024
(01 10101011)
If Vrefin = 2.0v, VH = 0x02 VL= 0xab;
VH – High byte VL – Low byte
Vout
= 4 * (683/1024)
= 2.67 v
98
Digital to Analog Converter
� The bit pattern send to the TLC5615C serially are :
0,0 ,L0,L1,L2,L3,L4,L5,L6,L7,H0,H1,D,D,D,D
where D – dummy bit, 0 - zero
� Every data bit will send to the TLC5615C when the clock is at high
transition.
� /CS must be “low” before the first clock take place and must be “high”
after the last 16th bit is clocked.
99
Digital to Analog Converter
100
Digital to Analog Converter Project
PIC 16F877A
To advance the DAC output to different value
RC2 - CS
RC3 - SCLK
RC5 - DIN
RA0
RB0
RB7
Lowest 8 DAC bit to PORTB display
REF In = VDD
TLC 5615D/A
VOUT
Functional block diagram
101
Digital to Analog Converter
� Programming sequence are :
/CS = 0
send in 4 clock pulse ( Din don’t care – dummy )
Reverse the bit sequence for High byte and low byte
for each of the 10 bit ( high or low ), send in the clock to clock in the bit
send in two clock with DIN= 0
/CS = 1
102
Some Useful Functions
103
Read the eeprom addressEEProm_read (address)
Write the eeprom address with the dataEEProm_Write (address, data)
Software delay using program variableVdelay_ms ( variable)
Software delay in millisecondsDelay_ms (number)
Software delay in microsecondsDelay_us (number)
Return (bit 31-24 ) of a numberHighest (number)
Return ( bit 23- 16 )of a numberHigher (number)
Return ( bit 15- 8 ) of a numberHi (number)
Return ( bit 7- 0 ) of a numberLo (number)
Descriptionfunction
Useful functions
104
Concert a character to lowercaseTolower
Convert a character to uppercaseToupper
Return a 1 if is is uppercaseIsupper
Return a 1 if is is printable ( decimal 32-126)Isprint
Return a 1 if is lowercaseIslower
Return a 1 if is 0-9Isdigit
Return a 1 if is control character ( decimal 0-31 and 127)Isntrl
Return a 1 if it is a-z, A-ZIsalpha
Return a 1 if is alphanumeric ( a-z. A-Z, 0-9)Isalnum
Descriptionfunction
Useful functions
105
Return the absolute valueAbs
Convert ASCII character to floating point numberAtof
Convert ASCII character to integerAtoi
Convert ASCII to long integerAtol
Return the greater of two integersMax
Convert input string consisting of hex digits into integerXtoi
Generate a seed for function rand to callSrand
Return a random number between 0 and 32767. srand() must be called firstRand
Return the lesser of two integersMin
Descriptionfunction
Useful functions
106
Return the length of a stringStrlen
Copy one string into another oneStrcpy, strncpy
Compare two stringsStrcmp, strncmp
Locate the first occurrence of a character in a stringStrchar, strpbrk
Append two stringsStrcat, strncat
Descriptionfunction
Useful functions
107
Convert a decimal number into BCDDec2Bcd
Convert a BCD number into decimalBcd2Dec
Convert a float into stringFloatToStr
Convert a long into stringLongToStr
Convert an integer into stringIntToStr
Convert an unsigned word into stringWordToStr
Convert a short into stringshortToStr
Convert a byte into stringByteToStr
Descriptionfunction
Useful functions
108
Top Related