]> begriffs open source - cmsis/blob - CMSIS/DoxyGen/Driver/src/I2C_Demo.c
Driver: Updated demo code for Flash Driver usage.
[cmsis] / CMSIS / DoxyGen / Driver / src / I2C_Demo.c
1 #include "Driver_I2C.h"
2 #include "cmsis_os.h"                   // ARM::CMSIS:RTOS:Keil RTX
3 #include <string.h>
4  
5 /* I2C Driver */
6 extern ARM_DRIVER_I2C Driver_I2C0;
7 static ARM_DRIVER_I2C * I2Cdrv = &Driver_I2C0;
8  
9  
10 #ifndef EEPROM_I2C_PORT
11 #define EEPROM_I2C_PORT       0         /* I2C Port number                    */
12 #endif
13  
14 #define EEPROM_I2C_ADDR       0x51      /* 24LC128 EEPROM I2C address         */
15  
16 #define EEPROM_MAX_ADDR       16384     /* Max memory locations available     */
17 #define EEPROM_MAX_WRITE      16        /* Max bytes to write in one step     */
18  
19 #define A_WR                  0         /* Master will write to the I2C       */
20 #define A_RD                  1         /* Master will read from the I2C      */
21  
22 static uint8_t DeviceAddr;
23 static uint8_t wr_buf[EEPROM_MAX_WRITE + 2];
24  
25 int32_t EEPROM_WriteBuf (uint16_t addr, const uint8_t *buf, uint32_t len) {
26  
27   wr_buf[0] = (uint8_t)(addr >> 8);
28   wr_buf[1] = (uint8_t)(addr & 0xFF);
29  
30   memcpy (&wr_buf[2], &buf[0], len);
31  
32   I2Cdrv->MasterTransmit (DeviceAddr, wr_buf, len + 2, false);
33   while (I2Cdrv->GetStatus().busy);
34   if (I2Cdrv->GetDataCount () != (len + 2)) return -1;
35   /* Acknowledge polling */
36  
37   do {
38     I2Cdrv->MasterReceive (DeviceAddr, &wr_buf[0], 1, false);
39     while (I2Cdrv->GetStatus().busy);
40   } while (I2Cdrv->GetDataCount () < 0);
41  
42   return 0;
43 }
44  
45 int32_t EEPROM_ReadBuf (uint16_t addr, uint8_t *buf, uint32_t len) {
46   uint8_t a[2];
47  
48   a[0] = (uint8_t)(addr >> 8);
49   a[1] = (uint8_t)(addr & 0xFF);
50  
51   I2Cdrv->MasterTransmit (DeviceAddr, a, 2, true);
52   while (I2Cdrv->GetStatus().busy);
53   I2Cdrv->MasterReceive (DeviceAddr, buf, len, false);
54   while (I2Cdrv->GetStatus().busy);
55   if (I2Cdrv->GetDataCount () != len) return -1;
56  
57   return 0;
58 }
59  
60 int32_t EEPROM_Initialize (void) {
61   uint8_t val;
62  
63   I2Cdrv->Initialize   (NULL);
64   I2Cdrv->PowerControl (ARM_POWER_FULL);
65   I2Cdrv->Control      (ARM_I2C_BUS_SPEED, ARM_I2C_BUS_SPEED_FAST);
66   I2Cdrv->Control      (ARM_I2C_BUS_CLEAR, 0);
67  
68   /* Init 24LC128 EEPROM device */
69   DeviceAddr = EEPROM_I2C_ADDR;
70  
71   /* Read min and max address */
72   if (EEPROM_ReadBuf (0x00, &val, 1) == 0) {
73     return (EEPROM_ReadBuf (EEPROM_MAX_ADDR-1, &val, 1));
74   }
75   return -1;
76 }
77   
78 uint32_t EEPROM_GetSize (void) {
79   return EEPROM_MAX_ADDR;
80 }