hal_flash.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #include "hal_flash.h"
  2. #include "stm32f1xx_hal_flash_ex.h"
  3. #include "stm32f1xx_hal_flash.h"
  4. #include "stdint.h"
  5. #include "string.h"
  6. #include "sys_log.h"
  7. static uint8_t _flash_write_word(uint32_t address, uint32_t value);
  8. static uint8_t _flash_sector_erase(uint32_t sector);
  9. uint8_t HAL_FlashInit(void *args)
  10. {
  11. return 0;
  12. }
  13. uint8_t HAL_FlashWriteBytes(uint32_t addr, uint8_t *buf, uint16_t size)
  14. {
  15. int w_size = size >> 2;
  16. int r_w_size = size - (w_size << 2);
  17. int i = 0, offset = 0, offset_w;
  18. int w_data;
  19. for (; i < w_size; i++)
  20. {
  21. w_data = *(int *)(buf + offset);
  22. if (_flash_write_word(addr + offset, w_data))
  23. {
  24. return 1;
  25. }
  26. offset += 4;
  27. }
  28. if (r_w_size)
  29. {
  30. w_data = 0;
  31. offset_w = 0;
  32. for (i = 0; i < r_w_size; i++)
  33. {
  34. w_data = (w_data) | (*(buf + offset + i) << offset_w);
  35. offset_w += 8;
  36. }
  37. if (_flash_write_word(addr + offset, w_data))
  38. {
  39. return 1;
  40. }
  41. }
  42. return 0;
  43. }
  44. uint8_t HAL_FlashReadBytes(uint32_t addr, uint8_t *buf, uint16_t size)
  45. {
  46. memcpy(buf, (const uint8_t *)addr, size);
  47. return 0;
  48. }
  49. uint8_t HAL_FlashSectorErase(uint32_t addr)
  50. {
  51. return (_flash_sector_erase(addr));
  52. }
  53. static uint8_t _flash_sector_erase(uint32_t sector)
  54. {
  55. FLASH_EraseInitTypeDef pEraseInit;
  56. HAL_StatusTypeDef status = HAL_OK;
  57. uint32_t PageError = 0;
  58. int i;
  59. pEraseInit.TypeErase = FLASH_TYPEERASE_PAGES;
  60. pEraseInit.Banks = FLASH_BANK_1;
  61. pEraseInit.PageAddress = sector;
  62. pEraseInit.NbPages = 1;
  63. HAL_FLASH_Unlock();
  64. for (i = 0; i < 3; i++)
  65. {
  66. status = HAL_FLASHEx_Erase(&pEraseInit, &PageError);
  67. if (HAL_OK == status)
  68. {
  69. break;
  70. }
  71. }
  72. HAL_FLASH_Lock();
  73. if (status != HAL_OK)
  74. {
  75. /* Error occurred while page erase */
  76. return FLASHIF_ERASEKO;
  77. }
  78. return FLASHIF_OK;
  79. }
  80. static uint8_t _flash_write_word(uint32_t address, uint32_t value)
  81. {
  82. HAL_StatusTypeDef status = HAL_OK;
  83. HAL_FLASH_Unlock();
  84. status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, address, value);
  85. HAL_FLASH_Lock();
  86. if (status != HAL_OK)
  87. {
  88. /* Error occurred while page erase */
  89. return FLASHIF_WRITING_ERROR;
  90. }
  91. return FLASHIF_OK;
  92. }