outline – chapter 10a picc c o a uat o oa dmicro ...me.metu.edu.tr/courses/me534/protected/me 534...

17
Outline Chapter 10a Development Procedure Hardware – Software CCS C Compiler – Differences Preprocessor Commands CCS C Functions CCS C Functions Serial Port Digital I/O Ports ADC ADC – PWM – Counters Interrupts Misc. functions Chapter 10a ME 534 2 PICMicro Evaluation Board PICMicro Evaluation Board (“EVB”)i ifi ll (“EVB”) is specifically developed for prototyping embedded control systems. Pots embedded control systems. It includes a bunch of useful features: LEDs RS-232 Interface Linear voltage regulator 2 pots/trimmers LEDs PBs 2 pots/trimmers 2 LEDs 2 pushbuttons Pin-headers for easy access to ports of 18F4520 Chapter 10a ME 534 3 Basic Circuitry Chapter 10a ME 534 4 Basic Circuitry (Cont’d) Chapter 10a ME 534 5

Upload: truongdien

Post on 02-May-2018

221 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

Outline – Chapter 10ap• Development Procedure

– Hardware– Software

• CCS C Compilerp– Differences

• Preprocessor Commands• CCS C Functions• CCS C Functions

– Serial Port– Digital I/O Ports

ADC– ADC– PWM– Counters– Interrupts– Misc. functions

Chapter 10a ME 534 2

PICMicro Evaluation BoardC c o a uat o oa d• PICMicro Evaluation Board

(“EVB”) i ifi ll(“EVB”) is specifically developed for prototyping embedded control systems.

Potsembedded control systems.

• It includes a bunch of useful features:

LEDs – RS-232 Interface– Linear voltage regulator – 2 pots/trimmers

LEDsPBs

2 pots/trimmers– 2 LEDs– 2 pushbuttons– Pin-headers for easy access

to ports of 18F4520

Chapter 10a ME 534 3

Basic Circuitryy

Chapter 10a ME 534 4

Basic Circuitry (Cont’d)y ( )

Chapter 10a ME 534 5

Page 2: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

Features of EVB• RESET button is used to reset the microcontroller and

h i h fl hrestart the program in the flash memory.• This button is also utilized to load a new program from the PC via the

bootloader utility program.y p g

• UART is interfaced using MAX-232 chip (level converter).– If your computer does not have a serial port, you need to use a

USB-to-serial port converter.• EVB includes a number of circuit elements that mayEVB includes a number of circuit elements that may

come handy as you develop/debug your controllers:– Two pushbuttons @ pins RD0 and RD1,

T LED @ i RD2 d RD3– Two LEDs @ pins RD2 and RD3,– Two 20k pots/trimmers @ pins RA2 and RA3.

Chapter 10a ME 534 6

Building Circuits on Breadboard*g• The breadboard (“socket

board”) has many strips of ) y pmetal running underneath the sockets.Thi k it t• This makes it easy to connect components together to build circuits. g

Chapter 10a ME 534 7[*] Courtesy of Iguana Labs

Software Development

e B

utto

n

C C C

Fil

• Run PCW C Compile IDE:– Select “PCH 16 bit” from the pull-down menu box.– Choose “New>Source File” from the File Button menu.

• Type the name of your C program

– Write or edit your C program and “Save” it– When done, “Compile” your program.

• If no error is encountered, the compiler creates a “Hex” file (PICMicro machine code) under the current directory.

Chapter 10a ME 534 8

Software Development (Cont’d)So t a e e e op e t (Co t d)• Once done, click the “Write Flash”

command button:command button:– It will start to search for the

bootloader program on your PIC18F4520PIC18F4520.

– Press the reset button of your (powered) EVB.

• Tiny Bootloader utility will download the specified file to the PIC and then your program will run y p gautomatically.– Make sure to select the serial port

and the baudrate (115200 kbps)• Minimize IDE and then run

Ti B tl d and the baudrate (115200 kbps) correctly.Tiny Bootloader.

• Search (Browse) for your “Hex” file.

Chapter 10a ME 534 9

Page 3: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

Software Development (Cont’d)So t a e e e op e t (Co t d)• Close the Tiny Bootloader

Cand switch to the PCWHD Compiler IDE.– Under “Tools” (ribbon) menu ( )

and run the “Serial Port Monitor”

• In Serial Input/Output p pMonitor, choose “Configuration>Set Port Options.” Set the following:p g– Baud rate: 19200– Parity: None – Data Bits: 8Data Bits: 8– Stop Bit: 1Serial Input/Output monitor (“siow”)

will be the prime communicationmeans of 18F4520 with your PC.

Chapter 10a ME 534 10

ea s o 8 5 0 you C

CCS C CompilerCCS C Co p e• The CCS C compiler which is developed byThe CCS C compiler, which is developed by

Custom Computer Services (CCS), supports almost all devices:almost all devices:– PIC12x – PIC16x– PIC16x– PIC18x

• Compiler is quite compatible with ANSI C• Compiler is quite compatible with ANSI C. • Quality of compiled code is excellent.

– The optimizer does a good job in compressing the code.

Chapter 10a ME 534 11

CCS C Compiler (Cont’d)CCS C Co p e (Co t d)

• The supplied IDE is nicely integrated into the compiler• The supplied IDE is nicely integrated into the compiler.– IDE is well-designed– User-friendly and configurabley g– Includes a set of useful tools

• Serial Port MonitorN i l t• Numerical converter

• Disassembler and more...

• CCS C comes with lots of sample codesCCS C comes with lots of sample codes– 50++ complete projects– Sample C codes demonstrate a huge range of techniques and

features suitable for almost all PICmicros.

Chapter 10a ME 534 12

Differences with ANSI Ce e ces t S C

• Unfortunately CCS C is not fully compliant with ANSI C• Unfortunately, CCS C is not fully compliant with ANSI C. • There are certain differences (restrictions) in data types:

– All types in CCS C, (except float) are, by default, unsigned.All types in CCS C, (except float) are, by default, unsigned.– However, maybe preceded by unsigned or signed.

• Data types used in CCS C:– int1 and short defines a 1-bit number– int8 or int defines an 8-bit number (byte)– int16 and long defines a 16-bit numberint16 and long defines a 16 bit number– int32 defines a 32-bit number– char defines a 8-bit character

f f f– float defines a 32-bit floating point number

Chapter 10a ME 534 13

Page 4: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

Generic CCS C ProgramGe e c CCS C og a• A generic C program for PICmicro constitutes

– Preprocessor commands / directives:• Hardware Information

– PICMicro type, clock frequency, etc.• Configuration of PICMicro

– Configuration (mode) bitsConfiguration (mode) bits – Parameters of peripheral units

• Compiler options and other declarations– Optimization option– Program starting address, file register declarations, etc.

Main program– Main program• Initialization of peripheral units• Calling “built-in” functions for the initialized units

Chapter 10a ME 534 14

g

Preprocessor Commandsep ocesso Co a dsFollowing directives will frequently appear in our programs:

#include <18F4520.h>#fuses HS,NOWDT,NOPROTECT,NOLVP#use delay(clock=20000000)y( )#use rs232(baud=19200,xmit=PIN_C6,rcv=PIN_C7)#org 0x3F00,0x3FFF {} #opt 9

• #include <18F4520.h> specifies the header file for PIC18F4520:Includes constants and relevant hardware definitions– Includes constants and relevant hardware definitions

• #use delay(clock = ...) informs the compiler about the clock frequency (in Hz). This information is crucial for delay functions.

• #use RS232(options) designates the parameters of the serial-port communication protocol.

Chapter 10a ME 534 15

Preprocessor Commands (Cont’d)p ( )• #fuses options tells the compiler about the configuration and

operating mode of the de iceoperating mode of the device:– HS option defines the oscillator type as high-speed resonator (>> 4MHz).

• Other oscillator options are– XT (standard crystal with a typical. freq. of 4MHz)– LP (low power oscillator)– RC (resistor-capacitor oscillator)

– NOWDT option tells the compiler that no Watch Dog Timer is utilized.• A safety measure in case the execution of the your program gets out of hand!

– NOPROTECT option specifies that flash memory of PICmicro is NOTp p yprotected and thus the resident program could be read (decompiled / reviewed) without authorization.

– NOLVP option informs the compiler that no low voltage programming isNOLVP option informs the compiler that no low voltage programming is to be allowed on this device.

Chapter 10a ME 534 16

Preprocessor Commands (Cont’d)p ( )

# t t dd fi l dd {}• #org start addr,final addr {}reserves memory in flash memory (ROM). – #org 0x3F00,0x3FFF{} reserves the last 255-word

of the ROM for the bootloader (a.k.a. “operating system program” of your PICmicro)system program” of your PICmicro).

• #opt option tells the compiler optimization level of your code:– 0: lowest – 9: highest (leads to the most-efficient compiled code)

Chapter 10a ME 534 17

Page 5: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

CCS C FunctionsCCS C u ct o s• CCS C built-in functions covered in this courseCCS C built in functions covered in this course

can be divided into the following categories:– Serial port (RS-232 / UART)p ( )– Digital (discrete) I/O ports – A/D converter– Pulse width modulator– Counters/timers– Interrupts

• Timer interrupts• External interrupt• External interrupt

– Miscellaneous functions

Chapter 10a ME 534 18

Serial Port FunctionsSe a o t u ct o s• In CCS C, there are 14 functions related to serial

t i tiport communication. • Some of them are carried over from standard C:

– printf(string) outputs a string of characters over serial port.

– getc() awaits for a character coming from the serial port.

d th ifi d h t th– putc(char) sends the specified character over the serial port.

di ti tti RS 232• #use rs232(options) directive setting RS-232 parameters must proceed these functions.

Chapter 10a ME 534 19

Example 1 – Serial Porta p e Se a o tAs an illustration of these functions, let us write a simple C programwhich turns the serial port monitor (“siow”) into a typewriter:

#include <18F4520.h> /* PICMicro Model: 18F4520 */#fuses HS,NOWDT,NOPROTECT,NOLVP /* Device configuration */#use delay(clock=20000000) /* CLK frequency: 20MHz */

p ( ) yp

#use rs232(baud=19200,xmit=PIN_C6,rcv=PIN_C7) /* RS-232 parameters */#org 0x3F00,0x3FFF {} /* Reserve memory in ROM */#opt 9 /* Compiler opt. level (max) */void main(){char c;long nc = 0;printf("*** PIC Typewriter ***\n\r");do{ c = getc(); /* Get a character from PC */putc(c); /* Send it back to PC */nc++; /* Count chars */if (c == 13) printf("\n"); /* Line feed */

} while (c!=0x11); /* Echo until ctrl-Q */printf("\n\rNo. of characters: %ld\n\r",nc);while(TRUE); /* Infinite loop */

Chapter 10a ME 534 20

}

Digital I/O Functionsg ta /O u ct o s

Digital I/O forms the basis of a microcontroller’s• Digital I/O forms the basis of a microcontroller s operation:

U d fi i f i t ll– Users can define any pin of a microcontroller as digital output and control its logic state (LS) at will:

• If LS is set to 1 → 5V is applied to that pin• If LS is set to 1 → 5V is applied to that pin.• If LS is set to 0 → Output pin is pulled to ground.

– A pin can be defined as input and its current logicA pin can be defined as input and its current logic states can be read arbitrarily:

• If LS is read as 1 → If 5V is being applied to the pin.• If LS is read as 0 → If the output pin is grounded.

Chapter 10a ME 534 21

Page 6: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

Digital Output Functionsg ta Output u ct o s

• CCS C provides a number of output functions:– output_high(PIN_X#) applies 5V to PIN_X#:

• # is a (bit) number between 0 and (usually) 7.• X is the port name (A, B, ..., G).t t l (PIN X#) li 0V t th t t i– output_low(PIN_X#) applies 0V to the output pin.

– output_bit(PIN_X#,state) applies either 5V or 0V to the pin depending on the state specified0V to the pin depending on the state specified.

– output_X(value)applies a set of voltages to all pins of port X depending on the given logic statespins of port X depending on the given logic states.

Chapter 10a ME 534 22

Digital Input Functionsg ta put u ct o s

H di it l i t f ti f CCS C• Here are some digital input functions of CCS C:– input(PIN_X#) returns the logic state of PIN_X#:

5V 1 (Hi h LS)• 5V → 1 (High LS)• 0V → 0 (Low LS)

– input X() returns the entire logic states of port X– input_X() returns the entire logic states of port X.

• Type of digital I/O can be specified through the following preprocessor commands:following preprocessor commands:– #use standard_io(X) (in effect, if omitted)# fi d i (X t t PIN X# PIN X# )– #use fixed_io(X_outputs = PIN_X#, PIN_X#, ...)

– #use fast_io(X) (we shall use this one!)

Chapter 10a ME 534 23

Digital I/O Functions (Cont’d)g ta /O u ct o s (Co t d)• When #use fast io(X) is used, the #use ast_ o( ) ,

compiler performs digital I/O without(re)programming the direction register(re)programming the direction register(TRISX).

• User must ensure TRISX is set correctly via– set tris X(state):set_tris_X(state):

• Bits of byte “state” correspond to directions of the pins of port X.p p

– If bit is 1, that pin is defined as (1)nput.– Otherwise, it is an (0)utput pin.

Chapter 10a ME 534 24

Delay Functionse ay u ct o s

• CCS C includes three functions for delaying the execution of a program at various points:– delay_us(value) creates a delay of (value×1μs)– delay_ms(value) creates a delay of (value×1ms)– delay_cycles(value) creates a delay of (value×5μs) where each cycle is 5 μs in our case.

• To utilize these functions, the clock speed must be specified:– #use delay(clock = ...)

Chapter 10a ME 534 25

Page 7: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

Example 2a – Digital I/Op gWrite a C program for aPIC18F4520 interfacing with

VddVdd = 5VRD2 RD3

PIC18F4520 interfacing withpush buttons that toggle thethe LEDs as the buttons

470

RD0

10 k

RD1

10 k

470

get to be depressed.

S l ti

PB-1LED-1

PB-2LED-2

Solution:In this exercise, the PICmicro turns into a simple toggle flip/flop driving a LED.Buttons on the EVB are connected to PIN D0 and PIN D1 while LEDs are_ _connected to PIN_D2 and PIN_D3 respectively. Assuming that no otherelements are connected to PORTD, port-pin directions are defined by setting/ tti th di bit TRISX i t/resetting the corresponding bits on TRISX resigter:• set_tris_d(0xF3) (remaining pins are defined as inputs!)

- Note that 0xF3 (hex) = 0b11110011 (bin) = 243 (dec)

Chapter 10a ME 534 26

( ) ( ) ( )

Example 2a – Digital I/O#include <18F4520.h>#fuses HS,NOWDT,NOPROTECT,NOLVP#use delay(clock=20000000)#use rs232(baud=19200,xmit=PIN_C6,rcv=PIN_C7)#use fast_io(D) /* tris_d must be set properly! */#org 0x3F00,0x3FFF {}#opt 9void main() {

int1 P = 0, Q = 0;set_tris_d(0xF3); /* PIN_D2 and PIN_D3 are defined as output */printf("Program starts...\n\r");while(TRUE) { /* infinite loop */

if (!input(PIN_D0)) { /* when PB-1 is depressed... */P = !P; /* ... toggle LED state */delay_ms(200); /* ... wait for 0.2s to de-bounce */output_bit(PIN_D2,P); /* ... output LED state */

}if (!input(PIN_D1)) { /* when PB-2 is depressed... */

Q = !Q; /* ... toggle LED state */delay ms(200); /* ... wait for 0.2s to de-bounce */delay_ms(200); / ... wait for 0.2s to de bounce /output_bit(PIN_D3,Q); /* ... output LED state */

}}

}

Chapter 10a ME 534 27

Accessing RAM Directlyccess g ect y• CCS C allows direct access to the RAM including the CCS C a o s d ect access to t e c ud g t e

(file) registers like PORTX:– #byte tag = address associates the byte at the specified

address with the given tag.– #bit tag = address.n associates the nth bit of byte residing

at the specified address with the given tag.at the specified address with the given tag.

• While accessing PORTX registers, one must set the directions of each pin correctly via set_tris_X(state)_ _function.

• Some useful addresses (refer to the datasheet) are – PORTA = 0xF80, PORTB = 0xF81– PORTC = 0xF82, PORTD = 0xF83

Chapter 10a ME 534 28

Example 2b – Digital I/O/* Directives are similar to those of Example 2a */#byte PORTD = 0xF83 /* control register for Port D */#bit PB1 = PORTD.0 /* RD0 is connected to PB-1 */# / /#bit PB2 = PORTD.1 /* RD1 is connected to PB-2 */#bit LED1 = PORTD.2 /* RD2 drives LED-1 */#bit LED2 = PORTD.3 /* RD3 drives LED-2 */void main() {void main() {

int1 P = 0, Q = 0;set_tris_d(0xF3); /* PIN_D2 and PIN_D3 are defined as output */printf("Program starts...\n\r");

/ /while(TRUE) { /* infinite loop */ if (!PB1) { /* when PB-1 is depressed... */

P = !P; /* ... toggle LED state */delay_ms(200); /* ... wait for 0.2s to de-bounce */LED1 = P; /* ... output LED state */p

}if (!PB2) { /* when PB-2 is depressed... */

Q = !Q; /* ... toggle LED state */delay_ms(200); /* ... wait for 0.2s to de-bounce */LED2 = Q; /* output LED state */LED2 = Q; /* ... output LED state */

}}

}

Chapter 10a ME 534 29

Page 8: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

Notes on Digital I/Ootes o g ta /O

Di it l I/O i h d b th i h l• Digital I/O pins are shared by other peripheral units (CCP, ADC, UART, etc.).

Sh d i lti l d– Shared pins are multiplexed.– If a peripheral unit is activated, the PICmicro does not

allow users to employ the corresponding pins asallow users to employ the corresponding pins as digital I/O.

• Any digital I/O operation on those pins will have no effect!

• It is advisable to define the unused pins of a particular port as inputs.– High-impedance

Chapter 10a ME 534 30

A/D Conversion• PIC18F4520 employ a 10-bit ADC unit with 13 multiplexed channels

(Ports A, B, and E):Pi RA0 t RA7 l d fi d i t f thi it– Pins RA0 to RA7 are commonly defined as inputs of this unit.

• A/D conversion has the following steps:– Initialization of ADC unit– Selecting an ADC channel– Reading ADC result for that channel

CCS C offers the following functions for initialization:• CCS C offers the following functions for initialization:– setup_adc_ports(ALL_ANALOG)sets all the pins as analog voltage

inputs.• Take a look at “18F4520.h” file for other input configurations.

– setup_adc(option) sets the clock source for ADC. The options are:• ADC_OFF turns off ADC unit.• ADC_CLOCK_DIV_n sets the ADC clock period as TADC = n*TCLK where

n ∈ {2, 4, 8, 16, 32, 64}• ADC_CLOCK_INTERNAL sets the ADC clock source as its internal RC

Chapter 10a ME 534 31

oscillator.

A/D Conversion (Cont’d)/ Co e s o (Co t d)• The following functions are utilized to select aThe following functions are utilized to select a

ADC channel and to read the result:– set adc channel(n)selects the pin RAn as theset_adc_channel(n)selects the pin RAn as the

input channel.– read ADC() returns the 10-bit result.ead_ ()

• One must wait at least 10 to 20 μs before reading the resultreading the result.

• ADC unit can generate an interrupt when a conversion is doneconversion is done.– A useful feature for time-sensitive apps.

Chapter 10a ME 534 32

Example 3 – ADC p470 a

LS 5015-20

RB6

Vdd = 5V

bcd

RB6

RB7

RB1

RB220 k( t )

RA2

a

bf

efg K

RB2

RB3

RB5

RB4

(pot.)

c

d

e

g

470 RB4

Consider a 18F4520 connected to a seven segment display (SSD) along witha 20kΩ potentiometer as illustrated. Write a C program such that the PICshows the applied voltage at RA2 pin as a hexadecimal number (0 – F) on theshows the applied voltage at RA2 pin as a hexadecimal number (0 F) on theSSD. Furthermore, hex. numbers 0 and F must blink on the display while thePIC is to send the strings “low” and “high” respectively over the RS-232.

Chapter 10a ME 534 33

Page 9: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

Example 3 – SSD Functiona p e 3 SS u ct oLet us develop a function which will generate the desired bit patterns on port B so as to display hex. numbers on SSD. The table below illustrates the characters vs. the corresponding bit patterns for the SSD segments:

Pin Seg 0 1 2 3 4 5 6 7 8 9 A b c d E FRB7 b 1 1 1 1 1 0 0 1 1 1 1 0 0 1 0 0RB6 a 1 0 1 1 0 1 1 1 1 1 1 0 0 0 1 1RB5 f 1 0 0 0 1 1 1 1 1 1 1 1 0 0 1 1RB4 g 0 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1RB3 e 1 0 1 0 0 0 1 0 1 0 1 1 1 1 1 1RB2 d 1 0 1 1 0 1 1 0 1 1 0 1 1 1 1 0

RB1 c 1 1 0 1 1 1 1 1 1 1 1 1 0 1 0 0Data: 238 130 220 214 178 118 126 226 254 246 250 62 28 158 124 120

In this table, 1 denotes that the LED on that particular segment is on. A byte(“data”) for each character can be formed using the following representation:

RB1RB2RB3RB4RB5RB6RB7 0SSD Data:MSB LSB One can write bit patterns

to Port B when SSD Dataof a character is specified.

Chapter 10a ME 534 34

o a c a ac e s spec ed

Example 3 – C Codea p e 3 C Code#include <18F4520.h>#device ADC=10 /* device has 10-bit ADC */#fuses HS NOWDT NOPROTECT NOLVP#fuses HS,NOWDT,NOPROTECT,NOLVP#use delay(clock=20000000)#use rs232(baud=19200,xmit=PIN_C6,rcv=PIN_C7)#use fast_io(B)#org 0x3F00,0x3FFF {}#opt 9void ss disp(int num) { /* seven segment display routine */void ss_disp(int num) { /* seven segment display routine *///// Due to this definition, disp_data now resides in ROM!//byte const SSData[16] = {238,130,220,214,178,118,126,226,

254,246,250,62,28,158,124,120};if(num < 16){

output b(SSData[num]);output_b(SSData[num]); }

}

Chapter 10a ME 534 35

Example 3 – C Code (Cont’d)a p e 3 C Code (Co t d)void main() {long adval;set tris b(1); /* define I/O pins first */_ _ ( ); / / p /output_b(0); /* clear display */setup_adc_ports(AN0_TO_AN3); /* setup ADC */setup_adc(ADC_CLOCK_INTERNAL);t d h l(2)set_adc_channel(2);

printf("Program starts...\n\r"); while(TRUE){

delay us(200); /* make sure ADC is ready */y_ ( ); / y /adval = read_ADC(); /* read 10-bit result */ss_disp(adval>>6); /* display (adval/64) */if (adval<64 || adval>960) { /* too high or too low? */

if ( d l<64) i tf("L \ \ ")if (adval<64) printf("Low\n\r"); if (adval>960) printf("High\n\r");delay_ms(200); /* blink the number... */output b(0); /* ... on the display */p _ ( ) p ydelay_ms(200);

}}

}Chapter 10a ME 534 36

}

Pulse Width Modulationu se dt odu at o• 18F4520 offers normally two PWM

i i C /C /PWM

t

outputs via its Capture/Compare/PWM(CCP) modules.

• 4 PWM outputs in ECCP mode.

PWM Period

duty • The resolution of duty cycle depends on the PWM frequency.

• The maximum resolution is 10 bits. (fixed)

• Following CCS C functions are employed to generate PWM output:– Initialization:

• setup_CCP#(CCP_PWM) configures CCP# as PWModulator– # is the number of CCP module (1 or 2).

• setup_timer_2(mode,period,postscale) sets the PWM frequency.– Timer2 is used to set 8-bit PWM period.

– set_pwm#_duty(value) sets PWM duty cycle (on the fly).

Chapter 10a ME 534 37

Page 10: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

Calculating PWM FrequencyCa cu at g eque cy

PWM i d d t b l l t d f ti f• PWM period needs to be calculated as a function of internal clock period.

• setup timer 2(mode period postscale) whichsetup_timer_2(mode,period,postscale), which sets the PWM frequency, has three arguments:– mode:

• T2_DISABLED• T2_DIV_BY_1• T2_DIV_BY_4• T2_DIV_BY_16

– period is a parameter (0-255) indicating the PWM period.– postscale (1 16) is ineffective in PWM frequency calculationpostscale (1...16) is ineffective in PWM frequency calculation.

Chapter 10a ME 534 38

PWM Frequency (Cont’d)eque cy (Co t d)T2_DISABLED: fPWM = 0

T2_DIV_BY_1 Mode:

1020 6f ][)1(4

1020)1(4

6Hz

periodperiodff CLK

PWM +×⋅

=+×

=

T2_DIV_BY_4 Mode:

1020 6

T2_DIV_BY_16 Mode:

1020 6

)1(441020

+××⋅

=period

fPWM )1(1641020

+××⋅

=period

fPWM

For instance, a period of 255 in T2_DIV_BY_1 mode yields fPWM ≅ 20 kHz.

Chapter 10a ME 534 39

PWM Duty Cycleuty Cyc e

PWM d t l i t b th f ti• PWM duty cycle is set by the function set_pwm#_duty(value):

If the value is a byte (int) the duty cycle (%) is determined by– If the value is a byte (int), the duty cycle (%) is determined by d(%) = 100*value/(period+1).

– If the value is a 16-bit number (long int), the duty cycle (%) ( g ) y y ( )becomes

d(%) = 25*value/(period+1).D t f PWM f i d• Duty of PWM waveform is expressed as

Td = d(%)÷(100*fPWM) [s]If d(%) > 100 no change in the output is observed• If d(%) > 100, no change in the output is observed.

Chapter 10a ME 534 40

Example 4 – PWM p470 a

b

LS 5015-20

RB6

Vdd = 5V

abcde

RB7

RB1

RB220 k(pot.)

RA2

a

bf

gefg

RB3

RB5

RB4

(p )

c

d

e

g

K470

RC2CCP1

1k2N2222

Consider a PIC18F4520 connected to a SSD along with a 20kΩ pot. Write a

1k

g pC program such that the PICMicro shows the applied voltage at RA2 pin as ahex. number (0 – F) on the SSD. Furthermore, it is to adjust the brightness of thedisplay via PWM as the the voltage across RA2 varies

Chapter 10a ME 534 41

display via PWM as the the voltage across RA2 varies.

Page 11: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

Example 4 – PWMpvoid main() {long adval;set_tris_b(0x01); /* define I/O pins first */set tris c(0xBB);set_tris_c(0xBB); set_tris_d(0xF3); output_b(0); /* clear 7-segment display */setup_ccp1(CCP_PWM); /* configure CCP1 as PWM */setup_timer_2(T2_DIV_BY_1,255,1); /* PWM frequency: ~20kHz */setup adc ports(AN0 TO AN3); /* only AN2 is used here! */setup_adc_ports(AN0_TO_AN3); /* only AN2 is used here! */setup_adc(ADC_CLOCK_INTERNAL);set_adc_channel(2);printf("Program starts...\n\r");while(TRUE){

delay_us(200);adval = read ADC(); /* read 10-bit result */adval = read_ADC(); /* read 10-bit result */set_pwm1_duty(adval); /* d(%) = 100*adval/1024 */ss_disp(adval>>6); /* display (adval/64) */

}

Chapter 10a ME 534 42}

Counters / Timers• PIC18F4520 has four on-board counters:

Ti 0 8 bit/16 bit ti / t ith– Timer0: 8-bit/16-bit timer/counter with pre-scaler Ti 1 16 bit ti / t ith l– Timer1: 16-bit timer/counter with pre-scaler

– Timer2: 8-bit timer/counter with pre- & post-lscalers.

– Timer3: 16-bit timer/counter with pre-scaler• Since Timer2 is used to set the period of

PWM, only TimerX (X: 0, 1/3) will be taken y ( )into consideration for counting external events.

Chapter 10a ME 534 43

Counter0 / Timer0Cou te 0 / e 0• setup_timer_0(mode) sets up timer0 or “real-time clock/counter”

(RTCC):(RTCC):– mode should indicate the timer source, prescaler, and options:

• RTCC_INTERNAL: driven by internal clock @ 20MHz / 4. • RTCC EXT L TO H: driven by the positive edge of external clock at• RTCC_EXT_L_TO_H: driven by the positive edge of external clock at

RA4/T0CKI pin. • RTCC_EXT_H_TO_L: driven by the negative edge of external clock. • RTCC DIV n: postscaler divides the clock frequency by n ∈ {1 2 4 256}• RTCC_DIV_n: postscaler divides the clock frequency by n ∈ {1, 2, 4, ..., 256}.• RTCC_8_BIT: 8 bit timer is selected (16-bit, if omitted!).

– These selections are combined via the logical OR (|) operator.• set_timer0(value) sets the initial count value of timer0.• get_timer0() returns the count value of timer0.

– All timers count up– All timers count up.– When timer0 reaches 255 (8-bit mode), it will flip over to 0 and continue

counting.

Chapter 10a ME 534 44

RTCC/Timer0 ModelCC/ e 0 ode

Chapter 10a ME 534 45Timer Interrupt

Page 12: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

Counter1 / Timer1 Cou te / e• setup timer 1(mode) sets up (16-bit) timer1:p_ _ ( ) p ( )

– mode values may be• T1_DISABLED: timer1 is disabled.• T1_INTERNAL: internal clock (@ 20MHz / 4) drives timer1.• T1_EXTERNAL: external clock at RC0/T1CK1 pin drives timer1.• T1 EXTERNAL SYNC: external clock is to be synchronized with the _ _ y

internal one (called “synchronous” counting).• T1_DIV_BY_n: divides the source frequency by n ∈ {1, 2, 4, 8}.• Logical OR may be applied to constants from different groups• Logical OR may be applied to constants from different groups.

• set_timer1(value) sets the initial count value of timer1.

• get_timer1() returns the count value of timer1.

Chapter 10a ME 534 46

Timer 1 Modele ode

Internal PICmicro

a(20 MHz / 4)aPICmicro

Clock

FrequencyDivider

16-bitCounter

get_timer1()

D Q

a

bD-F/F

External Frequency

Source

set_timer1(value)

T1_DIV_BY_1T1_DIV_BY_2T1_DIV_BY_4

bRC0/T13CKI

CLK a: T1_INTERNAL orT1_EXTERNAL

b: T1_EXT_SYNCHT1_DIV_BY_8

a: T1_INTERNALb: T1_EXTERNAL or

T1_EXT_SYNCH

Chapter 10a ME 534 47Timer Interrupt

Example 5 - Countersa p e 5 Cou te sdd

+

RA41 2

RD2

+

RC0

CD40106BVdd (14) = 5VVss (7) = GND

Button

Consider the circuit shown. Write a C program for the PICmicro such thatConsider the circuit shown. Write a C program for the PICmicro such thatit will send the counterX (X = 0 or 1) values to the serial port monitor (PC)over the serial port whenever the pushbutton is depressed.

Chapter 10a ME 534 48Example 6

Example 5a – Timer0p#include <18F4520.h>#fuses HS,NOWDT,NOPROTECT,NOLVP#use delay(clock=20000000)y( )#use rs232(baud=19200,xmit=PIN_C6,rcv=PIN_C7)#use fast_io(D)#org 0x3F00,0x3FFF {}#opt 9p#bit SW = 0xF83.0 /* RD0 is the switch input */void main(){int count;set_tris_d(0xF3); /* Set I/O pins of Port D */

/* Set up 8-bit RTCC */setup_timer_0(RTCC_EXT_L_TO_H|RTCC_DIV_1|RTCC_8_BIT);set timer0(0); /* I.C. = 0 */_while(TRUE){count = get_timer0(); /* Read ctr0 */if(!SW) { /* When SW is depressed... */printf("Counter0 = %u\n\r",count); /* ... send it out! */pdelay_ms(200);

} /* Wait 200 ms to debounce */}

}

Chapter 10a ME 534 49

Page 13: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

Example 5b – Timer1p#include <18F4520.h>#fuses HS,NOWDT,NOPROTECT,NOLVP#use delay(clock=20000000)#use rs232(baud=19200,xmit=PIN_C6,rcv=PIN_C7)#use fast_io(D)#org 0x3F00,0x3FFF {}#opt 9#bit SW = 0xF83.0 /* RD0 is the switch input */void main(){long count;set_tris_d(0xF3); /* Set I/O pins of Port D */set_tris_c(0xBB); /* Set I/O pins of Port C */setup_timer_1(T1_EXTERNAL|T1_DIV_BY_1); /* Set up Timer1 */set_timer1(0); /* I.C. = 0 */_while(TRUE){count = get_timer1(); /* Read ctr1 */if(!SW) { /* When SW is depressed... */printf("Counter1 = %lu\n\r",count); /* ... send it out! */delay_ms(200); /* Wait 200 ms to debounce */

}}

}

Chapter 10a ME 534 50

Interruptsp• Microcontrollers deals with time-sensitive or randomly occurring

events through interrupts.– Periheral units usually generate such signals.– They tell the processor that a special event has taken place.

• Whenever an interrupt occurs, the processor invokes an interrupt i ti (ISR) h dli th di it tiservice routine (ISR) handling the corresponding situation.

– After the execution of an ISR, the microcontroller resumes its normal operation.

• The generic procedure for ISR is as follows:• The generic procedure for ISR is as follows:– Disable interrupts: This ensures that no other interrupt messes up with

the service. – Service routinesService routines– Clear its interrupt flag (a bit in an interrupt control register) when done:

This informs the processor that the interrupt is handled and the ISR is ready for a new interrupt.E bl i t t– Enable interrupts

– Return from ISR: Restores the original state of MCU and resumes the main course.

Chapter 10a ME 534 51

Interrupt Functionste upt u ct o s• In CCS C, ISRs (“interrupt-handler” functions) are marked up via a compiler

directive:– #INT_XXXX where XXXX stands for the type of interrupt. – The interrupt service procedures are embedded inside this function.

• Interrupts must be enabled at the beginning of main function: enable interrupts(INT XXXX) sets the interrupt enable flag at the given– enable_interrupts(INT_XXXX) sets the interrupt enable flag at the given level.

– enable_interrupts(GLOBAL) enables all interrupts. • Other relevant built-in functions are

– disable_interrupts(INT_XXXX) – disable_interrupts(GLOBAL)– clear_interrupt(INT_XXXX) clears the interrupt flag at the given level.

• Interrupts available in PIC 18F4520 are• Interrupts available in PIC 18F4520 are– External interrupt (INT_EXT)– Timer interrupts (INT_RTCC, INT_TIMER1)– Change on (Port B) pin interrupt (INT_RB) }of major

interestg ( ) p p ( _ )– A/D conversion complete interrupt (INT_AD)– Serial port interrupts (INT_RDA, INT_TBE)– And more...

}Chapter 10a ME 534 52

Timer Interruptse te upts• Timer0 (RTCC) and Timer1 are frequently used to generate

(precise) periodic interrupts for timing sensitive applications like(precise) periodic interrupts for timing-sensitive applications like digital control systems!– When RTCC or Timer1 counter overflows, it generates an interrupt.

• Once the timer is set up in the main function, its interrupt is enabled.• Timers are set up such that the internal clock drives their counters.

The functions discussed in previous section are employed for thisThe functions discussed in previous section are employed for this purpose:– Timer0 (or RTCC):

t ti 0(RTCC INTERNAL|RTCC DIV )• setup_timer_0(RTCC_INTERNAL|RTCC_DIV_n)– Prescaler: n ∈ {1, 2, 4, 8, ..., 256}

– Timer1:• setup_timer_1(T1_INTERNAL|T1_DIV_BY_n)

– Prescaler: n ∈ {1, 2, 4, 8}

Chapter 10a ME 534 53

Page 14: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

Timer Interrupts (Cont’d)e te upts (Co t d)• In control applications, the ISR is used to pp ,

implement the control algorithm.– The frequency of interrupt is essentially the q y p y

sampling frequency!• The timerX interrupt frequency can beThe timerX interrupt frequency can be

calculated using the following expressions:

105 6][

2105

)1(8

6Hz

nf XtimerX +×

×=

where the timer index X is 0 or 1 while n ∈ {1, 2, 4, ...} is the prescaler.

Chapter 10a ME 534 54

{ , , , } s t e p esca e

Timer Interrupts (Cont’d)e te upts (Co t d)One can precisely set the desired interrupt frequency (fd) [Hz] by selecting the initial value (m ) of timerX:[Hz] by selecting the initial value (m0) of timerX:

⎬⎫

⎨⎧ ×

= +Xm6

)1(8 105int2⎭⎬

⎩⎨ ×

−=dfn

m0 int2

H t th b i i f ISR th t l i tHence, at the beginning of ISR, the counter value is set to m0 using set_timerX(m0). As an illustration, let us calculate the initial counter value for timer0 (withus calculate the initial counter value for timer0 (with RTCC_DIV_128 option: n = 128) if fd = 750 Hz:

105 6 ⎫⎧ 20452256750128105int2

6)01(8

0 =−=⎭⎬⎫

⎩⎨⎧

××

−= +m

Chapter 10a ME 534 55

Example 6a – Timer0 Interrupta p e 6a e 0 te upt

As an example we shall revisit Example 5• As an example, we shall revisit Example 5. • Instead of connecting an external clock to the

i 0 h ll ili PIC i ’ i l l ktimer0, we shall utilize PICmicro’s internal clock @ 5 MHz to generate timer0 interrupt.

• ISR is to count up each-time it is invoked.• As in the previous case, we would like to send p ,

count values to the serial port monitor (PC) over the serial port whenever the pushbutton is p ppressed.

Chapter 10a ME 534 56

Example 6a - C programa p e 6a C p og a// // Preprocessor directives are same as Example 5a////long count = 0; /* Global variable */#INT_RTCC /* ISR for timer0-overflow interrupt */id i (){ t++ }void isr(){count++;}

void main(){set tris d(0xF3); /* Set I/O pins of Port D */_ _ ( ) psetup_timer_0(RTCC_INTERNAL|RTCC_DIV_1); /* Setup RTCC */set_timer0(0); /* I.C. = 0 */enable_interrupts(INT_RTCC); /* Enable interrupts */

bl i t t (GLOBAL)enable_interrupts(GLOBAL);while(TRUE){

if(!SW){ /* When SW is depressed... */printf("Counter = %lu\n\r",count); /* ...send it out! */p ( , )delay_ms(200); /* Wait 200 ms to debounce */

}}

}Chapter 10a ME 534 57

}

Page 15: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

External Interruptte a te upt• PIC18F4520 allows the use of three external

interrupts (INT_EXT, INT_EXT1, INT_EXT2):– External (interrupt) sources must be connected to ( p )

RB0/INT0, RB1/INT1, RB2/INT2 pins.• Before enabling the external interrupts, the type g p , yp

of clock edge triggering interrupt should be specified:p– ext_int_edge(L_TO_H) denotes the positive edge

of the clock triggers the interrupt.– ext_int_edge(H_TO_L) denotes the negative

edge of the clock triggers the interrupt.

Chapter 10a ME 534 58

Example 6b – External Interrupta p e 6b te a te uptdd

+

RB0/INT1 2

RD0

+CD40106BVdd (14) = 5VVss (7) = GND

Button

In this example, the external clock is to be coupled to RB0/INT0 pin. We willit C f th PIC i h th t it ill t th l fwrite a C program for the PICmicro such that it will count the pulses of

external clock and will send out counter values to the serial port monitor (PC)whenever the pushbutton is depressed.

Chapter 10a ME 534 59

Example 6b – External Interrupta p e 6b te a te upt// // Preprocessor directives are same as those of Example 5a////long count = 0; /* Global variable */#INT_EXT /* ISR for external “B0” interrupt */void isr(){count++;}void isr(){count++;}void main() {set_tris_d(0xF3); /* Define digital I/O pins */set tris b(0xFF);set_tris_b(0xFF);ext_int_edge(L_TO_H); /* Interrupt on (+) edge */enable_interrupts(INT_EXT); /* Enable interrupts */enable interrupts(GLOBAL);enable_interrupts(GLOBAL);while(TRUE){if(!SW){ /* When SW is depressed... */printf("Counter = %lu\n\r",count); /* ...send it out! */delay ms(200); /* Wait 200 ms to debounce */delay_ms(200); /* Wait 200 ms to debounce */

}}

}

Chapter 10a ME 534 60

Pin-change Interruptc a ge te upt

• In 18F4520 pin change interrupt (INT RB) is• In 18F4520, pin change interrupt (INT_RB) is used to detect the logic state changes at pin RB7-RB4RB7-RB4.

• If there is any change in these four inputs, PICmicro generates an interruptPICmicro generates an interrupt. – This interrupt is intended for “keyboard wake-up”

Mi hi d t d th tili ti f thi i t t• Microchip does not recommend the utilization of this interrupt for any other applications.

– Any read or write to Port B (say RB3-RB0) clears theAny read or write to Port B (say RB3 RB0) clears the “mismatch” condition.

Chapter 10a ME 534 61

Page 16: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

Example 6c – Pin Change Interruptp g pRD2

1RB7

1 2

CD40106BVdd (14) = 5VVss (7) = GND

In this exercise, we would like to develop a C program for PICmicro so that themicrocontroller measures the input frequency (Hz) of the external clock at RB7microcontroller measures the input frequency (Hz) of the external clock at RB7and transmits that information through the serial port. Note that for testingpurposes, a LED coupled to RB1 pin gets toggled whenever a pin-changeinterrupt is generated.

Chapter 10a ME 534 62

p g

Example 6c – RB Change Interruptp g p#include <18F4520.h>#fuses HS,NOWDT,NOPROTECT,NOLVP#use delay(clock=20000000)#use delay(clock=20000000)#use rs232(baud=19200,xmit=PIN_C6,rcv=PIN_C7)#org 0x3F00,0x3FFF {}#use fast_io(B)#use fast_io(D)#opt 9#bit LED = 0xF83.2 /* RD2 drives a LED */int count = 0,b = 0; /* Global variables */short Q = 0;#INT_RB /* RB Change ISR */void isr() {count++; /* Count changes */Q = !Q; LED = Q; /* Toggle LED */Q = !Q; LED = Q; /* Toggle LED */b = input_b(); /* must R/W to Port B before clearing RBIF */clear_interrupt(INT_RB); /* Clear RBIF */

}

Chapter 10a ME 534 63

Example 6c (Cont’d)a p e 6c (Co t d)

id i (){void main(){int freq = 0, freq_old;set tris d(0xF3); /* Define I/O pins of Port D */_ _ ( ); / / p /set_tris_b(0xFF); /* Port B is defined as output */port_b_pullups(TRUE); /* Internal pull-ups activated */

bl i t t (INT RB) /* E bl i t t */enable_interrupts(INT_RB); /* Enable interrupts */enable_interrupts(GLOBAL);while(TRUE){( ){

freq_old = freq; /* Calculate frequency */freq = count; count = 0;if(freq!=freq_old) printf("Frequency = %d [Hz] \r",freq);d l (1000) /* S li i d i 1 */delay_ms(1000); /* Sampling period is 1s */

}}

Chapter 10a ME 534 64

EEPROM CommandsO Co a ds

• PIC 18F4520 incorporate 256-byte non-volatile• PIC 18F4520 incorporate 256-byte non-volatile memory. The user can access EEPROM through the• The user can access EEPROM through the following built-in functions of CCS C:

d ( dd ) d b t f th– read_eeprom(address)reads a byte from the EEPROM at the specified address (8-bit).

• The address ranges between 0 and 255 for PIC 18F4520• The address ranges between 0 and 255 for PIC 18F4520.– write_eeprom(address,value)writes a byte

(value) to EEPROM at the specified address.(value) to EEPROM at the specified address.• This function takes several milliseconds to execute.

Chapter 10a ME 534 65

Page 17: Outline – Chapter 10a PICC c o a uat o oa dMicro ...me.metu.edu.tr/courses/me534/protected/ME 534 - 10 CCS C Part I... · Outline – Chapter 10a ... – Software • CCS C Compiler

Example 7p#include <18F4520.h>#fuses HS,NOWDT,NOPROTECT,NOLVP#use delay(clock=20000000)#use rs232(baud=19200,xmit=PIN_C6,rcv=PIN_C7)#org 0x3F00,0x3FFF{}#opt 9void main() {int i = 0, m;printf("R(ead or W(rite? \n\r"); m = getc();if ((m==87)||(m==119)) {printf("Content? \n\r"); m = getc();do{write_EEPROM(i,m);printf("Writing %X to addr %X\n\r",m,i);

} while(++i>0);}do{m = read_EEPROM(i);_printf("Addr = %X Content = %X\n\r",i,m);

} while(++i>0);while(TRUE);

}

Chapter 10a ME 534 66

Watch Dog Timer (WDT)atc og e ( )• The WDT function is to monitor the computer system whether workThe WDT function is to monitor the computer system whether work

normally. – Otherwise, it will have some measures to fix up the system.

Th i f th WDT i th t ft ti t l t• The main reason of the WDT is that software sometimes got lost:– Enter infinite loops– Unexpected (conditional) branching puts the routine to go crazy.p ( ) g p g y

• The WDT unique intention is to reset the machine if certain programmable timer expires. Therefore “properly operating"software should "reset" WDT before it does!software should reset WDT before it does!– For instance, if you program the WDT to 1 second, you should reset the

WDT timer before that happens.• If a routine gets lost, the WDT will reset your machine in one

second, so not much is wasted.

Chapter 10a ME 534 67