rgb16mpm/eeprom.c

98 lines
3.5 KiB
C
Raw Permalink Normal View History

2012-03-02 17:35:35 +01:00
/***************************************************************************
* nvram parameter read/write *
* *
* Copyright (C) 2011 - 2012 by Olaf Rempel *
* razzor AT kopf MINUS tisch DOT de *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; version 2 of the License, *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <avr/eeprom.h>
#include <util/crc16.h>
#include "rgb16mpm.h"
static uint16_t nvram_write_pos;
struct _nvdata nvram_data;
static struct _nvdata nvram_eeprom EEMEM = NVRAM_DEFAULTS;
static struct _nvdata nvram_defaults PROGMEM = NVRAM_DEFAULTS;
/* store nvram data to eeprom */
ISR(EE_RDY_vect) {
EECR &= ~(1<<EERIE);
sei();
if (nvram_write_pos < sizeof(struct _nvdata)) {
/* not a function: shorter IRQ entry (fast IRQ re-enable) */
EEARL = (nvram_write_pos & 0xFF);
EEARH = (nvram_write_pos >> 8) & 0xFF;
EEDR = ((uint8_t *)&nvram_data)[nvram_write_pos++];
cli();
EECR |= (1<<EEMWE);
EECR |= (1<<EEWE);
sei();
EECR |= (1<<EERIE);
}
}
/* create crc and store nvram data to eeprom */
void eeprom_write(void)
{
uint8_t i;
uint16_t crc = 0x0000;
uint8_t *tmp = (uint8_t *)&nvram_data;
nvram_data.nvram_size = sizeof(struct _nvdata);
for (i = 0; i < sizeof(struct _nvdata) -2; i++) {
crc = _crc_ccitt_update(crc, *tmp++);
}
nvram_data.nvram_crc = crc;
nvram_write_pos = 0;
EEARL = (nvram_write_pos & 0xFF);
EEARH = (nvram_write_pos >> 8) & 0xFF;
EEDR = ((uint8_t *)&nvram_data)[nvram_write_pos++];
cli();
EECR |= (1<<EEMWE);
EECR |= (1<<EEWE);
sei();
EECR |= (1<<EERIE);
}
/* read nvram from eeprom and check crc */
2012-03-11 15:49:41 +01:00
void eeprom_read(uint8_t defaults)
2012-03-02 17:35:35 +01:00
{
uint8_t i;
uint16_t crc = 0x0000;
uint8_t *tmp = (uint8_t *)&nvram_data;
eeprom_read_block(&nvram_data, &nvram_eeprom, sizeof(struct _nvdata));
for (i = 0; i < sizeof(struct _nvdata); i++) {
crc = _crc_ccitt_update(crc, *tmp++);
}
/* if nvram content is invalid, overwrite with defaults */
2012-03-11 15:49:41 +01:00
if ((nvram_data.nvram_size != sizeof(struct _nvdata)) || (crc != 0x0000) || defaults) {
2012-03-02 17:35:35 +01:00
memcpy_P(&nvram_data, &nvram_defaults, sizeof(struct _nvdata));
eeprom_write();
}
}