bckp_sram.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * bkpsram.c
  3. *
  4. * Created on: 13.10.2016
  5. * Author: pavel
  6. */
  7. #include "stm32f4xx_rcc.h"
  8. #include <stdbool.h>
  9. bool fBckpSramInit = false;
  10. bool bckp_sram_init() {
  11. uint16_t timeout = 0xFFFF;
  12. RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);
  13. PWR_BackupAccessCmd(ENABLE);
  14. RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_BKPSRAM, ENABLE);
  15. PWR_BackupRegulatorCmd(ENABLE);
  16. // Wait until the Backup SRAM low power Regulator is ready
  17. while(PWR_GetFlagStatus(PWR_FLAG_BRR) == RESET) {
  18. if (timeout-- == 0) {
  19. return false;
  20. }
  21. }
  22. fBckpSramInit = true;
  23. return true;
  24. }
  25. int8_t write_to_backup_sram( uint8_t *data, uint16_t bytes, uint16_t offset ) {
  26. const uint16_t backup_size = 0x1000;
  27. uint8_t* base_addr = (uint8_t *) BKPSRAM_BASE;
  28. uint16_t i;
  29. if (!fBckpSramInit) {
  30. /* ERROR : Backup SRAM is not ready */
  31. return -2;
  32. }
  33. if( bytes + offset >= backup_size ) {
  34. /* ERROR : the last byte is outside the backup SRAM region */
  35. return -1;
  36. }
  37. PWR_BackupAccessCmd(ENABLE);
  38. for( i = 0; i < bytes; i++ ) {
  39. *(base_addr + offset + i) = *(data + i);
  40. }
  41. return 0;
  42. }
  43. int8_t read_from_backup_sram( uint8_t *data, uint16_t bytes, uint16_t offset ) {
  44. const uint16_t backup_size = 0x1000;
  45. uint8_t* base_addr = (uint8_t *) BKPSRAM_BASE;
  46. uint16_t i;
  47. if (!fBckpSramInit) {
  48. /* ERROR : Backup SRAM is not ready */
  49. return -2;
  50. }
  51. PWR_BackupAccessCmd(ENABLE);
  52. if( bytes + offset >= backup_size ) {
  53. /* ERROR : the last byte is outside the backup SRAM region */
  54. return -1;
  55. }
  56. for( i = 0; i < bytes; i++ ) {
  57. *(data + i) = *(base_addr + offset + i);
  58. }
  59. return 0;
  60. }