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 "RtosInclude.hpp"
8 
9 void DrvFlash::unlock() {
10  FLASH ->SR |= (FLASH_SR_PGSERR | FLASH_SR_PGPERR | FLASH_SR_PGAERR | FLASH_SR_WRPERR | FLASH_SR_SOP ); //Reset error flags
11  FLASH ->KEYR = ((uint32_t) 0x45670123); //Key1
12  FLASH ->KEYR = ((uint32_t) 0xCDEF89AB); //Key2
13 }
14 
15 void DrvFlash::lock() {
16  FLASH ->CR |= FLASH_CR_LOCK;
17 }
18 
19 bool DrvFlash::erasePage(unsigned int page) {
20  if (!waitActionComplete()) {
21  return false;
22  }
23 
24  FLASH ->CR = (page << 3) | FLASH_CR_SER;
25  FLASH ->CR |= FLASH_CR_STRT;
26 
27  if (!waitActionComplete()) {
28  return false;
29  }
30 
31  return true;
32 }
33 
34 bool DrvFlash::write(const void* dst, const void* src, size_t len) {
35  if (!waitActionComplete()) {
36  return false;
37  }
38 
39  uint8_t* dst8 = (uint8_t*) dst;
40  uint8_t* src8 = (uint8_t*) src;
41  for (size_t i = 0; i < len; i++) {
42  FLASH ->CR = FLASH_CR_PG;
43  *dst8++ = *src8++;
44  if (!waitActionComplete()) {
45  return false;
46  }
47  FLASH ->CR &= ~FLASH_CR_PG;
48  }
49  return true;
50 }
51 
52 bool DrvFlash::waitActionComplete() {
53  while (FLASH ->SR & FLASH_SR_BSY ) {
54  }
55  if (FLASH ->SR & (FLASH_SR_PGSERR | FLASH_SR_PGPERR | FLASH_SR_PGAERR | FLASH_SR_WRPERR | FLASH_SR_SOP )) {
56  return false;
57  }
58  return true;
59 }
60