You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

115 lines
2.1 KiB

#include "stm32f4xx.h"
#include "eeprom.h"
#include "i2c.h"
#include "utils.h"
static i2c_t _i2c;
static int alloced = 0;
static uint8_t _address;
static int _is_16bits = 0;
#define MEM_DEVICE_WRITE_ADDR (_address << 1)
#define MEM_DEVICE_READ_ADDR ((_address << 1) | 0x1)
int at24_i2c_init(uint32_t scl, uint32_t sda, uint8_t addr, int bits)
{
_i2c = i2c_new(scl, sda, 100000); /* 100K */
alloced = 1;
_address = addr;
_is_16bits = bits;
return 0;
}
int at24_i2c_init_ex(i2c_t i2c, uint8_t addr, int bits)
{
_i2c = i2c;
alloced = 0;
_address = addr;
_is_16bits = bits;
return 0;
}
void at24_i2c_close(void)
{
if (_i2c) {
if (alloced)
i2c_free(_i2c);
alloced = 0;
_i2c = 0;
_address = 0;
}
}
int at24_i2c_write(uint16_t addr, uint8_t data)
{
if (_i2c == 0)
return -1;
if (i2c_start(_i2c)) {
return -2;
}
i2c_send_byte(_i2c, MEM_DEVICE_WRITE_ADDR);
if (i2c_wait_ack(_i2c)) { /* NACK */
i2c_stop(_i2c);
return -3;
}
if (_is_16bits) {
/* two bytes address */
i2c_send_byte(_i2c, (addr >> 8) & 0xff);
i2c_wait_ack(_i2c);
}
i2c_send_byte(_i2c, addr & 0xff);
i2c_wait_ack(_i2c);
/* one byte data */
i2c_send_byte(_i2c, data);
i2c_wait_ack(_i2c);
i2c_stop(_i2c);
delay_microseconds(5000); /* wait 5ms, until eeprom write completed */
return 0;
}
uint8_t at24_i2c_read(uint16_t addr)
{
uint8_t data = 0xff;
if (_i2c == 0) {
return data;
}
if (i2c_start(_i2c)) {
return 0xff;
}
i2c_send_byte(_i2c, MEM_DEVICE_WRITE_ADDR);
if (i2c_wait_ack(_i2c)) { /* NACK */
i2c_stop(_i2c);
return 0xff;
}
if (_is_16bits) {
/* two bytes address */
i2c_send_byte(_i2c, (addr >> 8) & 0xff);
i2c_wait_ack(_i2c);
}
i2c_send_byte(_i2c, (addr & 0xff));
i2c_wait_ack(_i2c);
i2c_start(_i2c);
i2c_send_byte(_i2c, MEM_DEVICE_READ_ADDR);
i2c_wait_ack(_i2c);
data = i2c_recv_byte(_i2c);
i2c_nack(_i2c);
i2c_stop(_i2c);
return data;
}