utils.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "utils.h"
  2. /* Defines */
  3. #define WRITE_KEY1 0x45670123
  4. #define WRITE_KEY2 0xCDEF89AB
  5. /* Functions */
  6. flash_result_t Flash_Write(uint64_t * data) {
  7. nt64_t val;
  8. flash_result_t res = Flash_Ok;
  9. uint32_t address = FLASH_PAGE_START;
  10. val.u64 = *data;
  11. // search first free cell
  12. while ((address < FLASH_PAGE_END) && ((*(__IO uint32_t*)address) != 0xffffffff)) {
  13. address += 8;
  14. }
  15. /* Authorize the FLASH Registers access */
  16. FLASH->KEYR = WRITE_KEY1;
  17. FLASH->KEYR = WRITE_KEY2;
  18. /* verify Flash is unlock */
  19. if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0x00U) {
  20. res = Flash_Error;
  21. } else {
  22. if (address > FLASH_PAGE_END) {
  23. // no space, format flash page
  24. uint32_t tmp;
  25. /* Get configuration register, then clear page number */
  26. tmp = (FLASH->CR & ~FLASH_CR_PNB);
  27. /* Set page number, Page Erase bit & Start bit */
  28. FLASH->CR = (tmp | (FLASH_CR_STRT | (FLASH_PAGE_NMB << FLASH_CR_PNB_Pos) | FLASH_CR_PER));
  29. /* Wait for end of page erase */
  30. while ((FLASH->CR & FLASH_CR_STRT) != 0) { __NOP(); }
  31. address = FLASH_PAGE_START;
  32. }
  33. // write data from address
  34. /* Set PG bit */
  35. FLASH->CR |= FLASH_CR_PG;
  36. /* Program first word */
  37. *(uint32_t *)address = val.u32[0];
  38. /* Barrier to ensure programming is performed in 2 steps, in right order
  39. (independently of compiler optimization behavior) */
  40. __ISB();
  41. /* Program second word */
  42. *(uint32_t *)(address + 4U) = val.u32[1];
  43. /* Set the LOCK Bit to lock the FLASH Registers access */
  44. SET_BIT(FLASH->CR, FLASH_CR_LOCK);
  45. }
  46. return res;
  47. }
  48. /**
  49. * @brief Read fom flash latest actual data.
  50. * @param data
  51. * @return flash_result_t
  52. */
  53. flash_result_t Flash_Read(uint64_t * data) {
  54. nt64_t val;
  55. flash_result_t res = Flash_Ok;
  56. uint32_t address = FLASH_PAGE_START;
  57. while ((address < FLASH_PAGE_END) && ((*(__IO uint32_t*)address) != 0xffffffff)) {
  58. val.u32[0] = (*(__IO uint32_t*)address);
  59. address += 4;
  60. val.u32[1] = (*(__IO uint32_t*)address);
  61. address += 4;
  62. }
  63. *data = val.u64;
  64. if (address == FLASH_PAGE_START) {
  65. res = Flash_PG_Clear;
  66. } else if (address > FLASH_PAGE_END) {
  67. res = Flash_PG_End;
  68. }
  69. return res;
  70. }