193e7b2ea657a86f82ab7a06b7b0363f6a79ab03
[bertos.git] / bertos / drv / i2c.h
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2005 Develer S.r.l. (http://www.develer.com/)
30  *
31  * -->
32  *
33  * \addtogroup i2c_api
34  * \brief I2C generic driver functions.
35  *
36  * Some hardware requires you to declare the number of transferred
37  * bytes and the communication direction before actually reading or writing
38  * to the bus.
39  * Furthermore, sometimes you need to specify the first transferred byte
40  * before any data is sent over the bus.
41  *
42  * The usage pattern for writing is the following:
43  * \code
44  * i2c_init(args...);
45  * ...
46  * i2c_start_w(args...);
47  * i2c_write(i2c, buf, len);
48  * \endcode
49  * The flags in i2c_start_w determine if the stop command is sent after
50  * the data. Notice that you don't need to explicitly call a stop function
51  * after the write.
52  *
53  * Reading is a bit more complicated and it largely depends on the specific
54  * slave hardware.
55  * In general, the hardware may require you to first write something, then
56  * read the data without closing the communication. For example, EPROMs
57  * require first to write the reading address and then to read the actual
58  * data.
59  * Here is an example of how you can deal with such hardware:
60  *
61  * \code
62  * // init a session without closing it
63  * i2c_start_w(i2c, dev, bytes, I2C_NOSTOP);
64  * // write the address to read from
65  * i2c_write(i2c, addr, bytes);
66  * if (i2c_error(i2c))
67  *     // check for errors during setup
68  *     //...
69  * // now start the real data transfer
70  * i2c_start_r(i2c, dev, bytes, I2C_STOP);
71  * i2c_read(i2c, buf, bytes);
72  * // check for errors
73  * if (i2c_error(i2c))
74  *     //...
75  * \endcode
76  *
77  * It's not guaranteed that after a single call to i2c_putc, i2c_getc etc.
78  * data will pass on the bus (this is hardware dependent).
79  * However, it IS guaranteed after you have sent all the data.
80  *
81  * You can check error conditions by calling the function i2c_error after
82  * each function call. (This is similar to libc errno handling).
83  *
84  * \author Francesco Sacchi <batt@develer.com>
85  *
86  * $WIZ$ module_name = "i2c"
87  * $WIZ$ module_configuration = "bertos/cfg/cfg_i2c.h"
88  * $WIZ$ module_hw = "bertos/hw/hw_i2c_bitbang.h"
89  * $WIZ$ module_depends = "i2c_bitbang"
90  * $WIZ$ module_supports = "not atmega103 and not atmega168 and not at91"
91  */
92
93 #ifndef DRV_I2C_H
94 #define DRV_I2C_H
95
96 #include "cfg/cfg_i2c.h"
97
98 #include <cfg/compiler.h>
99 #include <cfg/macros.h>
100 #include <cfg/debug.h>
101
102 #include <cpu/attr.h>
103
104 #define I2C_READBIT BV(0)
105
106 /** \defgroup i2c_driver I2C driver
107  */
108
109 /*
110  * The following macros are needed to maintain compatibility with older i2c API.
111  * They can be safely removed once the old API is removed.
112  */
113
114  /**
115   * \addtogroup i2c_api
116   * \{
117   */
118 #if COMPILER_C99
119         #define i2c_init(...)           PP_CAT(i2c_init ## _, COUNT_PARMS(__VA_ARGS__)) (__VA_ARGS__)
120         #define i2c_start_w(...)        PP_CAT(i2c_start_w ## _, COUNT_PARMS(__VA_ARGS__)) (__VA_ARGS__)
121         #define i2c_start_r(...)        PP_CAT(i2c_start_r ## _, COUNT_PARMS(__VA_ARGS__)) (__VA_ARGS__)
122 #else
123         /**
124          * Initialize I2C module.
125          *
126          * To initialize the module you can write this code:
127          * \code
128          * I2c ctx;
129          * i2c_init(&ctx, 0, CONFIG_I2C_FREQ);
130          * \endcode
131          * This macro expands in two versions, depending on the number of
132          * parameters, to maintain compatibility with old API:
133          * \li i2c_init_3(I2c *i2c, int dev, uint32_t clock)
134          * \li i2c_init_0(void)
135          *
136          * Do NOT use the above functions directly, use i2c_init().
137          * \note Use the version with 3 parameters, the other one is only for
138          * legacy code.
139          */
140         #define i2c_init(args...)       PP_CAT(i2c_init ## _, COUNT_PARMS(args)) (args)
141
142         /**
143          * Start a write session.
144          *
145          * To start a write session, use the following code:
146          * \code
147          * i2c_start_w(i2c, dev, bytes, I2C_STOP);
148          * \endcode
149          *
150          * This macro expands in two versions, depending on the number of parameters:
151          * \li i2c_start_w_4(I2c *i2c, uint16_t slave_addr, size_t size, int flags)
152          * \li i2c_builtin_start_w(uint8_t id): Deprecated API, don't use in new projects
153          * \li i2c_bitbang_start_w(uint8_t id): Deprecated API, don't use in new projects
154          *
155          * Do NOT use the above functions directly, use i2c_start_w().
156          * \note Use the version with 4 parameters, the others are only for legacy code
157          */
158         #define i2c_start_w(args...)    PP_CAT(i2c_start_w ## _, COUNT_PARMS(args)) (args)
159
160         /**
161          * Start a read session.
162          *
163          * To start a read session, use the following code:
164          * \code
165          * i2c_start_r(i2c, dev, bytes, I2C_STOP);
166          * \endcode
167          *
168          * This macro expands in two versions, depending on the number of parameters:
169          * \li i2c_start_r_4(I2c *i2c, uint16_t slave_addr, size_t size, int flags)
170          * \li i2c_builtin_start_r(uint8_t id): Deprecated API, don't use in new projects
171          * \li i2c_bitbang_start_r(uint8_t id): Deprecated API, don't use in new projects
172          *
173          * Do NOT use the above functions directly, use i2c_start_r().
174          * \note Use the version with 4 parameters, the others are only for legacy code
175          */
176         #define i2c_start_r(args...)    PP_CAT(i2c_start_r ## _, COUNT_PARMS(args)) (args)
177 #endif
178 /**\}*/
179
180
181 /**
182  * \name I2C bitbang devices enum
183  */
184 enum
185 {
186         I2C_BITBANG_OLD = -1,
187         I2C_BITBANG0 = 1000, ///< Use bitbang on port 0
188         I2C_BITBANG1,        ///< Use bitbang on port 1
189         I2C_BITBANG2,
190         I2C_BITBANG3,
191         I2C_BITBANG4,
192         I2C_BITBANG5,
193         I2C_BITBANG6,
194         I2C_BITBANG7,
195         I2C_BITBANG8,
196         I2C_BITBANG9,
197
198         I2C_BITBANG_CNT  /**< Number of i2c ports */
199 };
200
201 /**
202  * \defgroup old_i2c_api Old I2C API
203  * \ingroup i2c_driver
204  *
205  * This is the old and deprecated I2C API. It is maintained for backward
206  * compatibility only, don't use it in new projects.
207  * @{
208  */
209 #if !CONFIG_I2C_DISABLE_OLD_API
210
211 /**
212  * \ingroup old_i2c_api
213  * I2C Backends.
214  * Sometimes your cpu does not have a builtin
215  * i2c driver or you don't want, for some reason, to
216  * use that.
217  * With this you can choose, at compile time, which backend to use.
218  * @{
219  */
220 #define I2C_BACKEND_BUILTIN 0 ///< Uses cpu builtin i2c driver
221 #define I2C_BACKEND_BITBANG 1 ///< Uses emulated bitbang driver
222 /**@}*/
223
224 /**
225  * \name I2c builtin prototypes.
226  * \ingroup old_i2c_api
227  * Do NOT use these function directly, instead,
228  * you can call the ones named without "_builtin_"
229  * and specify in cfg_i2c.h (CONFIG_I2C_BACKEND)
230  * that you want the builtin backend.
231  * @{
232  */
233 bool i2c_builtin_start_w(uint8_t id);
234 bool i2c_builtin_start_r(uint8_t id);
235 void i2c_builtin_stop(void);
236 bool i2c_builtin_put(uint8_t _data);
237 int i2c_builtin_get(bool ack);
238 /**@}*/
239
240 /**
241  * \name I2c bitbang prototypes.
242  * \ingroup old_i2c_api
243  * Do NOT use these function directly, instead,
244  * you can call the ones named without "_bitbang_"
245  * and specify in cfg_i2c.h (CONFIG_I2C_BACKEND)
246  * that you want the bitbang backend.
247  * @{
248  */
249 bool i2c_bitbang_start_w(uint8_t id);
250 bool i2c_bitbang_start_r(uint8_t id);
251 void i2c_bitbang_stop(void);
252 bool i2c_bitbang_put(uint8_t _data);
253 int i2c_bitbang_get(bool ack);
254 /**@}*/
255
256 #ifndef CONFIG_I2C_BACKEND
257 #define  CONFIG_I2C_BACKEND  I2C_BACKEND_BUILTIN
258 #endif
259
260 #if CONFIG_I2C_BACKEND == I2C_BACKEND_BUILTIN
261         #define i2c_start_w_1   i2c_builtin_start_w
262         #define i2c_start_r_1   i2c_builtin_start_r
263         #define i2c_stop        i2c_builtin_stop
264         #define i2c_put         i2c_builtin_put
265         #define i2c_get         i2c_builtin_get
266 #elif CONFIG_I2C_BACKEND == I2C_BACKEND_BITBANG
267         #define i2c_start_w_1   i2c_bitbang_start_w
268         #define i2c_start_r_1   i2c_bitbang_start_r
269         #define i2c_stop        i2c_bitbang_stop
270         #define i2c_put         i2c_bitbang_put
271         #define i2c_get         i2c_bitbang_get
272 #else
273         #error Unsupported i2c backend.
274 #endif
275
276
277 bool i2c_send(const void *_buf, size_t count);
278 bool i2c_recv(void *_buf, size_t count);
279
280 #endif /* !CONFIG_I2C_DISABLE_OLD_API */
281 /**@}*/
282
283 /** \defgroup i2c_api I2C driver API
284  * \ingroup i2c_driver
285  * \{
286  */
287
288 /**
289  * \name I2C error flags
290  * \ingroup i2c_api
291  * @{
292  */
293 #define I2C_OK               0     ///< I2C no errors flag
294 #define I2C_DATA_NACK     BV(4)    ///< I2C generic error
295 #define I2C_ERR           BV(3)    ///< I2C generic error
296 #define I2C_ARB_LOST      BV(2)    ///< I2C arbitration lost error
297 #define I2C_START_TIMEOUT BV(0)    ///< I2C timeout error on start
298 #define I2C_NO_ACK        BV(1)    ///< I2C no ack for sla start
299 /**@}*/
300
301 /**
302  * \name I2C command flags
303  * \ingroup i2c_api
304  * @{
305  */
306 #define I2C_NOSTOP           0    ///< Do not program the stop for current transition
307 #define I2C_STOP          BV(0)   ///< Program the stop for current transition
308 /** @} */
309 #define I2C_START_R       BV(1)   // Start read command
310 #define I2C_START_W          0    // Start write command
311
312
313 #define I2C_TEST_START(flag)  ((flag) & I2C_START_R)
314 #define I2C_TEST_STOP(flag)   ((flag) & I2C_STOP)
315
316 struct I2cHardware;
317 struct I2c;
318
319 typedef void (*i2c_start_t)(struct I2c *i2c, uint16_t slave_addr);
320 typedef uint8_t (*i2c_getc_t)(struct I2c *i2c);
321 typedef void (*i2c_putc_t)(struct I2c *i2c, uint8_t data);
322 typedef void (*i2c_write_t)(struct I2c *i2c, const void *_buf, size_t count);
323 typedef void (*i2c_read_t)(struct I2c *i2c, void *_buf, size_t count);
324
325 typedef struct I2cVT
326 {
327         i2c_start_t start;
328         i2c_getc_t   getc;
329         i2c_putc_t   putc;
330         i2c_write_t  write;
331         i2c_read_t   read;
332 } I2cVT;
333
334 typedef struct I2c
335 {
336         int errors;
337         int flags;
338         size_t xfer_size;
339         struct I2cHardware* hw;
340         const struct I2cVT *vt;
341 } I2c;
342
343
344 #include CPU_HEADER(i2c)
345
346 /*
347  * Low level i2c  init implementation prototype.
348  */
349 void i2c_hw_init(I2c *i2c, int dev, uint32_t clock);
350 void i2c_hw_bitbangInit(I2c *i2c, int dev);
351
352 void i2c_genericWrite(I2c *i2c, const void *_buf, size_t count);
353 void i2c_genericRead(I2c *i2c, void *_buf, size_t count);
354
355 /*
356  * Start a i2c transfer.
357  *
358  * \param i2c Context structure.
359  * \param slave_addr Address of slave device
360  * \param size Size of the transfer
361  */
362 INLINE void i2c_start(I2c *i2c, uint16_t slave_addr, size_t size)
363 {
364         ASSERT(i2c->vt);
365         ASSERT(i2c->vt->start);
366
367         if (!i2c->errors)
368                 ASSERT(i2c->xfer_size == 0);
369
370         i2c->errors = 0;
371         i2c->xfer_size = size;
372
373         i2c->vt->start(i2c, slave_addr);
374 }
375
376 /**
377  * \name I2C interface functions
378  * \ingroup i2c_api
379  * @{
380  */
381
382 /**
383  * Start a read session.
384  * \param i2c I2C context
385  * \param slave_addr Address of the slave device
386  * \param size Number of bytes to be read from device
387  * \param flags Session flags (I2C command flags)
388  */
389 INLINE void i2c_start_r_4(I2c *i2c, uint16_t slave_addr, size_t size, int flags)
390 {
391         ASSERT(i2c);
392         i2c->flags = flags | I2C_START_R;
393         i2c_start(i2c, slave_addr, size);
394 }
395
396 /**
397  * Start a write session.
398  * \param i2c I2C context
399  * \param slave_addr Address of the slave device
400  * \param size Size to be transferred
401  * \param flags Session flags
402  */
403 INLINE void i2c_start_w_4(I2c *i2c, uint16_t slave_addr, size_t size, int flags)
404 {
405         ASSERT(i2c);
406         i2c->flags = flags & ~I2C_START_R;
407         i2c_start(i2c, slave_addr, size);
408 }
409
410 /**
411  * Read a byte from I2C bus.
412  * \param i2c I2C context
413  * \return Byte read
414  */
415 INLINE uint8_t i2c_getc(I2c *i2c)
416 {
417         ASSERT(i2c);
418         ASSERT(i2c->vt);
419         ASSERT(i2c->vt->getc);
420
421         ASSERT(i2c->xfer_size);
422
423         ASSERT(I2C_TEST_START(i2c->flags) == I2C_START_R);
424
425         if (!i2c->errors)
426         {
427                 uint8_t data = i2c->vt->getc(i2c);
428                 i2c->xfer_size--;
429                 return data;
430         }
431         else
432                 return 0xFF;
433 }
434
435 /**
436  * Write the byte \a data into I2C port \a i2c.
437  * \param i2c I2C context
438  * \param data Byte to be written
439  */
440 INLINE void i2c_putc(I2c *i2c, uint8_t data)
441 {
442         ASSERT(i2c);
443         ASSERT(i2c->vt);
444         ASSERT(i2c->vt->putc);
445
446         ASSERT(i2c->xfer_size);
447
448         ASSERT(I2C_TEST_START(i2c->flags) == I2C_START_W);
449
450         if (!i2c->errors)
451         {
452                 i2c->vt->putc(i2c, data);
453                 i2c->xfer_size--;
454         }
455 }
456
457 /**
458  * Write \a count bytes to port \a i2c, reading from \a _buf.
459  * \param i2c I2C context
460  * \param _buf User buffer to read from
461  * \param count Number of bytes to write
462  */
463 INLINE void i2c_write(I2c *i2c, const void *_buf, size_t count)
464 {
465         ASSERT(i2c);
466         ASSERT(i2c->vt);
467         ASSERT(i2c->vt->write);
468
469         ASSERT(_buf);
470         ASSERT(count);
471         ASSERT(count <= i2c->xfer_size);
472
473         ASSERT(I2C_TEST_START(i2c->flags) == I2C_START_W);
474
475         if (!i2c->errors)
476                 i2c->vt->write(i2c, _buf, count);
477 }
478
479 /**
480  * Read \a count bytes into buffer \a _buf from device \a i2c.
481  * \param i2c Context structure
482  * \param _buf Buffer to fill
483  * \param count Number of bytes to read
484  */
485 INLINE void i2c_read(I2c *i2c, void *_buf, size_t count)
486 {
487         ASSERT(i2c);
488         ASSERT(i2c->vt);
489         ASSERT(i2c->vt->read);
490
491         ASSERT(_buf);
492         ASSERT(count);
493         ASSERT(count <= i2c->xfer_size);
494
495         ASSERT(I2C_TEST_START(i2c->flags) == I2C_START_R);
496
497         if (!i2c->errors)
498                 i2c->vt->read(i2c, _buf, count);
499 }
500
501 /**
502  * Return the error condition of the bus and clear errors.
503  */
504 INLINE int i2c_error(I2c *i2c)
505 {
506         ASSERT(i2c);
507         int err = i2c->errors;
508         i2c->errors = 0;
509
510         return err;
511 }
512
513 /**
514  * Initialize I2C context structure.
515  * \param i2c I2C context structure
516  * \param dev Number of device to be initialized. You can use I2C_BITBANG0
517  *            and similar if you want to activate the bitbang driver.
518  * \param clock Peripheral clock
519  */
520 #define i2c_init_3(i2c, dev, clock)   ((((dev) >= I2C_BITBANG0) | ((dev) == I2C_BITBANG_OLD)) ? \
521                                                                                 i2c_hw_bitbangInit((i2c), (dev)) : i2c_hw_init((i2c), (dev), (clock)))
522 /**@}*/
523 /**\}*/ // i2c_api
524
525 #if !CONFIG_I2C_DISABLE_OLD_API
526
527 extern I2c local_i2c_old_api;
528
529 /**
530  * Initialize I2C module (old API).
531  * \attention This function is deprecated. Use i2c_init(args...) in new code
532  */
533 INLINE void i2c_init_0(void)
534 {
535         #if CONFIG_I2C_BACKEND == I2C_BACKEND_BITBANG
536                 i2c_init_3(&local_i2c_old_api, I2C_BITBANG_OLD, CONFIG_I2C_FREQ);
537         #else
538                 i2c_init_3(&local_i2c_old_api, 0, CONFIG_I2C_FREQ);
539         #endif
540 }
541 #endif /* !CONFIG_I2C_DISABLE_OLD_API */
542
543
544
545 #endif