Raspberry Pi GPIO Library  0.3
Library allowing for control of the Raspberry Pi's GPIO pins.
All Files Functions Variables Enumerations Enumerator Macros Pages
i2c.c
Go to the documentation of this file.
1 
24 #include "i2c.h"
25 
27 static volatile uint32_t * gI2cMap = NULL;
28 
30 static int i2cByteTxTime_ns;
31 
37 {
38  int mem_fd = 0;
39  int sda;
40  int scl;
41  errStatus rtn = ERROR_DEFAULT;
42  off_t bscBase;
43 
44  if ((rtn = gpioGetI2cPins(&scl, &sda)) != OK)
45  {
46  dbgPrint(DBG_INFO, "gpioGetI2cPins() failed. %s", gpioErrToString(rtn));
47  }
48 
49  /* Find the correct BSC to use from I2C pins */
50  else if (sda == REV1_SDA && scl == REV1_SCL)
51  {
52  bscBase = BSC0_BASE;
53  }
54  else if (sda == REV2_SDA && scl == REV2_SCL)
55  {
56  bscBase = BSC1_BASE;
57  }
58  else
59  {
60  rtn = ERROR_INVALID_PIN_NUMBER;
61  }
62 
63  if (rtn != OK)
64  {
65  dbgPrint(DBG_INFO, "Return was not OK. %s", gpioErrToString(rtn));
66  }
67 
68  else if (gI2cMap != NULL)
69  {
70  dbgPrint(DBG_INFO, "gpioI2cSetup was already called.");
71  rtn = ERROR_ALREADY_INITIALISED;
72  }
73 
74  else if ((mem_fd = open("/dev/mem", O_RDWR)) < 0)
75  {
76  dbgPrint(DBG_INFO, "open() failed for /dev/mem. errno: %s.",
77  strerror(errno));
78  rtn = ERROR_EXTERNAL;
79  }
80 
81  else if ((gI2cMap = (volatile uint32_t *)mmap(NULL,
83  PROT_READ|PROT_WRITE,
84  MAP_SHARED,
85  mem_fd,
86  bscBase)) == MAP_FAILED)
87  {
88  dbgPrint(DBG_INFO, "mmap() failed. errno: %s.", strerror(errno));
89  rtn = ERROR_EXTERNAL;
90  }
91 
92  /* Close the fd, we have now mapped it */
93  else if (close(mem_fd) != OK)
94  {
95  dbgPrint(DBG_INFO, "close() failed. errno: %s.", strerror(errno));
96  rtn = ERROR_EXTERNAL;
97  }
98 
99  /* There are external Pullup resistors on the Pi. Disable the internals */
100  else if ((rtn = gpioSetPullResistor(sda, pullDisable)) != OK)
101  {
102  dbgPrint(DBG_INFO, "gpioSetPullResistor() failed for SDA. %s",
103  gpioErrToString(rtn));
104  }
105 
106  else if ((rtn = gpioSetPullResistor(scl, pullDisable)) != OK)
107  {
108  dbgPrint(DBG_INFO, "gpioSetPullResistor() failed for SCL. %s",
109  gpioErrToString(rtn));
110  }
111 
112  /* Set SDA pin to alternate function 0 for I2C */
113  else if ((rtn = gpioSetFunction(sda, alt0)) != OK)
114  {
115  dbgPrint(DBG_INFO, "gpioSetFunction() failed for SDA. %s",
116  gpioErrToString(rtn));
117  }
118 
119  /* Set SCL pin to alternate function 0 for I2C */
120  else if ((rtn = gpioSetFunction(scl, alt0)) != OK)
121  {
122  dbgPrint(DBG_INFO, "gpioSetFunction() failed for SCL. %s",
123  gpioErrToString(rtn));
124  }
125 
126  /* Default the I2C speed to 100 kHz */
127  else if ((rtn = gpioI2cSetClock(I2C_DEFAULT_FREQ_HZ)) != OK)
128  {
129  dbgPrint(DBG_INFO, "gpioI2cSetClock() failed. %s", gpioErrToString(rtn));
130  }
131 
132  else
133  {
134  /* Setup the Control Register.
135  * Enable the BSC Controller.
136  * Clear the FIFO. */
138 
139  /* Setup the Status Register
140  * Clear NACK ERR flag.
141  * Clear Clock stretch flag.
142  * Clear Done flag. */
144 
145  rtn = OK;
146  }
147 
148  return rtn;
149 }
150 
157 {
158  errStatus rtn = ERROR_DEFAULT;
159  int sda;
160  int scl;
161 
162  if (gI2cMap == NULL)
163  {
164  dbgPrint(DBG_INFO, "gI2cMap was NULL. Ensure gpioI2cSetup() was called successfully.");
165  rtn = ERROR_NOT_INITIALISED;
166  }
167 
168  else if ((rtn = gpioGetI2cPins(&scl, &sda)) != OK)
169  {
170  dbgPrint(DBG_INFO, "gpioGetI2cPins() failed. %s",
171  gpioErrToString(rtn));
172  }
173 
174  /* Set SDA pin to input */
175  else if ((rtn = gpioSetFunction(sda, input)) != OK)
176  {
177  dbgPrint(DBG_INFO, "gpioSetFunction() failed for SDA. %s",
178  gpioErrToString(rtn));
179  }
180 
181  /* Set SCL pin to input */
182  else if ((rtn = gpioSetFunction(scl, input)) != OK)
183  {
184  dbgPrint(DBG_INFO, "gpioSetFunction() failed for SCL. %s",
185  gpioErrToString(rtn));
186  }
187 
188  else
189  {
190  /* Disable the BSC Controller */
191  I2C_C &= ~BSC_I2CEN;
192 
193  /* Unmap the memory */
194  if (munmap((void *)gI2cMap, I2C_MAP_SIZE) != OK)
195  {
196  dbgPrint(DBG_INFO, "mummap() failed. errno: %s.", strerror(errno));
197  rtn = ERROR_EXTERNAL;
198  }
199 
200  else
201  {
202  gI2cMap = NULL;
203  rtn = OK;
204  }
205  }
206 
207  return rtn;
208 }
209 
210 
217 errStatus gpioI2cSet7BitSlave(uint8_t slaveAddress)
218 {
219  errStatus rtn = ERROR_DEFAULT;
220 
221  if (gI2cMap == NULL)
222  {
223  dbgPrint(DBG_INFO, "gI2cMap was NULL. Ensure gpioI2cSetup() was called successfully.");
224  rtn = ERROR_NOT_INITIALISED;
225  }
226 
227  else
228  {
229  I2C_A = slaveAddress;
230  rtn = OK;
231  }
232 
233  return rtn;
234 }
235 
236 
243 errStatus gpioI2cWriteData(const uint8_t * data, uint16_t dataLength)
244 {
245  errStatus rtn = ERROR_DEFAULT;
246  uint16_t dataIndex = 0;
247  uint16_t dataRemaining = dataLength;
248  struct timespec sleepTime;
249 
250  if (gI2cMap == NULL)
251  {
252  dbgPrint(DBG_INFO, "gI2cMap was NULL. Ensure gpioI2cSetup() was called successfully.");
253  rtn = ERROR_NOT_INITIALISED;
254  }
255 
256  else if (data == NULL)
257  {
258  dbgPrint(DBG_INFO, "data was NULL.");
259  rtn = ERROR_NULL;
260  }
261 
262  else
263  {
264  sleepTime.tv_sec = 0;
265 
266  /* Clear the FIFO */
267  I2C_C |= BSC_CLEAR;
268 
269  /* Configure Control for a write */
270  I2C_C &= ~BSC_READ;
271 
272  /* Set the Data Length register to dataLength */
273  I2C_DLEN = dataLength;
274 
275  /* Configure Control Register for a Start */
276  I2C_C |= BSC_ST;
277 
278  /* Main transmit Loop - While Not Done */
279  while (!(I2C_S & BSC_DONE))
280  {
281  while ((I2C_S & BSC_TXD) && dataRemaining)
282  {
283  I2C_FIFO = data[dataIndex];
284  dataIndex++;
285  dataRemaining--;
286  }
287 
288  /* FIFO should be full at this point. If data remaining to be added
289  * sleep for time it should take to approximately half empty FIFO */
290  if (dataRemaining)
291  {
292  sleepTime.tv_nsec = i2cByteTxTime_ns * BSC_FIFO_SIZE / 2;
293  }
294 
295  /* Otherwise all data is currently in the FIFO, sleep for how many
296  * bytes are in the FIFO to be transmitted */ /* TODO DOUBLE? */
297  else
298  {
299  sleepTime.tv_nsec = I2C_DLEN * i2cByteTxTime_ns;
300  }
301 
302  nanosleep(&sleepTime, NULL);
303  }
304 
305  /* Received a NACK */
306  if (I2C_S & BSC_ERR)
307  {
308  I2C_S |= BSC_ERR;
309  dbgPrint(DBG_INFO, "Received a NACK.");
310  rtn = ERROR_I2C_NACK;
311  }
312 
313  /* Received Clock Timeout error */
314  else if (I2C_S & BSC_CLKT)
315  {
316  I2C_S |= BSC_CLKT;
317  dbgPrint(DBG_INFO, "Received a Clock Stretch Timeout.");
318  rtn = ERROR_I2C_CLK_TIMEOUT;
319  }
320 
321  else if (dataRemaining)
322  {
323  dbgPrint(DBG_INFO, "BSC signaled done but %d data remained.", dataRemaining);
324  rtn = ERROR_I2C;
325  }
326 
327  else
328  {
329  rtn = OK;
330  }
331 
332  /* Clear the DONE flag */
333  I2C_S |= BSC_DONE;
334 
335  }
336 
337  return rtn;
338 }
339 
340 
348 errStatus gpioI2cReadData(uint8_t * buffer, uint16_t bytesToRead)
349 {
350  errStatus rtn = ERROR_DEFAULT;
351  uint16_t bufferIndex = 0;
352  uint16_t dataRemaining = bytesToRead;
353  struct timespec sleepTime;
354 
355  if (gI2cMap == NULL)
356  {
357  dbgPrint(DBG_INFO, "gI2cMap was NULL. Ensure gpioI2cSetup() was called successfully.");
358  rtn = ERROR_NOT_INITIALISED;
359  }
360 
361  else if (buffer == NULL)
362  {
363  dbgPrint(DBG_INFO, "buffer was NULL.");
364  rtn = ERROR_NULL;
365  }
366 
367  else
368  {
369  sleepTime.tv_sec = 0;
370 
371  /* Clear the FIFO */
372  I2C_C |= BSC_CLEAR;
373 
374  /* Configure Control for a write */
375  I2C_C |= BSC_READ;
376 
377  /* Set the Data Length register to dataLength */
378  I2C_DLEN = bytesToRead;
379 
380  /* Configure Control Register for a Start */
381  I2C_C |= BSC_ST;
382 
383  /* Main Receive Loop - While Transfer is not done */
384  while (!(I2C_S & BSC_DONE))
385  {
386  /* FIFO Contains Data. Read until empty */
387  while ((I2C_S & BSC_RXD) && dataRemaining)
388  {
389  buffer[bufferIndex] = I2C_FIFO;
390  bufferIndex++;
391  dataRemaining--;
392  }
393 
394  /* FIFO should be empty at this point. If more than one full FIFO
395  * remains to be read sleep for time to approximately half fill
396  * FIFO */
397  if (dataRemaining > BSC_FIFO_SIZE)
398  {
399  sleepTime.tv_nsec = i2cByteTxTime_ns * BSC_FIFO_SIZE / 2;
400  }
401 
402  /* Otherwise, sleep for the number of bytes to be received */ /*TODO DOUBLE ?*/
403  else
404  {
405  sleepTime.tv_nsec = I2C_DLEN * i2cByteTxTime_ns;
406  }
407 
408  /* Sleep for approximate time to receive half the FIFO */
409  sleepTime.tv_nsec = i2cByteTxTime_ns * (I2C_DLEN > BSC_FIFO_SIZE ?
410  BSC_FIFO_SIZE/2 : I2C_DLEN/2);
411 
412  nanosleep(&sleepTime, NULL);
413  }
414 
415  /* FIFO Contains Data. Read until empty */
416  while ((I2C_S & BSC_RXD) && dataRemaining)
417  {
418  buffer[bufferIndex] = I2C_FIFO;
419  bufferIndex++;
420  dataRemaining--;
421  }
422 
423  /* Received a NACK */
424  if (I2C_S & BSC_ERR)
425  {
426  I2C_S |= BSC_ERR;
427  dbgPrint(DBG_INFO, "Received a NACK");
428  rtn = ERROR_I2C_NACK;
429  }
430 
431  /* Received Clock Timeout error. */
432  else if (I2C_S & BSC_CLKT)
433  {
434  I2C_S |= BSC_CLKT;
435  dbgPrint(DBG_INFO, "Received a Clock Stretch Timeout");
436  rtn = ERROR_I2C_CLK_TIMEOUT;
437  }
438 
439  else if (dataRemaining)
440  {
441  dbgPrint(DBG_INFO, "BSC signaled done but data remained.");
442  rtn = ERROR_I2C;
443  }
444 
445  else
446  {
447  rtn = OK;
448  }
449 
450  /* Clear the DONE flag */
451  I2C_S |= BSC_DONE;
452 
453  }
454 
455  return rtn;
456 }
457 
458 
466 {
467  errStatus rtn = ERROR_DEFAULT;
468 
469  /*
470  * CDIV = 0 then diviser actually 32768
471  * Max freq 400,000*/
472  if (frequency < I2C_CLOCK_FREQ_MIN || frequency > I2C_CLOCK_FREQ_MAX)
473  {
474  rtn = ERROR_RANGE;
475  }
476 
477  else
478  {
479  /*Note CDIV is always rounded down to an even number */
480  I2C_DIV = CORE_CLK_HZ / frequency;
481  i2cByteTxTime_ns = (int)(1.0 / ((float)frequency / NSEC_IN_SEC)
482  * CLOCKS_PER_BYTE);
483 
484  rtn = OK;
485  }
486 
487 
488  return rtn;
489 
490 }
#define CORE_CLK_HZ
Speed of the core clock core_clk.
Definition: rpiGpio.h:31
static int i2cByteTxTime_ns
The time it takes ideally transmit 1 byte with current I2C clock.
Definition: i2c.c:30
#define I2C_DLEN
BSC_DLEN register.
Definition: i2c.h:61
#define REV2_SCL
The BCM2835 pin number of SCL on rev2 Raspberry Pi.
Definition: rpiGpio.h:140
#define REV2_SDA
The BCM2835 pin number of SDA on rev2 Raspberry Pi.
Definition: rpiGpio.h:138
errStatus
The enum of possible errors returned from gpio functions. Errors themselves are defined in the macro ...
Definition: rpiGpio.h:63
#define BSC_DONE
Definition: bcm2835_gpio.h:206
#define BSC_READ
Definition: bcm2835_gpio.h:193
#define BSC1_BASE
Definition: bcm2835_gpio.h:168
#define BSC_ST
Definition: bcm2835_gpio.h:191
#define I2C_MAP_SIZE
The size the I2C mapping is required to be.
Definition: i2c.h:43
static volatile uint32_t * gI2cMap
Pointer which will be mmap&#39;d to the I2C memory in /dev/mem.
Definition: i2c.c:27
#define BSC_RXD
Definition: bcm2835_gpio.h:202
#define BSC_CLEAR
Definition: bcm2835_gpio.h:192
#define I2C_A
BSC_A register.
Definition: i2c.h:59
errStatus gpioI2cSet7BitSlave(uint8_t slaveAddress)
Sets the 7-bit slave address to communicate with.
Definition: i2c.c:217
#define BSC_CLKT
Definition: bcm2835_gpio.h:198
#define I2C_S
BSC_S register.
Definition: i2c.h:63
#define I2C_CLOCK_FREQ_MAX
Maximum I2C frequency (Hertz)
Definition: rpiGpio.h:59
#define REV1_SDA
The BCM2835 pin number of SDA on rev1 Raspberry Pi.
Definition: rpiGpio.h:134
const char * gpioErrToString(errStatus error)
Debug function which converts an error from errStatus to a string.
Definition: gpio.c:405
#define BSC_FIFO_SIZE
Definition: bcm2835_gpio.h:209
#define BSC0_BASE
Definition: bcm2835_gpio.h:167
#define NSEC_IN_SEC
nano seconds in a second
Definition: i2c.h:49
#define I2C_DIV
BSC_DIV register.
Definition: i2c.h:57
#define I2C_C
BSC_C register.
Definition: i2c.h:55
errStatus gpioI2cCleanup(void)
Disables the I2C controller and unmaps the memory used for the i2c functionality. This function shoul...
Definition: i2c.c:156
#define BSC_ERR
Definition: bcm2835_gpio.h:199
Definition: rpiGpio.h:88
errStatus gpioI2cSetClock(int frequency)
Sets the I2C Clock Frequency.
Definition: i2c.c:465
#define I2C_FIFO
BSC_FIFO register.
Definition: i2c.h:65
errStatus gpioI2cSetup(void)
Initial setup of I2C functionality.
Definition: i2c.c:36
errStatus gpioSetPullResistor(int gpioNumber, eResistor resistorOption)
Allows configuration of the internal resistor at a GPIO pin.
Definition: gpio.c:302
#define CLOCKS_PER_BYTE
Clock pulses per I2C byte - 8 bits + ACK.
Definition: i2c.h:52
int dbgPrint(FILE *stream, const char *file, int line, const char *format,...)
Debug function wrapper for fprintf().
Definition: gpio.c:439
#define DBG_INFO
Macro which covers the first three arguments of dbgPrint.
Definition: rpiGpio.h:118
#define BSC_TXD
Definition: bcm2835_gpio.h:203
errStatus gpioI2cReadData(uint8_t *buffer, uint16_t bytesToRead)
Read a number of bytes from I2C. The slave address should have been previously set with gpioI2cSet7Bi...
Definition: i2c.c:348
errStatus gpioI2cWriteData(const uint8_t *data, uint16_t dataLength)
Writes data to the address previously specified by gpioI2cSet7BitSlave().
Definition: i2c.c:243
Definition: rpiGpio.h:86
errStatus gpioGetI2cPins(int *gpioNumberScl, int *gpioNumberSda)
Get the correct I2C pins.
Definition: gpio.c:356
#define I2C_DEFAULT_FREQ_HZ
Default I2C clock frequency (Hertz)
Definition: i2c.h:46
errStatus gpioSetFunction(int gpioNumber, eFunction function)
Sets the functionality of the desired pin.
Definition: gpio.c:164
#define REV1_SCL
The BCM2835 pin number of SCL on rev1 Raspberry Pi.
Definition: rpiGpio.h:136
Contains defines for i2c.c.
#define BSC_I2CEN
Definition: bcm2835_gpio.h:187