Changes to ADC API
[lpc82x] / drivers / i2c.c
1 /****************************************************************************
2  *   drivers/i2c.c
3  *
4  *
5  * Copyright 2012 Nathael Pajani <nathael.pajani@ed3l.fr>
6  *
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  *
21  *************************************************************************** */
24 /**************************************************************************** */
25 /*                      I2C                                                   */
26 /**************************************************************************** */
28 /* I2C driver for the I2C bus integrated module of the LPC82x.
29  * Refer to LPC82x documentation (UM10800.pdf) for more information.
30  */
32 #include "core/system.h"
33 #include "lib/string.h"
34 #include "lib/errno.h"
35 #include "drivers/i2c.h"
38 /*
39  * I2C Bus structure
40  *
41  * mode : current configuration mode : I2C_MASTER, I2C_SLAVE or I2C_MONITOR.
42  * clock : current i2c clock.
43  * state : global state of the i2c engine.
44  *
45  * ctrl_buf : This buffer, if used, must have the SAME size as out_buff.
46  *           Then, instead of simply moving to the next byte, the corresponding condition
47  *           will be executed : I2C_CONT, I2C_DO_REPEATED_START, I2C_DO_STOP_START or I2C_STOP.
48  */
49 struct i2c_bus {
50         volatile struct lpc_i2c* regs;
51         uint8_t irq;
52         uint8_t mode;
53         uint32_t reset_bit;
54         uint32_t power_bit;
55         volatile uint32_t clock;
56         volatile uint32_t state;
58         volatile const char* out_buff;
59         volatile const char* ctrl_buf;
60         volatile uint32_t write_length;
61         volatile uint32_t write_index;
63         volatile char* in_buff;
64         volatile uint32_t read_length;
65         volatile uint32_t read_index;
66 };
69 static struct i2c_bus i2c_buses[NB_I2C_BUSSES] = {
70         {
71                 .regs = (struct lpc_i2c*)LPC_I2C0,
72                 .irq = I2C0_IRQ,
73                 .reset_bit = LPC_I2C0_RESET_N,
74                 .power_bit = LPC_SYS_ABH_CLK_CTRL_I2C0,
75                 .state = I2C_OK,
76         },
77         {
78                 .regs = (struct lpc_i2c*)LPC_I2C1,
79                 .irq = I2C1_IRQ,
80                 .reset_bit = LPC_I2C1_RESET_N,
81                 .power_bit = LPC_SYS_ABH_CLK_CTRL_I2C1,
82                 .state = I2C_OK,
83         },
84         {
85                 .regs = (struct lpc_i2c*)LPC_I2C2,
86                 .irq = I2C2_IRQ,
87                 .reset_bit = LPC_I2C2_RESET_N,
88                 .power_bit = LPC_SYS_ABH_CLK_CTRL_I2C2,
89                 .state = I2C_OK,
90         },
91         {
92                 .regs = (struct lpc_i2c*)LPC_I2C3,
93                 .irq = I2C3_IRQ,
94                 .reset_bit = LPC_I2C3_RESET_N,
95                 .power_bit = LPC_SYS_ABH_CLK_CTRL_I2C3,
96                 .state = I2C_OK,
97         },
98 };
101 /* FIXME : Should add a field "what to do on addr NACK" to i2c_bus structure, and use
102    it with the timeout to create a retry mechanism */
103 /* FIXME : Implement Slave when arbitration lost ? */
107 /* I2C Interrupt handler */
108 /* Actual version will stop on NACKs */
109 void I2C_Handler(uint32_t bus_num)
111         uint8_t condition = I2C_CONT;
112         struct i2c_bus* i2c = &(i2c_buses[bus_num]);
114         /* I2C State Machine ! */
115         /* This handler deals with master read and master write only */
116         switch (i2c->regs->status & 0xFF) {
118         /* Errors */
119                 case 0x00: /* Should never happen */
120                         i2c->regs->int_en_clr = I2C_ST_MASTER_PENDING;
121                         i2c->state = I2C_ERROR_UNKNOWN;
122                         break;
124                 case 0x10:
125                 case 0x11: /* Arbitration lost. We don't deal with multiple master situation */
126                         /* FIXME : We have two option :
127                          *  - do nothing, which will release the bus.
128                          *      This options allows handling of multiple master topologies.
129                          *  - Set start flag, and a start condition will be transmitted when bus becomes free.
130                          */
131                         /* We choose to do nothing. User code should retry later. */
132                         i2c->state = I2C_ARBITRATION_LOST;
133                         break;
135                 case 0x40:
136                 case 0x41: /* Start/Stop error. */
137                         /* A start or stop condition has been detected while it was not allowed by the I2C
138                          *  specification. The master interface has stoped driving the bus and is in idle state.
139                          * We have three option :
140                          *  - Do nothing.
141                          *  - Set start flag, and a start condition will be transmitted when bus becomes free.
142                          *  - Try to detect whether the I2C bus has stalled (?? how ?)
143                          */
144                         /* We choose to do nothing. User code should retry later. */
145                         i2c->state = I2C_BUS_ERROR;
146                         break;
148         /* NACKs */
149                 case 0x06:  /* NACK on Address */
150                 case 0x07:
151                 case 0x08:  /* NACK on Data byte */
152                 case 0x09:
153                         /* Send a STOP condition will end transactions and let the driver retry later. */
154                         i2c->regs->master_ctrl = I2C_MASTER_STOP;
155                         i2c->state = I2C_NACK;
156                         break;
158         /* Rx */
159                 case 0x02:
160                 case 0x03:  /* Receive ready. Data byte has been received */
161                         if (i2c->in_buff != NULL) {
162                                 i2c->in_buff[i2c->read_index] = i2c->regs->master_data;
163                         }
164                         i2c->read_index++;
165                         if (i2c->read_index < i2c->read_length) {
166                                 /* Send ACK (tells the slave to continue) */
167                                 i2c->regs->master_ctrl = I2C_MASTER_CONTINUE;
168                         } else {
169                                 /* Send a NACK (tells the slave this was the last byte)
170                                  * FIXME : We have two other options : Repeated START or STOP + START,
171                                  *    but what for ? periodic reads ?
172                                  */
173                                 i2c->regs->master_ctrl = I2C_MASTER_STOP;
174                                 i2c->state = I2C_OK;
175                         }
176                         break;
178         /* Tx */
179                 case 0x04:
180                 case 0x05:  /* Transmit ready. */
181                         if (i2c->write_length <= 1) { /* Nothing more to send, we must stop. */
182                                 /* This one is used to probe devices, or wait for completion */
183                                 i2c->regs->master_ctrl = I2C_MASTER_STOP;
184                                 i2c->state = I2C_NO_DATA;
185                                 break;
186                         }
187                         
188                         if (i2c->ctrl_buf) {
189                                 condition = i2c->ctrl_buf[i2c->write_index];
190                         }
191                         i2c->write_index++;
193                         switch (condition) {
194                                 case I2C_DO_STOP_START: /* Send STOP / START condition */
195                                         i2c->regs->master_ctrl = I2C_MASTER_STOP;
196                                 case I2C_DO_REPEATED_START: /* Send repeated start condition */
197                                 case I2C_CONT: /* Send next data byte */
198                                         if (i2c->write_index < i2c->write_length) {
199                                                 i2c->regs->master_data = i2c->out_buff[i2c->write_index];
200                                         } else {
201                                                 /* We should have data to send ! Stop the controller. */
202                                                 i2c->regs->master_ctrl = I2C_MASTER_STOP;
203                                                 i2c->state = I2C_NO_DATA;
204                                                 break;
205                                         }
206                                         if (condition == I2C_CONT) {
207                                                 i2c->regs->master_ctrl = I2C_MASTER_CONTINUE;
208                                         } else {
209                                                 i2c->regs->master_ctrl = I2C_MASTER_START;
210                                         }
211                                         break;
212                                 case I2C_STOP: /* Send STOP condition */
213                                         i2c->regs->master_ctrl = I2C_MASTER_STOP;
214                                         i2c->state = I2C_OK;
215                                         break;
216                         }
217                         break;
219                 default:
220                         i2c->state = I2C_ERROR_UNKNOWN;
221                         break;
222         }
224         /* When communication is over, disable the idle/pending interrupt */
225         if (i2c->state != I2C_BUSY) {
226                 i2c->regs->int_en_clr = I2C_ST_MASTER_PENDING;
227         }
228         /* Clear interrupt flag. This has to be done last. */
229         i2c->regs->status = I2C_ST_CLEAR_ALL;
230         return;
234 void I2C_0_Handler(void)
236         I2C_Handler(0);
238 void I2C_1_Handler(void)
240         I2C_Handler(1);
242 void I2C_2_Handler(void)
244         I2C_Handler(2);
246 void I2C_3_Handler(void)
248         I2C_Handler(3);
253 /***************************************************************************** */
254 /*                        I2C access                                           */
255 /***************************************************************************** */
256 static int i2c_perform_data_transfer(struct i2c_bus* i2c)
257 {   
258         int ret = 0;
260         if (i2c->mode != I2C_MASTER) {
261                 return -EINVAL;
262         }
264         /* FIXME : This test is only valid for master */
265         if ((i2c->regs->status & 0x0F) != 0x01) {
266                 return -EBUSY;
267         }
268         /* Start the process */
269         i2c->state = I2C_BUSY;
270         i2c->write_index = 0;
271         i2c->read_index = 0;
272         i2c->regs->master_data = i2c->out_buff[0];
273         i2c->regs->master_ctrl = I2C_MASTER_START;
274         i2c->regs->int_en_set = (I2C_ST_MASTER_PENDING | I2C_ST_MASTER_ARB_LOSS | I2C_ST_MASTER_STERR);
276         /* Wait for process completion */
277         do {} while (i2c->state == I2C_BUSY); /* FIXME : OS should schedule here */
279         /* Handle returned state (errors or OK) */
280         switch (i2c->state) {
281                 case I2C_OK:
282                 case I2C_NO_DATA:
283                         /* Return 0 : success */
284                         break;
285                 case I2C_NACK:
286                         ret = -EREMOTEIO;
287                         break;
288                 case I2C_ARBITRATION_LOST:
289                         ret = -EBUSY;
290                         break;
291                 case I2C_BUS_ERROR: /* This one is bad ... */
292                 case I2C_ERROR_UNKNOWN:
293                 default:
294                         ret = -EIO;
295                         break;
296         }
298         /* Done with the Bus, Disable the interrupts */
299         i2c->regs->int_en_clr = (I2C_ST_MASTER_PENDING | I2C_ST_MASTER_ARB_LOSS | I2C_ST_MASTER_STERR);
300         i2c->state = I2C_OK;
302         return ret;
305 /* Release Bus
306  * Some devices do not release the Bus at the end of a transaction if they don't receive
307  *   a start condition immediately followed by a stop condition.
308  */
309 void i2c_release_bus(uint8_t bus_num)
311         struct i2c_bus* i2c = NULL;
312         if (bus_num >= NB_I2C_BUSSES) {
313                 return;
314         }
315         i2c = &(i2c_buses[bus_num]);
316         /* Force device to release the bus :
317          *  send a START followed by a STOP (initiate transmission with nul write_length) */
318         i2c->state = I2C_BUSY;
319         i2c->write_length = 0;
320         i2c->regs->master_data = 0;
321         i2c->regs->master_ctrl = I2C_MASTER_START;
322         i2c->regs->int_en_set = I2C_ST_MASTER_PENDING;
323         do {} while (i2c->state == I2C_BUSY); /* FIXME : OS should schedule here */
324         i2c->state = I2C_OK;
326         /* Done with the Bus, Disable the interrupts */ 
327         i2c->regs->int_en_clr = (I2C_ST_MASTER_PENDING | I2C_ST_MASTER_ARB_LOSS | I2C_ST_MASTER_STERR);
330 /* Read
331  * Performs a non-blocking read on the module's i2c bus.
332  *   bus_num : I2C bus number to use.
333  *   cmd_buf : buffer containing all control byte to be sent on the i2c bus
334  *   cmd_size : size of the cmd_buf command buffer
335  *   ctrl_buf : buffer containing action to be done after sending, like repeated START conditions
336  *         if not NULL, ctrl_buf has the same size as cmd_buf
337  *   inbuff : the buffer where read data will be put. May be NULL if count is 0.
338  *   count : the number of bytes to be read.
339  * RETURN VALUE
340  *   Upon successfull completion, returns the number of bytes read. On error, returns a negative
341  *   integer equivalent to errors from glibc.
342  */
343 int i2c_read(uint8_t bus_num, const void *cmd_buf, size_t cmd_size, const void* ctrl_buf, void* inbuff, size_t count)
345         int ret = 0;
346         struct i2c_bus* i2c = NULL;
348         if (bus_num >= NB_I2C_BUSSES) {
349                 return -EINVAL;
350         }
351         i2c = &(i2c_buses[bus_num]);
353         /* Checks */
354         if (i2c->clock == 0)
355                 return -EBADFD;
356         if (cmd_buf == NULL)
357                 return -EINVAL;
358         if ((inbuff == NULL) && (count > 0))
359                 return -EINVAL;
361         if (i2c->state == I2C_BUSY) {
362                 return -EBUSY;
363         }
364         if (i2c->state != I2C_OK) {
365                 /* What should we do ??? someone failed to reset status ? */
366         }
368         /* Set up i2c for read operation */
369         /* command (write) buffer */
370         i2c->out_buff = cmd_buf;
371         i2c->write_length = cmd_size;
372         /* Control buffer, if any.
373          * Used to control operations on i2C bus to simplify the interface */
374         i2c->ctrl_buf = ctrl_buf;
375         /* Read buffer */
376         i2c->in_buff = inbuff;
377         i2c->read_length = count;
378         i2c->read_index = 0;
380         ret = i2c_perform_data_transfer(i2c);
381         if (ret == 0) {
382                 return i2c->read_index;
383         }
384         return ret;
387 /* Write
388  * Performs a non-blocking write on the module's i2c bus.
389  *   bus_num : I2C bus number to use.
390  *   buf : buffer containing all byte to be sent on the i2c bus,
391  *         including conrtol bytes (address, offsets, ...)
392  *   count : the number of bytes to be sent, including address bytes and so on.
393  *   ctrl_buf : buffer containing action to be done after sending, like repeated START conditions
394  *         FIXME : note that STOP + START conditions are not allowed, the STOP would lead to sending
395  *         the first bytes of buf, creating an infinite loop.
396  * RETURN VALUE
397  *   Upon successfull completion, returns the number of bytes written. On error, returns a negative
398  *   integer equivalent to errors from glibc.
399  */
400 int i2c_write(uint8_t bus_num, const void *buf, size_t count, const void* ctrl_buf)
402         int ret = 0;
403         struct i2c_bus* i2c = NULL;
405         if (bus_num >= NB_I2C_BUSSES) {
406                 return -EINVAL;
407         }
408         i2c = &(i2c_buses[bus_num]);
410         /* Checks */
411         if (i2c->clock == 0)
412                 return -EBADFD;
413         if (buf == NULL)
414                 return -EINVAL;
416         if (i2c->state == I2C_BUSY) {
417                 return -EBUSY;
418         }
419         if (i2c->state != I2C_OK) {
420                 /* What should we do ??? someone failed to reset status ? */
421         }
423         /* Clear read information to prevent entering master receiver states */
424         i2c->read_length = 0;
425         i2c->in_buff = NULL;
426         /* Set up i2c for write operation */
427         i2c->out_buff = buf;
428         i2c->write_length = count;
429         /* Control buffer, if any.
430          * Used to control operations on i2C bus to simplify the interface */
431         i2c->ctrl_buf = ctrl_buf;
433         ret = i2c_perform_data_transfer(i2c);
434         if (ret == 0) {
435                 return count;
436         }
437         return ret;
441 int i2c_set_timeout(uint8_t bus_num, uint16_t timeout)
443         struct i2c_bus* i2c = NULL;
445         if (bus_num >= NB_I2C_BUSSES) {
446                 return -EINVAL;
447         }
448         i2c = &(i2c_buses[bus_num]);
449         i2c->regs->timeout = timeout;
451         return 0;
454 /***************************************************************************** */
455 /*                I2C Init                                                     */
456 /***************************************************************************** */
458 static void i2c_clock_on(struct i2c_bus* i2c)
460         uint32_t main_clock = get_main_clock();
461         uint32_t scl_div = 0;
463         /* Setup I2C clock */
464         scl_div = (main_clock / (i2c->clock * 4));  /* Two clocks low and two clocks high -> divide by 4 */
465         i2c->regs->clkdiv = (scl_div - 1);
466         i2c->regs->master_timing = 0; /* Two clocks low and two clocks high */
469 /* I2C on / off
470  *   bus_num : I2C bus number to use.
471  *   i2c_clk_freq : I2C clock freqeuncy in Hz
472  *   mode is one of I2C_MASTER, I2C_SLAVE or I2C_MONITOR.
473  */
474 int i2c_on(uint8_t bus_num, uint32_t i2c_clk_freq, uint8_t mode)
476         struct i2c_bus* i2c = NULL;
478         if (bus_num >= NB_I2C_BUSSES) {
479                 return -EINVAL;
480         }
481         i2c = &(i2c_buses[bus_num]);
483         NVIC_DisableIRQ(i2c->irq);
484         /* Power on I2C block */
485         subsystem_power(i2c->power_bit, 1);
486         subsystem_reset(i2c->reset_bit);
487         /* Set clock */
488         i2c->clock = i2c_clk_freq;
489         i2c_clock_on(i2c);
490         /* Disable all interrupt condition */
491         i2c->regs->int_en_clr = ~(0UL);
492         i2c->mode = mode;
493         /* Enable I2C */
494         switch (mode) {
495                 case I2C_MASTER:
496                         i2c->regs->config = I2C_MASTER_EN;
497                         break;
498                 case I2C_SLAVE:
499                         i2c->regs->config = I2C_SLAVE_EN;
500                         break;
501                 case I2C_MONITOR:
502                 default:
503                         i2c->regs->config = I2C_MONITOR_EN;
504                         break;
505         }
506         /* And enable interrupts */
507         NVIC_EnableIRQ(i2c->irq);
509         return 0;
512 int i2c_off(uint8_t bus_num)
514         struct i2c_bus* i2c = NULL;
516         if (bus_num >= NB_I2C_BUSSES) {
517                 return -EINVAL;
518         }
519         i2c = &(i2c_buses[bus_num]);
521         NVIC_DisableIRQ(i2c->irq);
522         subsystem_power(i2c->power_bit, 0);
523         i2c->clock = 0;
525         return 0;
528 /* Allow system to propagate main clock */
529 void i2c_clock_update(void)
531         int i = 0;
533         for (i = 0; i < NB_I2C_BUSSES; i++) {
534                 if (! subsystem_powered(i2c_buses[i].power_bit)) {
535                         continue;
536                 }
537                 if (i2c_buses[i].clock != 0) {
538                 /* FIXME : we should stop I2C transfers, disable I2C interrupts and stop I2C clock. */
539                         i2c_clock_on(&(i2c_buses[i]));
540                 }
541         }