I2C with AT24Cxxx

Dependencies:   mbed

main.cpp

Committer:
RedBearLab
Date:
2016-01-07
Revision:
2:9551fe55f227
Parent:
0:a9d57902bf67

File content as of revision 2:9551fe55f227:


#include "mbed.h"

#define DEV_ADDR    0xA0

I2C     i2c(P0_29, P0_28);
Serial  pc(USBTX, USBRX);

/**********************************************************************
* @brief            :  Write data to AT24C512
* 
* @param[in] addr   : The address of stored
* @param[in] *pbuf  : The pointer of data
* @param[in] length : The length of data
*
* @return none
**********************************************************************/
void AT24C512_WriteBytes(uint16_t addr, uint8_t *pbuf, uint16_t length)
{
    char buf[length+2];
    buf[0] = (uint8_t)(addr>>8);
    buf[1] = (uint8_t)(addr);
    memcpy(&buf[2], pbuf, length); 
    i2c.write(DEV_ADDR, buf, length+2, false);
}
/**********************************************************************
* @brief            :  Read data from AT24C512
* 
* @param[in] addr   : The address of read in AT24C512
* @param[out] *pbuf : The pointer of buffer 
* @param[in] length : The length of data
*
* @return none
**********************************************************************/
void AT24C512_ReadBytes(uint16_t addr, uint8_t *pbuf, uint16_t length)
{
    char buf[2];
    buf[0] = (uint8_t)(addr>>8);
    buf[1] = (uint8_t)(addr);
    i2c.write(DEV_ADDR, buf, 2, false);
    
    i2c.read(DEV_ADDR, (char *)pbuf, length, false);
}


uint8_t w_buf[11]={'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd', '!'};
uint8_t r_buf[11];


int main(void)
{
    uint8_t index;
    
    pc.baud(9600);
    pc.printf("IIC Demo Start \r\n");
    
    while(1)
    {
        wait(2);
        AT24C512_WriteBytes(0, w_buf, 11);
        wait(0.5);
        AT24C512_ReadBytes(0, r_buf, 11);
        for(index=0; index<11; index++)
         pc.putc(r_buf[index]);
         
        pc.printf("\r\n");
    }
}