72 lines
1.4 KiB
C
Raw Normal View History

2020-11-05 13:05:19 +01:00
#include <main.h>
#include <spi.h>
#include <eeprom.h>
// #include <stm32f1xx_hal.h>
2020-11-04 23:46:55 +01:00
#include <string.h>
#define HIGH GPIO_PIN_SET
#define LOW GPIO_PIN_RESET
const uint8_t EEPROM_READ = 0x03;
const uint8_t EEPROM_WRITE = 0x02;
const uint8_t EEPROM_WRDI = 0x04;
const uint8_t EEPROM_WREN = 0x06;
const uint8_t EEPROM_RDSR = 0x05;
const uint8_t EEPROM_WRSR = 0x01;
const uint32_t STORAGE_MAGIC = 0xaffe000b;
2020-11-05 13:05:19 +01:00
typedef union {
2020-11-04 23:46:55 +01:00
struct {
2020-11-05 13:05:19 +01:00
uint8_t cmd;
uint16_t addr;
uint8_t data[32];
} s;
uint8_t b[35];
} t_spiMsg;
2020-11-04 23:46:55 +01:00
2020-11-05 13:05:19 +01:00
inline static void __EEPROM_CS(GPIO_PinState v) {
HAL_GPIO_WritePin(EEPROM_CS_GPIO_Port, EEPROM_CS_Pin, v);
2020-11-04 23:46:55 +01:00
}
2020-11-05 13:05:19 +01:00
void eepromWrite(uint16_t addr, uint8_t *buf, uint8_t len) {
t_spiMsg msg = {
.s.cmd = EEPROM_WRITE,
.s.addr = addr
2020-11-04 23:46:55 +01:00
};
2020-11-05 13:05:19 +01:00
memcpy(msg.s.data, buf, len);
2020-11-04 23:46:55 +01:00
2020-11-05 13:05:19 +01:00
uint8_t writeEnable = EEPROM_WREN;
2020-11-04 23:46:55 +01:00
__EEPROM_CS(LOW);
2020-11-05 13:05:19 +01:00
HAL_SPI_Transmit(&eepromSpi, &writeEnable, 1, HAL_MAX_DELAY);
2020-11-04 23:46:55 +01:00
__EEPROM_CS(HIGH);
__EEPROM_CS(LOW);
2020-11-05 13:05:19 +01:00
HAL_SPI_Transmit(&eepromSpi, msg.b, ((uint16_t)(len+3+1)), HAL_MAX_DELAY);
2020-11-04 23:46:55 +01:00
__EEPROM_CS(HIGH);
}
void eepromRead(uint16_t addr, uint8_t *buf, uint8_t len) {
2020-11-05 13:05:19 +01:00
t_spiMsg txMsg = {
.s.cmd = EEPROM_READ,
.s.addr = addr
};
2020-11-04 23:46:55 +01:00
2020-11-05 13:05:19 +01:00
t_spiMsg rxMsg;
2020-11-04 23:46:55 +01:00
__EEPROM_CS(LOW);
2020-11-05 13:05:19 +01:00
HAL_SPI_TransmitReceive(&eepromSpi, txMsg.b, rxMsg.b, ((uint16_t)(len+3+1)), HAL_MAX_DELAY);
2020-11-04 23:46:55 +01:00
__EEPROM_CS(HIGH);
2020-11-05 13:05:19 +01:00
memcpy(buf, rxMsg.s.data, len);
2020-11-04 23:46:55 +01:00
}