embkernel
 All Classes Functions Variables Typedefs Groups Pages
DrvFlash.cpp
1 //------------------------------------------------------------------------------
2 //This file is part of embKernel.
3 //See license.txt for the full license governing this code.
4 //------------------------------------------------------------------------------
5 
6 #include "DrvFlash.hpp"
7 #include "DrvMacros.hpp"
8 #include "RtosInclude.hpp"
9 
10 void DrvFlash::unlock() {
11  FLASH ->SR |= (FLASH_SR_EOP | FLASH_SR_PGERR | FLASH_SR_WRPERR ); //Reset flags
12  FLASH ->KEYR = ((uint32_t) 0x45670123); //Key1
13  FLASH ->KEYR = ((uint32_t) 0xCDEF89AB); //Key2
14 }
15 
16 void DrvFlash::lock() {
17  FLASH ->CR |= FLASH_CR_LOCK;
18 }
19 
20 bool DrvFlash::erasePage(unsigned int page) {
21  if (!waitActionComplete()) {
22  return false;
23  }
24  uint32_t addr = (uint32_t) getPageStartAddress(page);
25 
26  FLASH ->CR = FLASH_CR_PER;
27  FLASH ->AR = addr;
28  FLASH ->CR |= FLASH_CR_STRT;
29 
30  if (!waitActionComplete()) {
31  return false;
32  }
33 
34  return true;
35 }
36 
37 bool DrvFlash::write(const void* dst, const void* src, size_t len) {
38  DRV_ASSERT((len&1)==0); //Len must by a multiple of 2
39  DRV_ASSERT(((uint32_t)dst&1)==0); //Dst must be aligned to 16bits boundary
40  DRV_ASSERT(((uint32_t)src&1)==0); //Src must be aligned to 16bits boundary
41 
42  if (!waitActionComplete()) {
43  return false;
44  }
45 
46  len >>= 1;
47  uint16_t* dst16 = (uint16_t*) dst;
48  uint16_t* src16 = (uint16_t*) src;
49  for (size_t i = 0; i < len; i++) {
50  FLASH ->CR = FLASH_CR_PG;
51  *dst16++ = *src16++;
52  if (!waitActionComplete()) {
53  FLASH ->CR &= ~FLASH_CR_PG;
54  return false;
55  }
56  FLASH ->CR &= ~FLASH_CR_PG;
57  }
58  return true;
59 }
60 
61 bool DrvFlash::waitActionComplete() {
62  while (FLASH ->SR & FLASH_SR_BSY ) {
63  }
64  if (FLASH ->SR & (FLASH_SR_PGERR | FLASH_SR_WRPERR )) {
65  return false;
66  }
67  return true;
68 }
69