parameters.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. #include "parameters.h"
  2. #include "global_def.h"
  3. #include "usart.h"
  4. #include "stm32l4xx_hal_flash.h"
  5. #include "stm32l4xx_hal_flash_ex.h"
  6. #include <string.h>
  7. #include <stdio.h>
  8. static uint64_t reflectionBuff[(sizeof(Config_type)>>3)+1];
  9. Config_type *config = (Config_type *)reflectionBuff;
  10. static uint32_t GetPage(uint32_t Addr)
  11. {
  12. uint32_t page = 0;
  13. if (Addr < (EFLASH_BASE + EFLASH_BANK_SIZE))
  14. {
  15. /* Bank 1 */
  16. page = (Addr - EFLASH_BASE) / EFLASH_PAGE_SIZE;
  17. }
  18. else
  19. {
  20. /* Bank 2 */
  21. page = (Addr - (EFLASH_BASE + EFLASH_BANK_SIZE)) / EFLASH_PAGE_SIZE;
  22. }
  23. return page;
  24. }
  25. /**
  26. * @brief Gets the bank of a given address
  27. * @param Addr: Address of the FLASH Memory
  28. * @retval The bank of a given address
  29. */
  30. static uint32_t GetBank(uint32_t Addr)
  31. {
  32. return FLASH_BANK_1;
  33. }
  34. static void Factory_reset(void)
  35. {
  36. config->magic = CONFIG_MAGIC;
  37. config->addr = DEFAULT_ADDR;
  38. config->br_index = BaudRate_9600;
  39. //config->App2Size = 0;
  40. //config->App2Crc = 0;
  41. //config->IapFlag = 0;
  42. }
  43. int Config_Init(void)
  44. {
  45. //EFLASH_StatusType ret = EFLASH_STATUS_SUCCESS;
  46. memcpy(reflectionBuff, (void *)CONFIG_ADDRESS, sizeof(Config_type));
  47. // for(int i=0; i<(sizeof(Config_type)>>3)+1; i++){
  48. // reflectionBuff[i] = *(__IO uint64_t *)(CONFIG_ADDRESS+i*8);
  49. // }
  50. if (config->magic != CONFIG_MAGIC)
  51. {/* initiliaze config */
  52. memset(reflectionBuff, 0xFF, sizeof(Config_type));
  53. //config->magic = CONFIG_MAGIC;
  54. Factory_reset();
  55. //
  56. config->IapFlag = Startup_Normal;
  57. config->hw_version = 0x0000;
  58. config->devicetype = 0x0000;
  59. config->deviceid = 0x00;
  60. SaveConfig();
  61. }
  62. printf("config->IapFlag: %x \r\n", config->IapFlag);
  63. return 0;
  64. }
  65. int SaveConfig(void)
  66. {
  67. HAL_StatusTypeDef ret = HAL_OK;
  68. FLASH_EraseInitTypeDef pEraseInit;
  69. uint32_t pageError = 0;
  70. HAL_FLASH_Unlock();
  71. pEraseInit.TypeErase = FLASH_TYPEERASE_PAGES;
  72. pEraseInit.Page = GetPage(CONFIG_ADDRESS);
  73. pEraseInit.Banks = GetBank(CONFIG_ADDRESS);
  74. pEraseInit.NbPages = 1;
  75. ret = HAL_FLASHEx_Erase(&pEraseInit, &pageError);
  76. //if (ret != HAL_OK) return -1;
  77. for(int i=0; i<((sizeof(Config_type)>>3)+1); i++){
  78. ret = HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, CONFIG_ADDRESS+i*8, reflectionBuff[i]);
  79. }
  80. HAL_FLASH_Lock();
  81. return ret;
  82. }
  83. int ResetConfig(void)
  84. {
  85. Factory_reset();
  86. //SaveConfig();
  87. return 0;
  88. }