Programming PIC MCU PDF
Programming PIC MCU PDF
Programming PIC MCU PDF
Module: EE2A2 Embedded Microprocessor Systems Lecturer: James Grimbleby y URL: http://www.personal.rdg.ac.uk/~stsgrimb/ email: j j.b.grimbleby g y reading.ac.uk g Number of Lectures: 5 Recommended text book: R Barnett R. Barnett, L OCull O Cull and S S. Fox Embedded C Programming and the Microchip PIC Thomson (2004) ISBN 1401837484
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 1
Recommended Text Book: R. Barnett, L OCull O Cull and S. Fox Embedded C Programming and the Microchip p PIC Thomson (2004) ISBN 1401837484 Price (Amazon) 47
James Grimbleby
Slide 2
Assessment
This unit nit will ill be assessed b by a m multiple-choice ltiple choice test The multiple-choice multiple choice test will last for 30 minutes minutes, during which 20 questions must be answered You will be permitted to bring your notebooks and the course notes into the test The test will be held at the end of the Autumn term The marks from this test will contribute to the overall mark for the module EE2A2
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 6
Answer:
James Grimbleby
Slide 7
CPU
Data memory
Slide 9
I/O ports
Brn out reset Watchdog Start up timer Low volt prog Debugger ALU
MUX Peripherals
W register
Slide 10
Clock Generator
PICs use a fully static design so that any clock frequency up to the specified maximum can be used There are 4 possible clock configurations: - external clock (eg crystal oscillator module) - self-oscillating with external crystal or ceramic resonator - external or self-oscillating with phase-locked loop - self-oscillating with external RC In practice the choice will normally be a compromise between cost and clock speed or clock stability
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 12
Reset
A reset p puts the PIC in a well-defined initial state so that the processor starts executing code from the first instruction Resets can result from: - external reset by MCLR pulled low - reset on power-up - reset by watchdog timer overflow - reset t on power supply l b brown-out t Reset can be used sed as a last resort for reco recovering ering from some catastrophic software event but all current data will be lost
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 13
James Grimbleby
Slide 14
P Program memory
0x7FFF
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 16
Data memory contains general purpose registers (GPRs) and special function registers (SFRs) The PIC18F452 has 1536 (0x600) locations of GPR data memory
0xF80 0xFFF
Slide 17
The memory block 0xF80 to 0xFFF (128 locations) references special function registers (SFRs) Some of the SFRs are shown h h here
James Grimbleby
Bit-oriented file register operations: BCF BTFSC Clear bit in f Test bit in f; skip if clear
James Grimbleby
Slide 21
Status Register
The 8-bit status register g is set during g arithmetic operations p N OV Z DC C N OV Z DC C
Negative bit - result of arithmetic operation was negative Overflow bit overflow occurred for signed arithmetic Zero bit - result of arithmetic operation was zero Digit Carry bit carry out from 4th low order bit of result Carry bit carry out from most-significant bit of result
The bits of the status register can then be used in conditional branches, , for example: p BNZ Branch if Not Zero BOV Branch of OVerflow
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 23
What is C ?
In 1970 a team at Bell Labs led by y Brian Kernighan g were developing the UNIX computer operating system They required a high-level computer language for writing computer operating systems Starting from an existing language called BCPL they developed C C was used dt to write it th the next t version i of f UNIX system t software UNIX eventually became the world's first portable operating system
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 25
What is C ?
C has now become a widely y used professional p language g g for various reasons: It has h high hi h l level l constructs t t It can handle low level activities It produces efficient programs It can be compiled on a wide variety of computers The standard for C programs was originally the features set by Brian Kernighan Later an international standard was developed: ANSI C (American National Standards Institute)
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 26
What is C++ C ?
More recently another group at AT&T led by Bjarne Stroustrup developed C to reflect modern programming techniques The new language was called C++ C++ has stronger type checking and supports object-oriented programming C++ may be considered in several ways.: An extension of C A "data data abstraction abstraction" improvement on C A base for "object oriented" programming
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 27
Programs are edited P dit d and d compiled il d t to PIC machine hi i instructions t ti on a PC PIC machine instructions are uploaded from PC to PIC system gg via the ICD2 debugger Code is executed on the PIC system and can be debugged (break points, points inspect variables variables, single step etc etc.) ) using PC
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 30
James Grimbleby
Slide 31
It is not appropriate to use the signed qualifier with char or short int, and floats are signed by default
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 34
Constants
Constants can be specified in either decimal, octal, hexadecimal or binary, or as a special character: 123 0123 0x123 0b010010 'x' \010 '\010' '\0xA5 Decimal Octal Hex Binary Character Octal character Hex character '\n' \n '\r' '\t' \t '\b' '\f' \f '\a' \v '\v' '\?' '\'' \ '\"' '\\' Line Feed Return Feed TAB Backspace Form Feed Bell Vertical Space Question Mark Single S g e Quote Double Quote A Single g Backslash
Slide 35
James Grimbleby
The standard boolean operators (||, (|| &&, && ! etc) ) can be used with these variables
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 36
Yes
Ams ++
Slide 38
James Grimbleby
Slide 39
MOVF Bls, W ADDWF Als MOVF B1, W ADDWFC A1 MOVF B2, W ADDWFC A2 MOVF Bms Bms, W ADDWFC Ams
James Grimbleby
Slide 40
Reference Parameters
CCS C provides C++ C like reference parameters to functions: Traditional C:
void swap(int *x, x, int *y) y) { int temp = *x; * = *y; *x * *y = temp; } int j = 5, k = 8; swap(&j, (&j &k); &k)
CCS C ( (C++): )
void swap(int &x, int &y) { int temp = x; x = y; y = temp; } int j = 5, k = 8; swap(j, (j k); k)
James Grimbleby
Slide 41
Discrete I/O:
output_low() output_high() output float() output_float() output_bit() input() output_X() t t () output_toggle() input_state() input_X() port_b_pullups() _ _ () set_tris_X()
Slide 42
I2C I/O
i2c_start() i2c_stop() i2C_read i2c_write() i2c poll() i2c_poll()
Processor control:
sleep() reset_cpu() restart_cause() disable_interrupts() enable interrupts() enable_interrupts() ext_int_edge() read_bank() write bank() write_bank() label_address() goto_address() getenv() t () clear_interrupts setup_oscillator()
James Grimbleby
Slide 43
Standard C Math:
abs() acos() asin() atan() ceil() cos() () exp() floor() labs() sinh() g() log() log10() pow() sin() cosh() tanh() fabs() fmod() atan2() frexp() ldexp() df() modf() sqrt() tan() div() ldiv()
James Grimbleby
Slide 44
strcmp() stricmp() strncmp() strcat() strstr() strchr() strrchr() isgraph() i iscntrl() t l() strtok() strspn() strcspn() strpbrk() strlwr() () sprintf() isprint() strtod()
Slide 45
Timers:
setup_timer_X() set_timer_X() i () get_timer_X() p setup_counters() setup_wdt() restart_wdt()
Standard C memory:
memset() memcpy() () offsetof() offsetofbit() malloc() calloc() free() realloc() memmove() memcmp() memchr()
Analog Compare:
setup_comparator()
James Grimbleby
Slide 46
Internal EEPROM:
read_eeprom() write eeprom() write_eeprom() read_program_eeprom() write_program_eeprom() read calibration() read_calibration() write_program_memory() read_program_memory() write_external_memory() i l () erase_program_memory() setup_external_memory()
Delays:
delay_us() delay_ms() delay cycles() delay_cycles()
Standard C Special:
rand() srand()
James Grimbleby
Slide 47
The first directive instructs the compiler to include the system header file 18F452.H This is a device-specific file that contains information about the location of SFRs and the values to be written to them
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 48
PIN_A0 31744 PIN PIN_A1 A1 31745 . . . . PIN_B0 31752 PIN PIN_B1 B1 31753 . . . . T1_DISABLED T1 T1_INTERNAL INTERNAL T1_EXTERNAL T1_EXTERNAL_SYNC . . . . CCP_OFF CCP_CAPTURE_FE CCP_CAPTURE_RE CCP_CAPTURE_DIV_4 . . . .
Fuses
CCS C p provides a fuse directive:
#fuses HS,NOWDT,NOBROWNOUT,NOPROTECT,PUT
which specifies the states of the configuration fuses that should be programmed onto the PIC In this example: HS NOWDT NOBROWNOUT NOPROTECT PUT
James Grimbleby
Clock is a high-speed crystal or resonator W t hd ti Watchdog timer i is di disabled bl d Brown-out detector is disabled Code protect off Power-on timer is enabled
Slide 50
Delays
CCS C p provides functions for g generating g delays: y
delay_us() delay ms() delay_ms()
These delay y functions actually y delay y by y a number of machine cycles The compiler needs to know the clock frequency in order to calculate the required number of machine cycles
#use delay(clock=20000000)
This use-delay directive specifies that the clock frequency of the PIC is 20 MHz
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 51
This directive instructs the compiler to include the user library fil lcd.c file l d in i th the fil file currently tl b being i compiled il d This is Thi i not t particularly ti l l efficient ffi i t (the (th library lib file fil i is compiled il d every time) - however typical PIC programs compile in a few seconds
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 52
Data Ports
Simplified p diagram g representing p g a single g data I/O p pin of one of the ports A-E: Data bus Data write D Q Tri-state s a e write e Q D Q I/O pin
Data read
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 54
Data Ports
Data I/O p port functions: Data write - this latches the data written to the pin which should be configured as an output Tri-state write - this latches the data direction for the pin (0 = output, 1 = input) Data read - this reads the current value of the pin which should h ld b be configured fi d as an i input t Each data port (A-E) (A E) consists of a n number mber of pins pins, each of which can individually be configured as an input or output
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 55
Hardware Access in C
Memory-mapped hardware is traditionally accessed in C using pointers If the hardware is byte (8-bit) organised then char or int (PIC) pointers are used Example: a pe a an 8 8-bit b t input put po port t memory-mapped e o y apped to location ocat o 0xF81:
#d fi #define portb tb (int (i t *) 0xF81 0 F81
Thus portb is an int pointer whose value is the address of the bus device
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 56
Hardware Access in C
Th port The t is i accessed d by b the th use of f the th indirection i di ti operator t * *:
int p; p = *portb;
In this example the value of the data on the port mapped to memory location 0xF81 (port B) is assigned to variable p Before the p port can be read it is necessary y to set the data direction register:
#define trisb (int *) 0xF93 *trisb = 0xFF;
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 57
Although Alth h thi this code d i is l longer th than th the previous i example l it i is better structured
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 59
The differences between these I/O methods are to do with the way that the data direction registers are controlled
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 61
Standard I/O
#use standard standard_io(port) io(port) affects how the compiler will generate code for input and output instructions that follow This directive takes effect until another #use xxx_io directive is encountered The e sta standard da d method et od o of I/O /O will cause t the e co compiler p e to generate code to set the direction register for each I/O operation p Standard_io is the default I/O method for all ports. Examples: #use standard_io(A)
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 62
Fast I/O
#use fast fast_io(port) io(port) affects how the compiler will generate code for input and output instructions that follow This directive takes effect until another #use xxxx_io directive is encountered The e fast ast method et od of o doing do g I/O /O will cause t the e co compiler p e to perform I/O without programming of the direction register The user must ensure the direction register is set correctly via set_tris_X() . Example: #use fast_io(A)
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 63
Fixed I/O
#use fixed fixed_io(port) io(port) affects how the compiler will generate code for input and output instructions that follow This directive takes effect until another #use xxx_io directive is encountered The fixed method of I/O will cause the compiler to generate code to set the direction register for each I/O operation The pins are programmed according to the information in this directive (not the operations actually performed) Examples: #use fixed_io(a_outputs=PIN_A2,PIN_A3)
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 64
Standard I/O
#use standard standard_io(b) io(b) void main() { int q; for (q = 0b00000001;; q ^ ^= 0b00000101) { output_b(q); delay_ms(100); y } } output_b(q); CLRF 0xf93 MOVFF 0x6, 0xf8a
James Grimbleby
Fast I/O
#use fast_io(b) fast io(b) void main() { int q; set tris b(0b11111010); set_tris_b(0b11111010); for (q = 0b00000001;; q ^= 0b00000101) { output_b(q); p q delay_ms(100); } }
Write port
Slide 67
Fixed I/O
#use fixed fixed_io(b_outputs=pin_b2,pin_b0) io(b outputs pin b2 pin b0) void main() { int q; for (q = 0b00000001;; q ^ ^= 0b00000101) { output_b(q); delay_ms(100); y } } output_b(q); MOVLW 0xfa MOVWF 0xf93 MOVFF 0x6, 0xf8a
James Grimbleby
Standard I/O
#use standard_io(b) void main() { boolean q; for (q = false;; q = !q) { if (q) output_high(pin_b2); else output_low(pin_b2); delay_ms(100); } } output_high(pin_b2); output high(pin b2); BCF 0xf93, 0x2 BSF 0xf8a, , 0x2
James Grimbleby
Fast I/O
#use fast_io(b) void main() { boolean q; set_tris_b(0b11111010); for (q = false;; q = !q) { if (q) output_high(pin_b2); else output_low(pin_b2); delay ms(100); delay_ms(100); } } output_high(pin_b2); BSF 0xf8a, 0x2
James Grimbleby
Write pin
Slide 71
Fixed I/O
#use fixed_io(b_outputs=pin_b2,pin_b0) void main() { boolean q; for (q = false;; q = !q) { if (q) output_high(pin_b2); else output low(pin b2); output_low(pin_b2); delay_ms(100); } } p g (p ); output_high(pin_b2); MOVLW 0xfa MOVWF 0xf93 BSF 0xf8a, 0xf8a 0x2
James Grimbleby
Toggle pin
Slide 73
where a value true will activate, and a value false de-activate, the internal pull pull-ups ups
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 74
Lecture 4 Timer/Counter/PWM
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 75
Timer/Counters
The PIC 18F452 has 4 timer/counters: Timer0, Timer1, Timer2, Timer3 Timer 0: Ti 0 Timer 1: Timer 2: Timer 3: 8 or 16 16-bit bit ( (selectable) l t bl ) 16-bit 8 bit 8-bit 16-bit
The timer/counters can be used to: generate timed interrupts count incoming logic transitions capture timer/counter on an input event generate variable PWM outputs
School of Systems Engineering - Electronic Engineering Slide 76
James Grimbleby
Timer/Counters
Fosc/4 I/O pin T0SE T0CS 0 1 Pre-scaler 0 1 PSA D-bus T0SE determines whether 01 or 10 transitions are active T0CS determines d i the h source (I/O pin i or internal i l clock) l k) PSA determine whether the input is pre-scaled pre scaled or not
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 77
Timer/ counter
Enable: off (0) or on(1) Mode: 16-bit (0) or 8-bit (1) Time source: internal clock (0) or external (1) Edge select: 01 (0) or 10 (1) Prescaler: on (0) or off (1) Prescaler ratio: 1/2 (000) .. 1/256 (111)
For example for 8-bit mode, external source, 01 edge, no pre-scaler: pre scaler: T0CON = 0b11100000 = 0xE0
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 78
Counters
Program g to count p pulses on external input p to timer/counter 0:
#define t0con (int *) 0xFD5 #define tmr0l (int *) 0xFD6 void main() { *t0con = 0xE0; *tmr0l = 0; lcd_init(); for (;;) { printf(lcd_putc, "\f%d", *tmr0l); delay_ms(200); } }
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 79
Counters
Fortunately y it is not necessary y to manipulate p the registers g directly because special functions are provided in CCS C:
setup_timer_0(mode) setup timer 0(mode) setup_timer_1(mode) . . . . . . . . . .
where mode depends on the timer, but for timer 0 can be:
RTCC INTERNAL RTCC_EXT_L_TO_H RTCC_INTERNAL, RTCC EXT L TO H or RTCC_EXT_H_TO_L RTCC EXT H TO L RTCC_DIV_2, RTCC_DIV_4, RTCC_DIV_8, RTCC_DIV_16, RTCC DIV 32 RTCC_DIV_64, RTCC_DIV_32, RTCC DIV 64 RTCC_DIV_128 RTCC DIV 128 or RTCC_DIV_256 RTCC DIV 256 RTCC_OFF, RTCC_8_BIT
One constant may be used from each group ORed together with the | operator
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 80
Counters
To set the counter:
set_timer0(value) set_timer1(value) ( ) . . . . . . . . .
For timers/counters 0, 1 and 3 the value is a 16 bit int For timer/counter 2 the value is an 8 bit int To read the counter:
value = get_timer0() get timer0() value = get_timer1() . . . . . .
Counters
Program to count pulses on external input to timer/counter 0:
void main() { setup_timer_0(RTCC_EXT_L_TO_H | RTCC_8_BIT); set_timer0(0); lcd init(); lcd_init(); for (;;) { printf(lcd_putc, p ( p , "\f%d", \ , ( (int) ) get_timer0()); g ()); delay_ms(200); } }
James Grimbleby
Slide 82
Timer Interrupts
Microprocessors p normally y execute code sequentially q y Sometimes execution must be suspended temporarily to perform some other task In PICs this happens as the result of interrupt requests An interrupt is raised when a particular condition occurs: timer/counter overflow change in the state of an input line data received on the serial bus completion of an analogue-to-digital conversion power supply p pp y brown-out
School of Systems Engineering - Electronic Engineering Slide 83
James Grimbleby
Timer Interrupts
An interrupt can be generated each time a counter/timer overflows This generates interrupts at a frequency determined by the clock speed p and the timer/counter configuration g The clock, divided by 4 and pre-scaled, is applied to the counter which counts to 2n-1 before overflowing back to 0
Timer Interrupts
Suppose that S th t the th clock l k frequency f is i 20 M Mz and d a pre-scaler l ratio of 16 is used:
Timer Interrupts
CCS C provides the following functions to configure interrupts:
disable_interrupts() enable_interrupts() clear_interrupt()
disables the specified interrupt enables the specified interrupt clear specified interrupt flag
The are corresponding interrupt types and directives for each of f the th available il bl i interrupt t t sources:
INT_TIMER0 INT TIMER0 INT_AD INT RB INT_RB INT_SSP . . . . . . .
James Grimbleby
#INT_TIMER0 #INT TIMER0 Counter/timer 0 oflo #INT_AD A/D conversion complete #INT RB #INT_RB Change on B port #INT_SSP I2C Activity . . . . . . . . . . . . . . . . .
Slide 86
Timer Interrupts
#INT_TIMER0 # 0 void timer_irq() { output_toggle(pin_b1); } void main() { setup_timer_0(RTCC_INTERNAL | RTCC_DIV_16); enable_interrupts(INT_TIMER0); enable_interrupts(GLOBAL); bl i ( ) for (;;) { } }
James Grimbleby
Slide 87
Timer Interrupts
Starting with a 20 MHz clock there is no power-of-2 prescaler ratio that gives an interrupt rate close to 1 Hz A pre-scaler l ratio ti of f 128 gives: i
Timer Interrupts
Pre-loading with a value n:
1 Hz Timer Interrupts
#INT_TIMER0 # 0 void timer_irq() { set_timer0(26474); output_toggle(pin_b1); } void main() { setup_timer_0(RTCC_INTERNAL | RTCC_DIV_128); enable_interrupts(INT_TIMER0); bl i ( 0) enable_interrupts(GLOBAL); for (;;) { } }
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 90
R Q reset RC2 S
Note that q should not exceed the value of the period register It is also necessary to configure counter/timer 2:
setup timer 2(pre scaler period, setup_timer_2(pre-scaler, period 1);
pre-scaler is one of: T2_DIV_BY_1, T2_DIV_BY_4, T2_DIV_BY_16 period (the period register) is an int 0-255
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 94
This function sets up the PIC I/O pins used to communicate with the LCD and initializes the LCD registers Then various routines can be used to control the display:
lcd_clear() l d l () lcd_home() lcd backspace() lcd_backspace() lcd_panleft() lcd panright() lcd_panright() lcd_gotoxy(int x, int y) lcd putc(char c) lcd_putc(char
James Grimbleby
clear complete display goto 1st character on 1st line backspace by 1 character pan complete display left pan complete display right goto x character on y line write character at current pos
Slide 98
printf() can print characters, text, integers and floating-point numbers The first parameter determines the output channel, channel in this case the LCD The second parameter is the formatting string which determines how the following parameters ae displayed Any further parameters are variables or constants to be printed
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 99
s d Ld X LX g w
String or character Signed int Long signed int Hex int (upper case) Hex long int (upper case) Float (rounded decimal) Int with decimal p point
Slide 100
RS232
The PIC18F452 has a built-in Universal Synchronous Asynchronous Receiver Transmitter (USART) This allows it to communicate using the RS232, RS422 and RS485 protocols The e 5 V logic-level og c e e receive ece e a and dt transmit a s ts signals g aso of t the e PIC Ca are e converted to RS232 levels by a MAX232 device Baud rates are generated by dividing down the system clock The USART receive and transmit pins are c7 and c6 respectively
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 102
RS232
CCS C p provides the following g functions to control RS2323 communications:
getc() kbhit() putc(char) printf(form,..)
returns character received on RS232 true when character received on RS232 transmits character over RS232 transmits formatted data over RS232
There is also a directive which sets up the USART for RS232 operation:
#USE RS232(options)
where options include: transmit pin, receive pin, baud rate, bits, and p parity y
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 103
RS232
#use rs232(baud=38400, , xmit=PIN_C6, , rcv=PIN_C7, , parity=n, bits=8) void main() { float p; lcd_init(); for (;;) { p = 5.0 * read_adc() / 1024.0; printf("\n\rVoltage p ( \ \ g = %01.2fV", , p); if (kbhit()) printf(lcd_putc, "%c", fgetc()); delay ms(100); delay_ms(100); } }
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 104
James Grimbleby
Slide 105
James Grimbleby
Slide 106
set the clock source set which pins are analogue set current input channel perform conversion
There is also a directive which determines the return size for read_adc():
#DEVICE ADC=xx
where h xx can b be 8 or 10 ( (when h set tt to 8 th the ADC will ill return t th the most significant byte)
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 107
EEPROM
The PIC18F452 has 256 byte of internal data eeprom EEPROM is not directly mapped to the data space but is accessed indirectly through the SFR: EEADR This memory is non-volatile and can be used to store, for example, e a p e, setup pa parameters a ete s CCS C p provides the following g functions to read and write to the EEPROM:
read_eeprom(address) read eeprom(address) write_eeprom(address, value)
James Grimbleby
Issues a start command on the I2C Sends a single byte over the I2C Reads a byte y over the I2C Issues a stop command on the I2C
There is also a pre-processor directive which configures the device as a Master or a Slave:
#use i2c
This directive also assigns the SDA and SCL pins used for the I2C interface
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 111
24LC256 EEPROM
The Microchip Technology 24LC256/ is a 32K x 8 (256 Kbit) serial EEPROM It has h been b developed d l df for advanced, d d l low-power applications li ti such as personal communications or data acquisition This device is capable of operation across a broad voltage range (1.8V (1 8V to 5 5.5V) 5V) Functional address lines allow up to eight devices on the same bus, for up to 2 Mbit address space It is available in the standard 8-pin plastic DIP,SOIC, TSSOP, MSOP and DFN packages. packages
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 112
24LC256 EEPROM
To p perform a read operation p the master g generates a Start with R/W=0 and sends the word address (MS byte first) Then the master generates a Start with R/W=1 and reads the data Finally the master generates a Stop
James Grimbleby
Slide 113
24LC256 EEPROM
#use i2c(master, sda=pin sda pin_c4, c4, scl scl=pin pin_c3) c3) #define eeprom_addr 0xa0 int read_ext_eeprom(long i d (l int i i) { int q; i2c_start(); i2c_write(eeprom_addr & 0xfe); i2 i2c_write(i i (i >> 8); 8) i2c_write(i & 0xff); i2c start(); i2c_start(); i2c_write(eeprom_addr | 0x01); q = i2c_read(0); i2 i2c_stop(); () return q; }
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 114
24LC256 EEPROM
To p perform a write operation p the master g generates a Start with R/W=0 and sends the word address (MS byte first) and data Then the master generates a Stop To prevent further writes while the device is busy the master should wait for acknowledge (ack=0) before proceeding
James Grimbleby
Slide 115
24LC256 EEPROM
boolean busy() { boolean ack; i2c_start(); ack k = i2c_write(eeprom_addr i i ( dd & 0xfe); f ) i2c_stop(); return ack; ; } void write_ext_eeprom(long int i, int d) { i2c_start(); i2c_write(eeprom_addr _ ( p _ & 0xfe); ); i2c_write(i >> 8); i2c_write(i & 0xff); i2c write(d); i2c_write(d); i2c_stop(); while (busy()); }
James Grimbleby School of Systems Engineering - Electronic Engineering Slide 116
James Grimbleby
Slide 117