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.

68 lines
1.9 KiB

  1. /* gc_n64_usb : Gamecube or N64 controller to USB adapter firmware
  2. Copyright (C) 2007-2016 Raphael Assenat <raph@raphnet.net>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include <avr/eeprom.h>
  15. #include <util/crc16.h>
  16. #include <stdint.h>
  17. #include <string.h>
  18. #include "eeprom.h"
  19. static uint16_t calc_geeprom_data_crc(void)
  20. {
  21. uint16_t crc = 0x0000;
  22. int i;
  23. /* Update the CRC */
  24. for (i=0; i<EEPROM_USED_SIZE_NOCRC; i++) {
  25. crc = _crc_xmodem_update(crc, ((uint8_t*)&g_eeprom_data)[i]);
  26. }
  27. return crc;
  28. }
  29. void eeprom_commit(void)
  30. {
  31. g_eeprom_data.crc16 = calc_geeprom_data_crc();
  32. /* Sync eeprom content */
  33. eeprom_update_block(&g_eeprom_data, EEPROM_BASE_PTR, EEPROM_USED_SIZE);
  34. }
  35. static char isCrcValid()
  36. {
  37. return g_eeprom_data.crc16 == calc_geeprom_data_crc();
  38. }
  39. // return 1 if eeprom was blank
  40. void eeprom_init(void)
  41. {
  42. eeprom_read_block(&g_eeprom_data, EEPROM_BASE_PTR, EEPROM_USED_SIZE);
  43. /* Detect new or corrupted content. Program default values if required. */
  44. if ((g_eeprom_data.magic != EEPROM_MAGIC) || !isCrcValid())
  45. {
  46. memset(&g_eeprom_data, 0, EEPROM_USED_SIZE);
  47. g_eeprom_data.magic = EEPROM_MAGIC;
  48. // Call application code to set application defaults
  49. eeprom_app_write_defaults();
  50. // Write the now valid content to the EEPROM at once.
  51. eeprom_commit();
  52. }
  53. eeprom_app_ready();
  54. }