Александр Селифонов
/
Nucleo_i2c_master
11
main.cpp
- Committer:
- turumputum
- Date:
- 2018-08-20
- Revision:
- 0:51d7f8d33957
File content as of revision 0:51d7f8d33957:
#include "mbed.h" int address = 0xA0; DigitalOut VCC(PB_5); DigitalOut GND(PB_13); I2C i2c(PB_4, PA_8); DigitalOut myled(LED1); Serial pc(SERIAL_TX, SERIAL_RX); void writeEEPROM(int address, unsigned int eeaddress, char *data, int size); void readEEPROM(int address, unsigned int eeaddress, char *data, int size); // this function has 63 bytes write limit void writeEEPROM(int address, unsigned int eeaddress, char *data, int size) { char i2cBuffer[size + 2]; i2cBuffer[0] = (unsigned char)(eeaddress >> 8); // MSB i2cBuffer[1] = (unsigned char)(eeaddress & 0xFF); // LSB for (int i = 0; i < size; i++) { i2cBuffer[i + 2] = data[i]; } int result = i2c.write(address, i2cBuffer, size + 2, false); wait_ms(6); } // this function has no read limit void readEEPROM(int address, unsigned int eeaddress, char *data, int size) { char i2cBuffer[2]; i2cBuffer[0] = (unsigned char)(eeaddress >> 8); // MSB i2cBuffer[1] = (unsigned char)(eeaddress & 0xFF); // LSB // Reset eeprom pointer address int result = i2c.write(address, i2cBuffer, 2, false); wait_ms(6); // Read eeprom i2c.read(address, data, size); wait_ms(6); } int main() { VCC=1; GND=0; pc.printf("I2C EEPROM started...\n"); int pointerAdddress = 0; wait_ms(3000); // write some data on eeprom char writeData[] = {"1234567890"}; // the text length must be below 64 bytes char writeDataLen = 0; do {writeDataLen++;} while (writeData[writeDataLen]); // calculate the text length writeEEPROM(address, pointerAdddress, writeData, writeDataLen); pc.printf("Data written: %s\n", writeData); // read the data back char data_read[writeDataLen]; readEEPROM(address, pointerAdddress, data_read, writeDataLen); pc.printf("Data read: %s\n", data_read); }