]> git.donarmstrong.com Git - qmk_firmware.git/blob - tmk_core/tool/mbed/mbed-sdk/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC82X/i2c_api.c
Merge commit '1fe4406f374291ab2e86e95a97341fd9c475fcb8'
[qmk_firmware.git] / tmk_core / tool / mbed / mbed-sdk / libraries / mbed / targets / hal / TARGET_NXP / TARGET_LPC82X / i2c_api.c
1 /* mbed Microcontroller Library
2  * Copyright (c) 2006-2013 ARM Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <stdlib.h>
17 #include <string.h>
18
19 #include "i2c_api.h"
20 #include "cmsis.h"
21 #include "pinmap.h"
22
23 #define LPC824_I2C0_FMPLUS 1
24
25 #if DEVICE_I2C
26
27 static const SWM_Map SWM_I2C_SDA[] = {
28     //PINASSIGN Register ID, Pinselect bitfield position
29     { 9,  8}, 
30     { 9, 24},
31     {10,  8},
32 };
33
34 static const SWM_Map SWM_I2C_SCL[] = {
35     //PINASSIGN Register ID, Pinselect bitfield position
36     { 9, 16},
37     {10,  0},
38     {10, 16},
39 };
40
41
42 static int i2c_used = 0;
43 static uint8_t repeated_start = 0;
44
45 #define I2C_DAT(x)          (x->i2c->MSTDAT)
46 #define I2C_STAT(x)         ((x->i2c->STAT >> 1) & (0x07))
47
48 static inline void i2c_power_enable(int ch)
49 {
50     switch(ch) {
51         case 0:
52             // I2C0, Same as for LPC812
53             LPC_SYSCON->SYSAHBCLKCTRL |=  (1 << 5);
54             LPC_SYSCON->PRESETCTRL    &= ~(1 << 6);
55             LPC_SYSCON->PRESETCTRL    |=  (1 << 6);
56             break;
57         case 1:
58         case 2:
59         case 3:
60             // I2C1,I2C2 or I2C3. Not available for LPC812
61             LPC_SYSCON->SYSAHBCLKCTRL |=  (1 << (20 + ch));
62             LPC_SYSCON->PRESETCTRL    &= ~(1 << (13 + ch));
63             LPC_SYSCON->PRESETCTRL    |=  (1 << (13 + ch));
64             break;
65         default:
66             break;
67     }
68 }
69
70
71 static inline void i2c_interface_enable(i2c_t *obj) {
72   obj->i2c->CFG |=  (1 << 0);  // Enable Master mode
73 //  obj->i2c->CFG &= ~(1 << 1);  // Disable Slave mode
74 }
75
76
77 static int get_available_i2c(void) {
78     int i;
79     for (i=0; i<3; i++) {
80         if ((i2c_used & (1 << i)) == 0)
81             return i+1;
82     }
83     return -1;
84 }
85
86 void i2c_init(i2c_t *obj, PinName sda, PinName scl)
87 {
88     const SWM_Map *swm;
89     uint32_t regVal;
90     int i2c_ch = 0;
91     
92     //LPC824
93     //I2C0 can support FM+ but only on P0_11 and P0_10
94     if (sda == I2C_SDA && scl == I2C_SCL) {
95       //Select I2C mode for P0_11 and P0_10
96       LPC_SWM->PINENABLE0 &= ~(0x3 << 11);
97       
98 #if(LPC824_I2C0_FMPLUS == 1)
99       // Enable FM+ mode on P0_11, P0_10    
100       LPC_IOCON->PIO0_10 &= ~(0x3 << 8);
101       LPC_IOCON->PIO0_10 |=  (0x2 << 8); //FM+ mode
102       LPC_IOCON->PIO0_11 &= ~(0x3 << 8);
103       LPC_IOCON->PIO0_11 |=  (0x2 << 8); //FM+ mode      
104 #endif
105     }
106     else {
107         //Select any other pin for I2C1, I2C2 or I2C3
108         i2c_ch = get_available_i2c();
109         if (i2c_ch == -1)
110             return;
111         i2c_used |= (1 << (i2c_ch - 1));
112
113         swm = &SWM_I2C_SDA[i2c_ch - 1];
114         regVal = LPC_SWM->PINASSIGN[swm->n] & ~(0xFF << swm->offset);
115         LPC_SWM->PINASSIGN[swm->n] = regVal |  ((sda >> PIN_SHIFT) << swm->offset);
116
117         swm = &SWM_I2C_SCL[i2c_ch - 1];
118         regVal = LPC_SWM->PINASSIGN[swm->n] & ~(0xFF << swm->offset);
119         LPC_SWM->PINASSIGN[swm->n] = regVal |  ((scl >> PIN_SHIFT) << swm->offset);
120     }
121
122     switch(i2c_ch) {
123         case 0:
124             obj->i2c = (LPC_I2C0_Type *)LPC_I2C0;
125             break;
126         case 1:
127             obj->i2c = (LPC_I2C0_Type *)LPC_I2C1;
128             break;
129         case 2:
130             obj->i2c = (LPC_I2C0_Type *)LPC_I2C2;
131             break;
132         case 3:
133             obj->i2c = (LPC_I2C0_Type *)LPC_I2C3;
134             break;
135         default:
136             break;
137     }
138
139     // enable power
140     i2c_power_enable(i2c_ch);
141     // set default frequency at 100k
142     i2c_frequency(obj, 100000);   
143     i2c_interface_enable(obj);
144 }
145
146
147 static inline int i2c_status(i2c_t *obj) {
148     return I2C_STAT(obj);
149 }
150
151 // Wait until the Master Serial Interrupt (SI) is set
152 // Timeout when it takes too long.
153 static int i2c_wait_SI(i2c_t *obj) {
154     int timeout = 0;
155     while (!(obj->i2c->STAT & (1 << 0))) {
156         timeout++;
157         if (timeout > 100000) return -1;
158     }
159     return 0;
160 }
161
162
163 //Attention. Spec says: First store Address in DAT before setting STA ! 
164 //Undefined state when using single byte I2C operations and too much delay
165 //between i2c_start and do_i2c_write(Address).
166 //Also note that lpc812/824 will immediately continue reading a byte when Address b0 == 1
167 inline int i2c_start(i2c_t *obj) {
168     int status = 0;
169     if (repeated_start) {
170         obj->i2c->MSTCTL = (1 << 1) | (1 << 0); // STA bit and Continue bit to complete previous RD or WR
171         repeated_start = 0;
172     } else {
173         obj->i2c->MSTCTL = (1 << 1); // STA bit
174     }
175     return status;
176 }
177
178 //Generate Stop condition and wait until bus is Idle
179 //Will also send NAK for previous RD
180 inline int i2c_stop(i2c_t *obj) {
181     int timeout = 0;
182
183     // STP bit and Continue bit. Sends NAK to complete previous RD
184     obj->i2c->MSTCTL = (1 << 2) | (1 << 0);
185     
186     //Spin until Ready (b0 == 1)and Status is Idle (b3..b1 == 000)
187     while ((obj->i2c->STAT & ((7 << 1) | (1 << 0))) != ((0 << 1) | (1 << 0))) {
188         timeout ++;
189         if (timeout > 100000) return 1;
190     }
191
192     // repeated_start = 0; // bus free
193     return 0;
194 }
195
196 //Spec says: first check Idle and status is Ok
197 static inline int i2c_do_write(i2c_t *obj, int value, uint8_t addr) {
198     // write the data
199     I2C_DAT(obj) = value;
200     
201     if (!addr)
202         obj->i2c->MSTCTL = (1 << 0); //Set continue for data. Should not be set for addr since that uses STA
203     
204     // wait and return status
205     i2c_wait_SI(obj);
206     return i2c_status(obj);
207 }
208
209
210 //Attention, correct Order: wait for data ready, read data, read status, continue, return
211 //Dont read DAT or STAT when not ready, so dont read after setting continue.
212 //Results may be invalid when next read is underway.
213 static inline int i2c_do_read(i2c_t *obj, int last) {
214     // wait for it to arrive
215     i2c_wait_SI(obj);
216     if (!last)
217         obj->i2c->MSTCTL = (1 << 0); //ACK and Continue
218     
219     // return the data
220     return (I2C_DAT(obj) & 0xFF);
221 }
222
223
224 void i2c_frequency(i2c_t *obj, int hz) {
225     // No peripheral clock divider on the M0
226     uint32_t PCLK = SystemCoreClock;
227     
228     uint32_t clkdiv = PCLK / (hz * 4) - 1;
229     
230     obj->i2c->CLKDIV = clkdiv;
231     obj->i2c->MSTTIME = 0;
232 }
233
234 // The I2C does a read or a write as a whole operation
235 // There are two types of error conditions it can encounter
236 //  1) it can not obtain the bus
237 //  2) it gets error responses at part of the transmission
238 //
239 // We tackle them as follows:
240 //  1) we retry until we get the bus. we could have a "timeout" if we can not get it
241 //      which basically turns it in to a 2)
242 //  2) on error, we use the standard error mechanisms to report/debug
243 //
244 // Therefore an I2C transaction should always complete. If it doesn't it is usually
245 // because something is setup wrong (e.g. wiring), and we don't need to programatically
246 // check for that
247 int i2c_read(i2c_t *obj, int address, char *data, int length, int stop) {
248     int count, status;
249     
250     //Store the address+RD and then generate STA
251     I2C_DAT(obj) = address | 0x01;
252     i2c_start(obj);    
253
254     // Wait for completion of STA and Sending of SlaveAddress+RD and first Read byte
255     i2c_wait_SI(obj);
256     status = i2c_status(obj);    
257     if (status == 0x03) { // NAK on SlaveAddress
258         i2c_stop(obj);
259         return I2C_ERROR_NO_SLAVE;
260     }
261
262     // Read in all except last byte
263     for (count = 0; count < (length-1); count++) {
264         
265       // Wait for it to arrive, note that first byte read after address+RD is already waiting
266       i2c_wait_SI(obj);
267       status = i2c_status(obj);
268       if (status != 0x01) { // RX RDY
269         i2c_stop(obj);
270         return count;
271       }
272       data[count] = I2C_DAT(obj) & 0xFF; // Store read byte
273
274       obj->i2c->MSTCTL = (1 << 0); // Send ACK and Continue to read
275     }
276     
277     // Read final byte
278     // Wait for it to arrive
279     i2c_wait_SI(obj);
280
281     status = i2c_status(obj);
282     if (status != 0x01) { // RX RDY
283       i2c_stop(obj);
284       return count;
285     }
286     data[count] = I2C_DAT(obj) & 0xFF; // Store final read byte
287
288     // If not repeated start, send stop.
289     if (stop) {
290         i2c_stop(obj); // Also sends NAK for last read byte
291     } else {
292         repeated_start = 1;
293     }
294    
295     return length;
296 }
297
298
299 int i2c_write(i2c_t *obj, int address, const char *data, int length, int stop) {
300     int i, status;
301
302     //Store the address+/WR and then generate STA
303     I2C_DAT(obj) = address & 0xFE;   
304     i2c_start(obj);
305     
306     // Wait for completion of STA and Sending of SlaveAddress+/WR
307     i2c_wait_SI(obj);
308     status = i2c_status(obj);    
309     if (status == 0x03) { // NAK SlaveAddress
310         i2c_stop(obj);
311         return I2C_ERROR_NO_SLAVE;
312     }
313     
314     //Write all bytes
315     for (i=0; i<length; i++) {
316         status = i2c_do_write(obj, data[i], 0);
317         if (status != 0x02) { // TX RDY. Handles a Slave NAK on datawrite
318             i2c_stop(obj);
319             return i;
320         }
321     }
322     
323     // If not repeated start, send stop.
324     if (stop) {
325         i2c_stop(obj);
326     } else {
327         repeated_start = 1;
328     }
329     
330     return length;
331 }
332
333 void i2c_reset(i2c_t *obj) {
334     i2c_stop(obj);
335 }
336
337 int i2c_byte_read(i2c_t *obj, int last) {
338     return (i2c_do_read(obj, last) & 0xFF);
339 //    return (i2c_do_read(obj, last, 0) & 0xFF);    
340 }
341
342 int i2c_byte_write(i2c_t *obj, int data) {
343     int ack;
344     int status = i2c_do_write(obj, (data & 0xFF), 0);
345     
346     switch(status) {
347         case 2: // TX RDY. Handles a Slave NAK on datawrite
348             ack = 1;
349             break;
350         default:
351             ack = 0;
352             break;
353     }
354
355     return ack;
356 }
357
358
359 #if DEVICE_I2CSLAVE
360
361 #define I2C_SLVDAT(x)        (x->i2c->SLVDAT)
362 #define I2C_SLVSTAT(x)      ((x->i2c->STAT >> 9) & (0x03))
363 #define I2C_SLVSI(x)        ((x->i2c->STAT >> 8) & (0x01))
364 //#define I2C_SLVCNT(x)        (x->i2c->SLVCTL = (1 << 0))
365 //#define I2C_SLVNAK(x)        (x->i2c->SLVCTL = (1 << 1))
366
367 #if(0)
368 // Wait until the Slave Serial Interrupt (SI) is set
369 // Timeout when it takes too long.
370 static int i2c_wait_slave_SI(i2c_t *obj) {
371     int timeout = 0;
372     while (!(obj->i2c->STAT & (1 << 8))) {
373         timeout++;
374         if (timeout > 100000) return -1;
375     }
376     return 0;
377 }
378 #endif
379
380 void i2c_slave_mode(i2c_t *obj, int enable_slave) {
381
382   if (enable_slave) {
383 //    obj->i2c->CFG &= ~(1 << 0); //Disable Master mode    
384     obj->i2c->CFG |=  (1 << 1); //Enable Slave mode
385   }
386   else {
387 //    obj->i2c->CFG |=  (1 << 0); //Enable Master mode    
388     obj->i2c->CFG &= ~(1 << 1); //Disable Slave mode
389   } 
390 }
391
392 // Wait for next I2C event and find out what is going on
393 //
394 int i2c_slave_receive(i2c_t *obj) {
395   int addr;
396   
397   // Check if there is any data pending
398   if (! I2C_SLVSI(obj)) {
399     return 0; //NoData    
400   };
401   
402   // Check State
403   switch(I2C_SLVSTAT(obj)) {
404     case 0x0: // Slave address plus R/W received 
405               // At least one of the four slave addresses has been matched by hardware.
406               // You can figure out which address by checking Slave address match Index in STAT register.
407                
408               // Get the received address
409               addr = I2C_SLVDAT(obj) & 0xFF;
410               // Send ACK on address and Continue
411               obj->i2c->SLVCTL = (1 << 0); 
412               
413               if (addr == 0x00) {
414                 return 2; //WriteGeneral
415               }  
416               //check the RW bit
417               if ((addr & 0x01) == 0x01) {
418                 return 1; //ReadAddressed
419               }
420               else {
421                 return 3; //WriteAddressed
422               }
423               //break;
424     
425     case 0x1: // Slave receive. Received data is available (Slave Receiver mode).
426               // Oops, should never get here...     
427               obj->i2c->SLVCTL = (1 << 1);  // Send NACK on received data, try to recover...
428               return 0; //NoData        
429               
430     case 0x2: // Slave transmit. Data can be transmitted (Slave Transmitter mode).
431               // Oops, should never get here...         
432               I2C_SLVDAT(obj) = 0xFF;       // Send dummy data for transmission
433               obj->i2c->SLVCTL = (1 << 0);  // Continue and try to recover...
434               return 0; //NoData        
435     
436     case 0x3: // Reserved.
437     default:  // Oops, should never get here... 
438               obj->i2c->SLVCTL = (1 << 0);  // Continue and try to recover...              
439               return 0; //NoData        
440               //break; 
441   } //switch status  
442 }
443
444 // The dedicated I2C Slave byte read and byte write functions need to be called
445 // from 'common' mbed I2CSlave API for devices that have separate Master and 
446 // Slave engines such as the lpc812 and lpc1549.
447
448 //Called when Slave is addressed for Write, Slave will receive Data in polling mode
449 //Parameter last=1 means received byte will be NACKed.
450 int i2c_slave_byte_read(i2c_t *obj, int last) {
451   int data;
452   
453   // Wait for data
454   while (!I2C_SLVSI(obj)); // Wait forever
455 //if (i2c_wait_slave_SI(obj) != 0) {return -2;} // Wait with timeout
456
457   // Dont bother to check State, were not returning it anyhow..
458 //if (I2C_SLVSTAT(obj)) == 0x01) {
459   // Slave receive. Received data is available (Slave Receiver mode).    
460 //};
461
462   data = I2C_SLVDAT(obj) & 0xFF; // Get and store the received data
463   if (last) {
464     obj->i2c->SLVCTL = (1 << 1);  // Send NACK on received data and Continue 
465   }    
466   else {  
467     obj->i2c->SLVCTL = (1 << 0);  // Send ACK on data and Continue to read                
468   }
469  
470   return data; 
471 }
472
473
474 //Called when Slave is addressed for Read, Slave will send Data in polling mode
475 //
476 int i2c_slave_byte_write(i2c_t *obj, int data) {
477
478   // Wait until Ready 
479   while (!I2C_SLVSI(obj)); // Wait forever
480 //  if (i2c_wait_slave_SI(obj) != 0) {return -2;} // Wait with timeout
481
482   // Check State
483   switch(I2C_SLVSTAT(obj)) {
484     case 0x0: // Slave address plus R/W received 
485               // At least one of the four slave addresses has been matched by hardware.
486               // You can figure out which address by checking Slave address match Index in STAT register.                
487               // I2C Restart occurred
488               return -1; 
489               //break;    
490     case 0x1: // Slave receive. Received data is available (Slave Receiver mode).
491               // Should not get here... 
492               return -2;
493               //break;                
494     case 0x2: // Slave transmit. Data can be transmitted (Slave Transmitter mode).
495               I2C_SLVDAT(obj) = data & 0xFF; // Store the data for transmission
496               obj->i2c->SLVCTL = (1 << 0);   // Continue to send
497               
498               return 1;    
499               //break;      
500     case 0x3: // Reserved.
501     default:
502               // Should not get here... 
503               return -3;
504               //break; 
505   } // switch status
506 }
507
508
509 //Called when Slave is addressed for Write, Slave will receive Data in polling mode
510 //Parameter length (>=1) is the maximum allowable number of bytes. All bytes will be ACKed.
511 int i2c_slave_read(i2c_t *obj, char *data, int length) {
512   int count=0;
513   
514   // Read and ACK all expected bytes
515   while (count < length) {
516     // Wait for data
517     while (!I2C_SLVSI(obj)); // Wait forever
518 //    if (i2c_wait_slave_SI(obj) != 0) {return -2;} // Wait with timeout
519
520     // Check State
521     switch(I2C_SLVSTAT(obj)) {
522       case 0x0: // Slave address plus R/W received 
523                 // At least one of the four slave addresses has been matched by hardware.
524                 // You can figure out which address by checking Slave address match Index in STAT register.                
525                 // I2C Restart occurred
526                 return -1; 
527                 //break;
528     
529       case 0x1: // Slave receive. Received data is available (Slave Receiver mode).
530                 data[count] = I2C_SLVDAT(obj) & 0xFF; // Get and store the received data
531                 obj->i2c->SLVCTL = (1 << 0);          // Send ACK on data and Continue to read                
532                 break;
533
534       case 0x2: // Slave transmit. Data can be transmitted (Slave Transmitter mode).
535       case 0x3: // Reserved.
536       default:  // Should never get here... 
537                 return -2;
538                 //break; 
539     } // switch status
540     
541     count++;
542   } // for all bytes
543     
544   return count; // Received the expected number of bytes
545 }
546
547
548 //Called when Slave is addressed for Read, Slave will send Data in polling mode
549 //Parameter length (>=1) is the maximum number of bytes. Exit when Slave byte is NACKed.
550 int i2c_slave_write(i2c_t *obj, const char *data, int length) {
551   int count;
552   
553   // Send and all bytes or Exit on NAK
554   for (count=0; count < length; count++) {
555     // Wait until Ready for data 
556     while (!I2C_SLVSI(obj)); // Wait forever
557 //    if (i2c_wait_slave_SI(obj) != 0) {return -2;} // Wait with timeout
558
559     // Check State
560     switch(I2C_SLVSTAT(obj)) {
561       case 0x0: // Slave address plus R/W received 
562                 // At least one of the four slave addresses has been matched by hardware.
563                 // You can figure out which address by checking Slave address match Index in STAT register.                
564                 // I2C Restart occurred
565                 return -1; 
566                 //break;    
567       case 0x1: // Slave receive. Received data is available (Slave Receiver mode).
568                 // Should not get here... 
569                 return -2;
570                 //break;                
571       case 0x2: // Slave transmit. Data can be transmitted (Slave Transmitter mode).
572                 I2C_SLVDAT(obj) = data[count] & 0xFF; // Store the data for transmission
573                 obj->i2c->SLVCTL = (1 << 0);          // Continue to send
574                 break;      
575       case 0x3: // Reserved.
576       default:
577               // Should not get here... 
578               return -3;
579               //break; 
580     } // switch status
581   } // for all bytes
582      
583   return length; // Transmitted the max number of bytes
584 }
585
586
587 // Set the four slave addresses. 
588 void i2c_slave_address(i2c_t *obj, int idx, uint32_t address, uint32_t mask) {
589   obj->i2c->SLVADR0   = (address & 0xFE); // Store address in address 0 register
590   obj->i2c->SLVADR1   = (0x00    & 0xFE); // Store general call write address in address 1 register
591   obj->i2c->SLVADR2   = (0x01);           // Disable address 2 register
592   obj->i2c->SLVADR3   = (0x01);           // Disable address 3 register
593   obj->i2c->SLVQUAL0  = (mask & 0xFE);    // Qualifier mask for address 0 register. Any maskbit that is 1 will always be a match 
594 }
595
596 #endif
597
598 #endif