/*
 * eeprom.c
 *
 *  Created on: Jun 7, 2017
 *      Author: wn
 */

#include "eeprom.h"
#include "stm32f1xx_hal.h"


#define HIGH GPIO_PIN_SET
#define LOW GPIO_PIN_RESET

extern SPI_HandleTypeDef hspi1;


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;


static void __EEPROM_CS(GPIO_PinState v) {
  HAL_GPIO_WritePin(EEPROM_CS_GPIO_Port, EEPROM_CS_Pin, v);
}

static void __HAL_SPI_Transmit_One_ByValue(SPI_HandleTypeDef *hspi, uint8_t c) {
  HAL_SPI_Transmit(hspi, &c, 1, 0);
}


void eepromWrite(uint16_t addr, uint8_t *buf, uint8_t len) {
  __EEPROM_CS(LOW);

  __HAL_SPI_Transmit_One_ByValue(&hspi1, EEPROM_WREN);
  __HAL_SPI_Transmit_One_ByValue(&hspi1, EEPROM_WRITE);
  HAL_SPI_Transmit(&hspi1, (uint8_t*)&addr, 2, 0);
  HAL_SPI_Transmit(&hspi1, buf, len, 0);

  __EEPROM_CS(HIGH);
}

void eepromRead(uint16_t addr, uint8_t *buf, uint8_t len) {
  __EEPROM_CS(LOW);

  __HAL_SPI_Transmit_One_ByValue(&hspi1, EEPROM_READ);
  HAL_SPI_Transmit(&hspi1, (uint8_t*)&addr, 2, 0);
  HAL_SPI_Receive(&hspi1, buf, len, 0);

  __EEPROM_CS(HIGH);

}
