summaryrefslogtreecommitdiff
path: root/src/br24t_eeprom_driver.c
blob: 53165d372b034e9dd0e3db7b7caab47d8ca2c883 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <stdio.h>
#include "i2c.h"
#include "br24t_eeprom_driver.h"

#define EEPROM_ADDR       0x57
#define EEPROM_PAGE_SIZE  64

//for burning eeprom
#define MAGIC_SYN         0xdeadbeef
#define MAGIC_ACK         0xf00dd00d

#define PAGE_WRITE_OK                 0x00
#define PAGE_WRITE_CORRUPTED          0x01
#define PAGE_WRITE_UNKNOWN_ERROR      0xff

//we need another function cause it's got a 16 bit register address

#ifdef FLASH_EEPROM
void flash_eeprom() {
  uint16_t data_len;
  uint32_t syn = 0;
  uint8_t on_byte;
  uint8_t eeprom_buffer_out[EEPROM_PAGE_SIZE]; 
  uint8_t eeprom_buffer_in[EEPROM_PAGE_SIZE];

  while(syn != MAGIC_SYN) fread(&syn, 4, 1, stdin); //not sure we _really_ need to do this?
  
  //this feels ugly
  syn = MAGIC_ACK;
  fwrite(&syn, 4, 1, stdout);
  
  //get amount of data we'll be using
  data_len = uart_recvbyte();
  data_len |= (uart_recvbyte() >> 8);

  for(int page = 0; page < (data_len / EEPROM_PAGE_SIZE); data_len -= EEPROM_PAGE_SIZE) {

    fread(eeprom_buffer_out, EEPROM_PAGE_SIZE, 1, stdin);

    i2c_start(EEPROM_I2C_ADDR, I2C_READ);
    i2c_send((uint8_t)(page * EEPROM_PAGE_SIZE) & 0xff);
    i2c_send((uint8_t)(page * EEPROM_PAGE_SIZE) >> 8);
    for(on_byte = 0; on_byte < EEPROM_PAGE_SIZE; on_byte++) 
      i2c_send(eeprom_buffer_out[on_byte]); 
    i2c_stop();

    //verify
    eeprom_buffer_in[0] = EEPROM_READBYTE(page * EEPROM_PAGE_SIZE);
    //eeprom_buffer_in[0] = i2c_read_reg_addr16(EEPROM_I2C_ADDR, page * EEPROM_PAGE_SIZE);
    i2c_start(EEPROM_I2C_ADDR, I2C_READ);
    for(on_byte = 1; on_byte < EEPROM_PAGE_SIZE; on_byte++)
      eeprom_buffer_in[on_byte] = i2c_recv();
    i2c_stop();

    if(memcmp(eeprom_buffer_in, eeprom_buffer_out, EEPROM_PAGE_SIZE)) {
      fputc(PAGE_WRITE_CORRUPTED, stdout);
      error();
    }
    fputc(PAGE_WRITE_OK, stdout);
  }
}
#endif