├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── examples ├── flash_erase_all │ └── flash_erase_all.ino ├── flash_erase_and_write │ └── flash_erase_and_write.ino ├── test_all │ └── test_all.ino ├── virtual_page_format │ └── virtual_page_format.ino └── virtual_page_usage │ └── virtual_page_usage.ino ├── keywords.txt ├── library.properties └── src ├── EEPROM.h ├── Flash.cpp ├── Flash.h ├── NVRAM.cpp ├── NVRAM.h ├── VirtualPage.cpp ├── VirtualPage.h └── avr_eeprom.h /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.slo 3 | *.lo 4 | *.o 5 | *.obj 6 | 7 | # Precompiled Headers 8 | *.gch 9 | *.pch 10 | 11 | # Compiled Dynamic libraries 12 | *.so 13 | *.dylib 14 | *.dll 15 | 16 | # Fortran module files 17 | *.mod 18 | *.smod 19 | 20 | # Compiled Static libraries 21 | *.lai 22 | *.la 23 | *.a 24 | *.lib 25 | 26 | # Executables 27 | *.exe 28 | *.out 29 | *.app 30 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: generic 2 | addons: 3 | apt: 4 | packages: 5 | - libc6:i386 6 | - libstdc++6:i386 7 | env: 8 | global: 9 | - IDE_VERSION=1.8.1 10 | before_install: 11 | - /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_1.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :1 -ac -screen 0 1280x1024x16 12 | - sleep 3 13 | - export DISPLAY=:1.0 14 | - wget http://downloads.arduino.cc/arduino-$IDE_VERSION-linux64.tar.xz 15 | - tar xf arduino-$IDE_VERSION-linux64.tar.xz 16 | - mv arduino-$IDE_VERSION $HOME/arduino-ide 17 | - export PATH=$PATH:$HOME/arduino-ide 18 | - arduino --pref "boardsmanager.additional.urls=https://redbearlab.github.io/arduino/package_redbearlab_index.json,http://rfduino.com/package_rfduino166_index.json,https://redbearlab.github.io/arduino/package_redbearlab_index.json,https://sandeepmistry.github.io/arduino-nRF5/package_nRF5_boards_index.json" --save-prefs 19 | - #arduino --install-boards arduino:sam >/dev/null 20 | - #arduino --install-boards arduino:samd >/dev/null 21 | - arduino --install-boards RFduino:RFduino >/dev/null 22 | - arduino --install-boards RedBear:nRF51822 >/dev/null 23 | - arduino --install-boards sandeepmistry:nRF5 >/dev/null 24 | - arduino --install-boards arduino:nrf52 >/dev/null 25 | - buildExampleSketch() { arduino --verbose-build --verify --board $1 $PWD/examples/$2/$2.ino; } 26 | install: 27 | - mkdir -p $HOME/Arduino/libraries 28 | - ln -s $PWD $HOME/Arduino/libraries/. 29 | script: 30 | - #buildExampleSketch "arduino:sam:arduino_due_x_dbg" test_all 31 | - #buildExampleSketch "arduino:samd:arduino_zero_edbg" test_all 32 | - buildExampleSketch "RFduino:RFduino:RFduino" test_all 33 | - buildExampleSketch "RedBear:nRF51822:nRF51822" test_all 34 | - buildExampleSketch "RedBear:nRF51822:nRF51822_NANO" test_all 35 | - buildExampleSketch "sandeepmistry:nRF5:Generic_nRF51822:chip=xxac" test_all 36 | - buildExampleSketch "sandeepmistry:nRF5:Generic_nRF52832" test_all 37 | - buildExampleSketch "arduino:nrf52:primo" test_all 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | (This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.) 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | {description} 474 | Copyright (C) {year} {fullname} 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 489 | USA 490 | 491 | Also add information on how to contact you by electronic and paper mail. 492 | 493 | You should also get your employer (if you work as a programmer) or your 494 | school, if any, to sign a "copyright disclaimer" for the library, if 495 | necessary. Here is a sample; alter the names: 496 | 497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 498 | library `Frob' (a library for tweaking knobs) written by James Random 499 | Hacker. 500 | 501 | {signature of Ty Coon}, 1 April 1990 502 | Ty Coon, President of Vice 503 | 504 | That's all there is to it! 505 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # arduino-NVM 2 | 3 | [![Build Status](https://travis-ci.org/d00616/arduino-NVM.svg?branch=master)](https://travis-ci.org/d00616/arduino-NVM) 4 | 5 | This library allows the usage of internal Flash memory. To enhance the limited erase cycles a VirtualPage layer is available. On top of VirtualPage, there is an NVRAM class to allow a lot of writes by using a log-based storage. 6 | 7 | For Arduino compatibility, a subset of avr/eeprom.h functionality and a complete port of EEPROM.h is provided. 8 | 9 | Accessing bytes via NVRAM or EEPROM is faster than an AVR controller until the internal log is full. At this point, a new page must build. This process takes up to 3400ms (nRF51) or 1300ms (nRF52) depending on your hardware and the highest written address. 10 | 11 | To find out more about timing, please run "test_all" example. 12 | 13 | _This code is not compatible with any SoftDevice. You have to use the [radio notification](https://devzone.nordicsemi.com/tutorials/14/radio-notification/) and VirtualPage.clean_up()/NVRAM.write_prepare(NUMBER) to ensure that writes are only used in a time without radio activation._ 14 | 15 | ## Flash.h 16 | 17 | This class is the hardware abstraction to the Flash controller. Please look into Flash.h for a more detailed description. 18 | 19 | Please read the documentation of your microcontroller to find out limitations about writing into flash. You can use the FLASH_... defines in your code to take care about quirks. 20 | 21 | ## VirtualPage.h 22 | 23 | This class provides manages Flash pages. This helps you to reach more erase cycles and handle page faults. The underlying Flash page needs to hold some metadata so a VirtualPage is some bytes smaller than 4k. The size can differ between different hardware. 24 | 25 | If you need to allocate VirtualPages in performance critical situations, call VirtualPage.clean_up(), when you have a time slot of more than 100ms. 26 | 27 | For VirtualPages the last 16k(nRF51) or 32k(nRF52) are used. This allows the same number of erase cycles on both platforms. 28 | 29 | ## NVRAM.h 30 | 31 | This class provides a 3072 bytes large memory. You can access this memory in a random order without needing to take care of the underlying flash architecture. This class is stateless, this means there is nothing cached in RAM. With every access, the data structure is parsed. This saves RAM and avoids conflicts when you have more than one instance of NVRAM class in your code. 32 | 33 | To reach a maximum of write cycles and performance, place all your data at the beginning of the memory. This allows a maximum of write cycles. 34 | 35 | When you only use the first 8 Bytes of the NVRAM, you have 5,100,000 write cycles per byte. If you use all 3072 bytes, you have only 3,300 write cycles per byte. 36 | 37 | For your own calculation of write cycles, you can calculate the sum of available writes with: (VirtualPage.length()-4-HIGHEST_ADDRESS/4)*40,000 38 | 39 | Reading or writing the NVRAM is fast until the internal log is full. On nRF51 you can calculate with 1.2ms and on nRF52 with 0,5ms. If the log is full a new VirtualPage is allocated and written. This procedure can take a time of 3400ms (nRF51) or 1300ms (nRF52). 40 | 41 | If you use this code in performance critical situations. Use NVRAM.write_prepare(NUMBER) before to guarantee a fast write for the given number of bytes. 42 | 43 | ## EEPROM.h and avr_eeprom.h 44 | 45 | Both libraries are for Arduino compatibility. Instead of avr/eeprom.h, you have to include avr_eeprom.h. This file maps a limited set of functions to NVRAM. 46 | 47 | The EEPROM.h is fully compatible with the AVR version without committing changes. 48 | 49 | If you use one of both files, please keep in mind that writing a single byte is fast until the log becomes full. In that case, a single write operation can take up to 3400ms (nRF51) or 1300ms (nRF52). 50 | -------------------------------------------------------------------------------- /examples/flash_erase_all/flash_erase_all.ino: -------------------------------------------------------------------------------- 1 | /* 2 | * This skech erases all content of your controller. Use it only, when 3 | * you are able to install all firemware parts via your programmer. 4 | * 5 | * There is no chance to to updates over the air or via serial port 6 | * after erasing the Flash! 7 | */ 8 | 9 | #include 10 | 11 | void setup() { 12 | Serial.begin(9600); 13 | } 14 | 15 | char num=0; 16 | char yes=10; 17 | void loop() { 18 | if ((millis()%5000)<100) { 19 | Serial.println(); 20 | Serial.println("**************************************************"); 21 | Serial.println("* This sketch deletes all Flash memory including *"); 22 | Serial.println("* this sketch, bootloaders and SoftDevices!!! *"); 23 | Serial.println("* ---------------------------------------------- *"); 24 | Serial.println("* After erasing the Flash, you need to flash *"); 25 | Serial.println("* a new Sketch with a programmer like J-Link, *"); 26 | Serial.println("* ST-Link v2 or CMSIS-DAP. Other methods dosn't *"); 27 | Serial.println("* work! *"); 28 | Serial.println("* ---------------------------------------------- *"); 29 | Serial.println("* If you are shure what you are doing, send a *"); 30 | Serial.println("* 'Y' character to erase the nRF CPU completely. *"); 31 | Serial.println("* ---------------------------------------------- *"); 32 | Serial.println("* You may brick your device! *"); 33 | Serial.println("**************************************************"); 34 | num=0; 35 | } else { 36 | if (num++<49) { 37 | Serial.print('.'); 38 | } else { 39 | Serial.println('.'); 40 | num=0; 41 | } 42 | } 43 | if (Serial.available() > 0) { 44 | if (Serial.read() == 'Y') { 45 | if (yes>0) { 46 | Serial.print("\r\nYou may brick your device. Please give me "); 47 | Serial.print(yes, DEC); 48 | Serial.println(" additional 'Y' characters."); 49 | yes--; 50 | } else { 51 | Serial.println("\r\nYou have been warned! Erase flash. Goodbye."); 52 | Flash.erase_all(); 53 | } 54 | } 55 | } 56 | delay(50); 57 | } 58 | -------------------------------------------------------------------------------- /examples/flash_erase_and_write/flash_erase_and_write.ino: -------------------------------------------------------------------------------- 1 | /* 2 | * This skech do sime erase and write operations to the last available 3 | * Flash page. 4 | */ 5 | 6 | #include 7 | 8 | // Output function 9 | void print_word(uint32_t *address); 10 | 11 | void setup() { 12 | Serial.begin(9600); 13 | delay(1500); 14 | 15 | // Print some flash data 16 | Serial.print("Flash page size: "); 17 | Serial.println(Flash.page_size()); 18 | Serial.print("Number of flash pages: "); 19 | Serial.println(Flash.page_count()); 20 | Serial.print("Address of first page: 0x"); 21 | Serial.println((size_t)Flash.page_address(0), HEX); 22 | 23 | // Find out address of the last available page 24 | uint32_t *page = Flash.page_address(Flash.page_count() - 1); 25 | print_word(page); 26 | 27 | // Erase the page 28 | Serial.println("Erase page"); 29 | Flash.erase(page, Flash.page_size()); 30 | print_word(page); 31 | 32 | // Inform about write 33 | Serial.println("Write 0x12345678"); 34 | 35 | // Write to flash, you can do more writes until writing is disabled 36 | Flash.write(page, 0x12345678); 37 | 38 | // Print memory content 39 | print_word(page); 40 | } 41 | 42 | void loop() { 43 | // Nothing to do here 44 | yield(); 45 | } 46 | 47 | // Print data 48 | void print_word(uint32_t *address) { 49 | Serial.print("Word at address 0x"); 50 | Serial.print((size_t)address, HEX); 51 | Serial.print("=0x"); 52 | Serial.println(*address, HEX); 53 | } 54 | -------------------------------------------------------------------------------- /examples/test_all/test_all.ino: -------------------------------------------------------------------------------- 1 | /* 2 | * Test code for Flash, VirtualPage, NVM and EEPROM 3 | * 4 | * Do some tests and prints hopefully a lot of "OK" 5 | * messages. 6 | * 7 | * This example code is in the public domain. 8 | */ 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | // Enable tests 17 | #define TEST_FLASH 18 | #define TEST_VIRTUALPAGE 19 | #define TEST_NVRAM_TIMING 20 | #define TEST_NVRAM_CONSISTENCY 21 | #define TEST_EEPROM 22 | 23 | // Internal functions 24 | void print_ok(); 25 | void print_error(); 26 | void print_compare(uint32_t word1, uint32_t word2); 27 | void print_word(uint32_t *address); 28 | void print_time(time_t time); 29 | uint8_t addr2value(uint16_t idx); 30 | 31 | // Constants 32 | #define MAGIC1 0x12345678 33 | #define MAGIC2 0x87654321 34 | #define MAGIC3 0x88888888 35 | #define EMPTY 0xffffffff 36 | 37 | void setup() { 38 | // Initialize serial port 39 | Serial.begin(9600); 40 | // Wait some time 41 | delay(1500); 42 | 43 | // Testdata 44 | uint32_t *page, *old_page; 45 | uint32_t testword = 0x12345678; 46 | uint32_t testword_in; 47 | time_t time_start, time_end, time_max; 48 | uint16_t fill_size; 49 | bool failed; 50 | 51 | // Clear Flash 52 | VirtualPage.format(); 53 | 54 | /* 55 | * Test Flash functionality 56 | */ 57 | #ifdef TEST_FLASH 58 | Serial.println("\r\nFlash:\r\n======"); 59 | // Print some flash data 60 | Serial.print("Flash page size: "); 61 | Serial.println(Flash.page_size()); 62 | Serial.print("Number of flash pages: "); 63 | Serial.println(Flash.page_count()); 64 | Serial.print("Address of first page: 0x"); 65 | Serial.println((size_t)Flash.page_address(0), HEX); 66 | 67 | // Find out address of a page 68 | page = Flash.page_address(Flash.page_count() - 20); 69 | print_word(page); 70 | Serial.println(); 71 | 72 | // Erase the page 73 | Serial.print("Erase page:"); 74 | Flash.erase(page, Flash.page_size()); 75 | print_compare(page[0], EMPTY); 76 | 77 | // Test write 78 | Serial.print("Flash.write:"); 79 | Flash.write(page, testword); 80 | print_compare(page[0], testword); 81 | 82 | Serial.print("Flash.write_block:"); 83 | Flash.write_block(&page[1], &testword, sizeof(testword)); 84 | print_compare(page[1], testword); 85 | #endif 86 | 87 | /* 88 | * Test VirtualPage functionality 89 | */ 90 | #ifdef TEST_VIRTUALPAGE 91 | Serial.println("\r\nVirtualPage:\r\n============"); 92 | Serial.println("Format VirtualPage area."); 93 | VirtualPage.format(); 94 | 95 | Serial.print("VirtualPage size:"); 96 | Serial.println(VirtualPage.size()); 97 | Serial.print("VirtualPage size:"); 98 | Serial.println(VirtualPage.length()); 99 | Serial.print("VirtualPage page_count:"); 100 | Serial.println(VirtualPage.page_count()); 101 | Serial.print("VirtualPage wear_level:"); 102 | Serial.print(((float)VirtualPage.wear_level()) / 100); 103 | Serial.println("%\r\n"); 104 | 105 | Serial.print("Get an invalid page:"); 106 | page = VirtualPage.get(MAGIC3); 107 | print_compare((size_t)page, EMPTY); 108 | 109 | Serial.print("Allocate a page:"); 110 | page = VirtualPage.allocate(MAGIC1); 111 | print_compare2((size_t)page, EMPTY); 112 | 113 | Serial.print("Page is not in 'Release' state: "); 114 | print_compare(VirtualPage.release_started(page), 0); 115 | 116 | Serial.print("Get page again:"); 117 | page = VirtualPage.get(MAGIC1); 118 | print_compare2((size_t)page, EMPTY); 119 | 120 | Serial.print("Write to page:"); 121 | Flash.write(&page[0], testword); 122 | print_compare(page[0], testword); 123 | 124 | Serial.print("Prepare release a page:"); 125 | VirtualPage.release_prepare(page); 126 | print_compare(VirtualPage.release_started(page), 1); 127 | old_page = page; 128 | 129 | Serial.println("Allocate a page:"); 130 | page = VirtualPage.allocate(MAGIC1); 131 | Serial.print(" - Valid page:"); 132 | print_compare2((size_t)page, EMPTY); 133 | Serial.print(" - Got a new page:"); 134 | print_compare2((size_t)old_page, (size_t)page); 135 | 136 | Serial.println("Simulate aborted release:"); 137 | page = VirtualPage.get(MAGIC1); 138 | Serial.print(" - Got old page:"); 139 | print_compare((size_t)old_page, (size_t)page); 140 | Serial.print(" - Page in release:"); 141 | print_compare(VirtualPage.release_started(page), 1); 142 | 143 | Serial.println("Allocate a page:"); 144 | page = VirtualPage.allocate(MAGIC1); 145 | Serial.print(" - Valid page:"); 146 | print_compare2((size_t)page, EMPTY); 147 | Serial.print(" - Got a new page:"); 148 | print_compare2((size_t)old_page, (size_t)page); 149 | 150 | Serial.print("Release old page:"); 151 | VirtualPage.release(old_page); 152 | page = VirtualPage.get(MAGIC1); 153 | print_compare2((size_t)old_page, (size_t)page); 154 | 155 | Serial.print("Write to page:"); 156 | Flash.write(&page[0], testword); 157 | print_compare(page[0], testword); 158 | 159 | Serial.print("Try to allocate duplicate pages:"); 160 | failed = false; 161 | // try to allocate more pages than available. This must work because the old 162 | // page hast to deleted by allocate() 163 | for (int i = 0; i <= (VirtualPage.page_count() + 1); i++) { 164 | page = VirtualPage.allocate(MAGIC1); 165 | // When no page is availabe or testdata found -> error 166 | if (((size_t)page == EMPTY) || (page[0] == testword)) { 167 | failed = true; 168 | } 169 | } 170 | print_compare(failed, 0); 171 | 172 | Serial.print("Do clean_up(): "); 173 | VirtualPage.release(old_page); 174 | time_start = micros(); 175 | VirtualPage.clean_up(); 176 | time_end = micros(); 177 | print_time(time_end - time_start); 178 | // clear all empty pages 179 | for (int i = 0; i < VirtualPage.page_count(); i++) { 180 | VirtualPage.clean_up(); 181 | } 182 | #endif 183 | 184 | /* 185 | * Test NVRAM functionality 186 | */ 187 | #if defined(TEST_NVRAM_CONSISTENCY) || defined(TEST_NVRAM_TIMING) 188 | Serial.println("\r\nNVRAM:\r\n======="); 189 | Serial.print("NVRAM size:"); 190 | Serial.println(NVRAM.length()); 191 | Serial.print("NVRAM log size:"); 192 | Serial.println(NVRAM.write_prepare(0)); 193 | Serial.println(); 194 | #endif 195 | 196 | // Repeat this test with various length of used cells 197 | #ifdef TEST_NVRAM_TIMING 198 | fill_size = 1; 199 | 200 | while (fill_size < NVRAM.length() - 4) { 201 | // Calculate addresses to fill 202 | fill_size = fill_size * 2; 203 | if (fill_size > NVRAM.length()) 204 | fill_size = NVRAM.length(); 205 | 206 | // Fill 207 | Serial.print("Fill NVRAM with "); 208 | Serial.print(fill_size); 209 | Serial.println(" bytes:"); 210 | time_max = 0; 211 | while (NVRAM.write_prepare(0) > 5) { 212 | uint16_t addr = random(0, fill_size); 213 | for (int i = 0; i < 4; i++) { 214 | time_start = micros(); 215 | NVRAM.write(addr, random(0, 256)); 216 | time_end = micros(); 217 | if ((time_end - time_start) > time_max) { 218 | time_max = time_end - time_start; 219 | } 220 | addr++; 221 | } 222 | } 223 | 224 | Serial.print(" - Max write time until log is full: "); 225 | print_time(time_max); 226 | 227 | // Read 228 | time_max = 0; 229 | for (int i = 0; i < NVRAM.length(); i++) { 230 | time_start = micros(); 231 | NVRAM.read(i); 232 | time_end = micros(); 233 | if ((time_end - time_start) > time_max) { 234 | time_max = time_end - time_start; 235 | } 236 | } 237 | Serial.print(" - Max read time when log is full: "); 238 | print_time(time_max); 239 | 240 | // Force switch page 241 | Serial.print(" - Log full write time: "); 242 | time_start = micros(); 243 | NVRAM.write_prepare(20); 244 | time_end = micros(); 245 | print_time(time_end - time_start); 246 | } 247 | #endif 248 | 249 | #ifdef TEST_NVRAM_CONSISTENCY 250 | Serial.println("Check consistency: "); 251 | 252 | Serial.print(" - Write byte: "); 253 | NVRAM.write(257, 0xcc); 254 | print_compare(NVRAM.read(257), 0xcc); 255 | 256 | Serial.print(" - Write block: "); 257 | NVRAM.write_block((uint8_t *)&testword, 257, sizeof(testword)); 258 | NVRAM.read_block((uint8_t *)&testword_in, 257, sizeof(testword)); 259 | print_compare(testword, testword_in); 260 | 261 | Serial.print(" - Until log is full: "); 262 | // Clear all VirtualPages 263 | VirtualPage.format(); 264 | failed = false; 265 | fill_size = 0; 266 | // Fill until log is full 267 | for (int i = 0; (i < NVRAM.length()) && (NVRAM.write_prepare(0) > 10); i++) { 268 | uint8_t idxval = addr2value(i); 269 | NVRAM.write(i, idxval); 270 | if (NVRAM.read(i) != idxval) 271 | failed = true; 272 | fill_size = i; 273 | } 274 | print_compare(failed, 0); 275 | 276 | Serial.print(" - After clearing the log: "); 277 | failed = false; 278 | // Clear log 279 | NVRAM.write_prepare(512); 280 | // Check 281 | for (int i = 0; i < fill_size; i++) { 282 | uint8_t idxval = addr2value(i); 283 | if (NVRAM.read(i) != idxval) 284 | failed = true; 285 | } 286 | print_compare(failed, 0); 287 | #endif 288 | 289 | #ifdef TEST_EEPROM 290 | Serial.println("\r\nEEPROM:\r\n======="); 291 | 292 | Serial.print("eeprom_write_byte: "); 293 | eeprom_write_byte(0, 0xaa); 294 | print_compare(NVRAM.read(0), 0xaa); 295 | 296 | Serial.print("eeprom_read_byte: "); 297 | print_compare(eeprom_read_byte(0), 0xaa); 298 | 299 | Serial.print("eeprom_write_block: "); 300 | eeprom_write_block(&testword, 1, sizeof(testword)); 301 | NVRAM.read_block((uint8_t *)&testword_in, 1, sizeof(testword)); 302 | print_compare(testword, testword_in); 303 | 304 | Serial.print("eeprom_read_block: "); 305 | eeprom_read_block(&testword_in, 1, sizeof(testword)); 306 | print_compare(testword, testword_in); 307 | 308 | Serial.print("EEPROM.write: "); 309 | EEPROM.write(5, 0x77); 310 | print_compare(NVRAM.read(5), 0x77); 311 | 312 | Serial.print("EEPROM.read: "); 313 | print_compare(EEPROM.read(5), 0x77); 314 | 315 | Serial.print("EEPROM[]++: "); 316 | EEPROM[5]++; 317 | print_compare(EEPROM[5], 0x78); 318 | 319 | Serial.print("EEPROM[]--: "); 320 | EEPROM[5]--; 321 | print_compare(EEPROM[5], 0x77); 322 | 323 | #endif 324 | 325 | Serial.println("\r\n***************\r\n* The END ;-) *\r\n***************"); 326 | } 327 | 328 | void loop() { /** Empty loop. **/ 329 | } 330 | 331 | void print_ok() { Serial.println(" OK"); } 332 | 333 | void print_error() { Serial.println(" ERROR"); } 334 | 335 | void print_compare(uint32_t word1, uint32_t word2) { 336 | if (word1 == word2) { 337 | Serial.println(" OK"); 338 | } else { 339 | Serial.print(" ERROR ("); 340 | Serial.print(word1, HEX); 341 | Serial.print(" != "); 342 | Serial.print(word2, HEX); 343 | Serial.println(")"); 344 | } 345 | } 346 | 347 | void print_compare2(uint32_t word1, uint32_t word2) { 348 | if (word1 != word2) { 349 | Serial.println(" OK"); 350 | } else { 351 | Serial.print(" ERROR ("); 352 | Serial.print(word1, HEX); 353 | Serial.print(" == "); 354 | Serial.print(word2, HEX); 355 | Serial.println(")"); 356 | } 357 | } 358 | 359 | void print_word(uint32_t *address) { 360 | Serial.print("Word at address 0x"); 361 | Serial.print((size_t)address, HEX); 362 | Serial.print("=0x"); 363 | Serial.println(*address, HEX); 364 | } 365 | 366 | void fill_num(int num, char c) { 367 | if (num < 100) { 368 | Serial.print(c); 369 | } 370 | if (num < 10) { 371 | Serial.print(c); 372 | } 373 | } 374 | 375 | void print_time(time_t time) { 376 | int ms = time / 1000; 377 | int modulo = time % 1000; 378 | Serial.print(ms); 379 | Serial.print('.'); 380 | fill_num(modulo, '0'); 381 | Serial.print(modulo); 382 | Serial.println(" ms"); 383 | } 384 | 385 | uint8_t addr2value(uint16_t idx) { return (uint8_t)(idx + (idx >> 8)); } 386 | -------------------------------------------------------------------------------- /examples/virtual_page_format/virtual_page_format.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void setup() { 5 | Serial.begin(9600); 6 | delay(1500); 7 | Serial.println("This erases all virtual pages. The wear level is preserved."); 8 | VirtualPage.format(); 9 | Serial.println("Virtual pages are reset."); 10 | Serial.print("Actual Flash wear level: "); 11 | Serial.print(((float)VirtualPage.wear_level()) / 100); 12 | Serial.println("%"); 13 | } 14 | 15 | void loop() { yield(); } 16 | -------------------------------------------------------------------------------- /examples/virtual_page_usage/virtual_page_usage.ino: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * This skech erases demonstates the usage of VirtualPages. 4 | * 5 | * The VirtualPages are placed at the end of available Flash Memory. 6 | * For nRF52 32k are used. The nRF51 use 16k of Flash Memory. 7 | * 8 | * You can put any type of 32 Bit aligned data into a VirtualPage. 9 | * The size()/length() can differ at various platforms. At the moment 10 | * a page has a minium size of 4080 bytes. 11 | * 12 | * For compatibility please don't use random writes or check if 13 | * FLASH_SUPPORTS_RANDOM_WRITE is set after including . Fill 14 | * a virtual page from beginning to the end to support a wide range of 15 | * Flash Controllers. 16 | * 17 | * A page is addressed via a given MAGIC_COUNTER number. You can mange one or 18 | * two differnt pages at a time on Controllers with 16k of reservation. 19 | * 20 | */ 21 | 22 | #include 23 | #include 24 | 25 | // the MAGIC number to address your page 26 | #define MAGIC_COUNTER 0xe7cba72b 27 | #define MAGIC_TEST 0x5294aa9f 28 | 29 | // Functions 30 | void print_word(uint32_t *address); 31 | void print_time(time_t time_start, time_t time_end); 32 | void print_page_data(uint32_t *address); 33 | void print_address(uint32_t *address); 34 | void print_counter(uint32_t counter); 35 | void print_status(bool status); 36 | void print_ok(); 37 | void print_error(); 38 | 39 | // Variables 40 | time_t time_start, time_end; 41 | 42 | /***************************************************/ 43 | 44 | void setup() { 45 | Serial.begin(9600); 46 | delay(1500); 47 | 48 | // Clear VirtualPages if needed 49 | // VirtualPage.format(); 50 | 51 | // Variables 52 | uint32_t *vpage, *new_vpage; 53 | 54 | // Print out some data about virtual pages 55 | Serial.println("\r\n\r\nVirtual page " 56 | "demonstration\r\n----------------------------------"); 57 | Serial.print("Virtual page size in bytes: "); 58 | Serial.println(VirtualPage.size()); 59 | Serial.print("Virtual page number of words available: "); 60 | Serial.println(VirtualPage.length()); 61 | Serial.print("Maximum number of virtual pages: "); 62 | Serial.println(VirtualPage.page_count()); 63 | Serial.print("Wear level in percent: "); 64 | Serial.println(((float)VirtualPage.wear_level()) / 100); 65 | Serial.print("Used MAGIC_COUNTER word: 0x"); 66 | Serial.println(MAGIC_COUNTER, HEX); 67 | 68 | // Try to allocate an old page, if it fails allocate a new page 69 | time_start = micros(); 70 | vpage = VirtualPage.get(MAGIC_COUNTER); 71 | time_end = micros(); 72 | if (vpage == (uint32_t *)~0) { 73 | Serial.print("No page found with MAGIC_COUNTER 0x"); 74 | Serial.print(MAGIC_COUNTER, HEX); 75 | print_time(time_start, time_end); 76 | Serial.print("Allocate a new page at "); 77 | time_start = micros(); 78 | // Allocate a new page 79 | vpage = VirtualPage.allocate(MAGIC_COUNTER); 80 | time_end = micros(); 81 | } else { 82 | Serial.print("Found an old page at "); 83 | } 84 | print_address(vpage); 85 | print_time(time_start, time_end); 86 | print_page_data(vpage); 87 | print_counter(vpage[0]); 88 | 89 | Serial.println("\r\nUse pages in a loop. After 10 page releases we are using " 90 | "clean_up() for faster allocation."); 91 | for (int i = 0; i < 20; i++) { 92 | Serial.print("Interation "); 93 | Serial.println(i); 94 | Serial.println("*************************"); 95 | 96 | // Print page data 97 | print_page_data(vpage); 98 | print_counter(vpage[0]); 99 | 100 | // Prepare releasing the old page 101 | Serial.print("Prepare releasing the page "); 102 | time_start = micros(); 103 | VirtualPage.release_prepare(vpage); 104 | time_end = micros(); 105 | print_time(time_start, time_end); 106 | 107 | // Allocate a new page 108 | Serial.print("Allocate a new page at "); 109 | time_start = micros(); 110 | new_vpage = VirtualPage.allocate(MAGIC_COUNTER); 111 | time_end = micros(); 112 | print_address(new_vpage); 113 | print_time(time_start, time_end); 114 | 115 | // Print a message if allocating fails 116 | if ((uint32_t)new_vpage == (uint32_t)~0) { 117 | Serial.println("FAILED to allocate a new page. You can clear your " 118 | "VirtualPages with VirtualPage.format();"); 119 | } 120 | 121 | /* Write new counter to Flash. */ 122 | // Write new counter value 123 | Flash.write(&new_vpage[0], vpage[0] + 1); 124 | 125 | // Release the old page 126 | Serial.print("Release the old page"); 127 | time_start = micros(); 128 | VirtualPage.release(vpage); 129 | time_end = micros(); 130 | print_time(time_start, time_end); 131 | 132 | // Swap page 133 | vpage = new_vpage; 134 | 135 | // This code is for time measurement only. There is no need to call get() at 136 | // this point 137 | Serial.print("Time to get() the new page:"); 138 | time_start = micros(); 139 | vpage = VirtualPage.get(MAGIC_COUNTER); 140 | time_end = micros(); 141 | print_time(time_start, time_end); 142 | 143 | // Print page data 144 | print_page_data(vpage); 145 | print_counter(vpage[0]); 146 | 147 | // This code can called, in a none time critical moment 148 | // Released pages are erased to allow faster allocating. 149 | if (i > 9) { 150 | Serial.print("Clean up released pages "); 151 | time_start = micros(); 152 | VirtualPage.clean_up(); 153 | time_end = micros(); 154 | print_time(time_start, time_end); 155 | } 156 | 157 | Serial.println("\r\n"); 158 | delay(1500); 159 | } 160 | 161 | /* Do some testing. You don't need this in production code. */ 162 | Serial.println("Test functionality"); 163 | Serial.println("*************************"); 164 | 165 | Serial.print("Used MAGIC_TEST word: 0x"); 166 | Serial.println(MAGIC_TEST, HEX); 167 | 168 | // Find a page 169 | Serial.print("Try to get a page:"); 170 | vpage = VirtualPage.get(MAGIC_TEST); 171 | if (vpage == (uint32_t *)~0) { 172 | Serial.println(" no page found. (OK on first run)"); 173 | vpage = VirtualPage.allocate(MAGIC_TEST); 174 | } else { 175 | print_ok(); 176 | } 177 | 178 | // Write test data 179 | Serial.print("Write test:"); 180 | Flash.write(&vpage[0], 0x12345678); 181 | print_status(vpage[0] == 0x12345678); 182 | 183 | // Try to allocate a new page. Because the old page is not in release_sate, it 184 | // must deleted 185 | Serial.print("Alocate removes old pages:"); 186 | new_vpage = VirtualPage.allocate(MAGIC_TEST); 187 | print_status(vpage[0] != 0x12345678); 188 | 189 | // Allocate a new page, set it to release_prepare, allocate a new page and try 190 | // to get the page -> old page is given 191 | /* THIS IS BUGGY AT THE MOMENT 192 | Serial.print("Test interrupted release process:"); 193 | vpage = new_vpage; 194 | // this writes 0x87654321 starting at the fourth byte of the page 195 | Flash.write(&vpage[1], 0x87654321); 196 | VirtualPage.release_prepare(vpage); 197 | new_vpage = VirtualPage.allocate(MAGIC_TEST); 198 | new_vpage = VirtualPage.get(MAGIC_TEST); 199 | print_status( (size_t)vpage == (size_t)new_vpage); 200 | */ 201 | 202 | // End 203 | Serial.println("\r\nTHE END.\r\n\r\n"); 204 | } 205 | 206 | void loop() { yield(); } 207 | 208 | /***************************************************/ 209 | 210 | // print a data word inluding address 211 | void print_word(uint32_t *address) { 212 | Serial.print("Word at address 0x"); 213 | Serial.print((size_t)address, HEX); 214 | Serial.print("=0x"); 215 | Serial.println(*address, HEX); 216 | } 217 | 218 | // print a time 219 | void print_time(time_t time_start, time_t time_end) { 220 | time_t micros = time_end - time_start; 221 | 222 | Serial.print(" "); 223 | Serial.print(micros / 1000); 224 | Serial.print("."); 225 | int rest = (micros % 1000) / 10; 226 | if (rest < 10) { 227 | Serial.print("0"); 228 | } 229 | if (rest < 100) { 230 | Serial.print("0"); 231 | } 232 | Serial.print(rest); 233 | Serial.println("ms"); 234 | } 235 | 236 | // dump page data 237 | void print_page_data(uint32_t *address) { 238 | Serial.println("---------- Page data ----------"); 239 | Serial.print("Page address: 0x"); 240 | Serial.println((size_t)address, HEX); 241 | Serial.print("Page in release state: "); 242 | Serial.println(VirtualPage.release_started(address)); 243 | Serial.println("Data not equal to 0xffffffff:"); 244 | for (int i = 0; i < VirtualPage.length(); i++) { 245 | if (address[i] != ~(uint32_t)0) 246 | print_word(&address[i]); 247 | } 248 | Serial.println("-------------------------------"); 249 | } 250 | 251 | // Print a page address 252 | void print_address(uint32_t *address) { 253 | Serial.print("address 0x"); 254 | Serial.print((size_t)address, HEX); 255 | } 256 | 257 | // Print counter value 258 | void print_counter(uint32_t counter) { 259 | Serial.print("Data value is: "); 260 | Serial.println(counter); 261 | } 262 | 263 | void print_status(bool status) { 264 | if (status) { 265 | print_ok(); 266 | } else { 267 | print_error(); 268 | } 269 | } 270 | 271 | void print_ok() { Serial.println(" OK"); } 272 | 273 | void print_error() { Serial.println(" Error"); } 274 | -------------------------------------------------------------------------------- /keywords.txt: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # Syntax Coloring Map For EEPROM 3 | ####################################### 4 | 5 | ####################################### 6 | # Datatypes (KEYWORD1) 7 | ####################################### 8 | 9 | NVRAM KEYWORD1 10 | EEPROM KEYWORD1 11 | VirtualPage KEYWORD1 12 | Flash KEYWORD1 13 | 14 | ####################################### 15 | # Methods and Functions (KEYWORD2) 16 | ####################################### 17 | 18 | # Flash/VirtualPage/EEPROM 19 | length KEYWORD2 20 | page_count KEYWORD2 21 | 22 | # Flash/NVRAM/EEPROM 23 | write KEYWORD2 24 | write_block KEYWORD2 25 | clean_up KEYWORD2 26 | 27 | # Flash 28 | size KEYWORD2 29 | page_size KEYWORD2 30 | page_size_bits KEYWORD2 31 | page_count KEYWORD2 32 | specified_erase_cycles KEYWORD2 33 | page_address KEYWORD2 34 | erase KEYWORD2 35 | erase_all KEYWORD2 36 | 37 | # VirtualPage 38 | wear_level KEYWORD2 39 | get KEYWORD2 40 | allocate KEYWORD2 41 | release_prepare KEYWORD2 42 | release KEYWORD2 43 | release_started KEYWORD2 44 | fail KEYWORD2 45 | format KEYWORD2 46 | 47 | # NVRAM 48 | read_block KEYWORD2 49 | read KEYWORD2 50 | write_prepare KEYWORD2 51 | 52 | # EEPROM 53 | read KEYWORD2 54 | update KEYWORD2 55 | 56 | ####################################### 57 | # Constants (LITERAL1) 58 | ####################################### 59 | 60 | # Flash.h 61 | FLASH_ERASE_CYCLES LITERAL1 62 | FLASH_PAGE_SIZE LITERAL1 63 | FLASH_ERASE_PAGE_TIME LITERAL1 64 | FLASH_SUPPORTS_RANDOM_WRITE LITERAL1 65 | FLASH_WRITES_PER_WORD LITERAL1 66 | FLASH_WRITES_PER_PAGE LITERAL1 67 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=arduino-NVM 2 | version=0.9.1 3 | author=Frank Holtz 4 | maintainer=Frank Holtz 5 | sentence=Direct flash memory access, round robin virtual pages and EEPROM like memory. (Flash, VirtualPage, NVRAM) 6 | paragraph=This package includes three Libraries (Flash, VirtualPage, NVRAM) and a EEPROM Emulation. Use avr_eeprom.h for a minimal AVR compatibility. Please look into README.md 7 | category=Data Storage 8 | url=https://github.com/d00616/arduino-NVM 9 | architectures=nRF5,nRF52832,nRF51822 10 | -------------------------------------------------------------------------------- /src/EEPROM.h: -------------------------------------------------------------------------------- 1 | /* 2 | EEPROM.h - EEPROM library 3 | Original Copyright (c) 2006 David A. Mellis. All right reserved. 4 | New version by Christopher Andrews 2015. 5 | 6 | This library is free software; you can redistribute it and/or 7 | modify it under the terms of the GNU Lesser General Public 8 | License as published by the Free Software Foundation; either 9 | version 2.1 of the License, or (at your option) any later version. 10 | 11 | This library is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | Lesser General Public License for more details. 15 | 16 | You should have received a copy of the GNU Lesser General Public 17 | License along with this library; if not, write to the Free Software 18 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | 21 | #ifndef EEPROM_h 22 | #define EEPROM_h 23 | 24 | #include 25 | #include "NVRAM.h" 26 | 27 | /*** 28 | EERef class. 29 | 30 | This object references an EEPROM cell. 31 | Its purpose is to mimic a typical byte of RAM, however its storage is the EEPROM. 32 | This class has an overhead of two bytes, similar to storing a pointer to an EEPROM cell. 33 | ***/ 34 | 35 | struct EERef{ 36 | 37 | EERef( const int index ) 38 | : index( index ) {} 39 | 40 | //Access/read members. 41 | uint8_t operator*() const { return NVRAM.read( index ); } 42 | operator uint8_t() const { return **this; } 43 | 44 | //Assignment/write members. 45 | EERef &operator=( const EERef &ref ) { return *this = *ref; } 46 | EERef &operator=( uint8_t in ) { return NVRAM.write( index, in ), *this; } 47 | EERef &operator +=( uint8_t in ) { return *this = **this + in; } 48 | EERef &operator -=( uint8_t in ) { return *this = **this - in; } 49 | EERef &operator *=( uint8_t in ) { return *this = **this * in; } 50 | EERef &operator /=( uint8_t in ) { return *this = **this / in; } 51 | EERef &operator ^=( uint8_t in ) { return *this = **this ^ in; } 52 | EERef &operator %=( uint8_t in ) { return *this = **this % in; } 53 | EERef &operator &=( uint8_t in ) { return *this = **this & in; } 54 | EERef &operator |=( uint8_t in ) { return *this = **this | in; } 55 | EERef &operator <<=( uint8_t in ) { return *this = **this << in; } 56 | EERef &operator >>=( uint8_t in ) { return *this = **this >> in; } 57 | 58 | EERef &update( uint8_t in ) { return in != *this ? *this = in : *this; } 59 | 60 | /** Prefix increment/decrement **/ 61 | EERef& operator++() { return *this += 1; } 62 | EERef& operator--() { return *this -= 1; } 63 | 64 | /** Postfix increment/decrement **/ 65 | uint8_t operator++ (int){ 66 | uint8_t ret = **this; 67 | return ++(*this), ret; 68 | } 69 | 70 | uint8_t operator-- (int){ 71 | uint8_t ret = **this; 72 | return --(*this), ret; 73 | } 74 | 75 | int index; //Index of current EEPROM cell. 76 | }; 77 | 78 | /*** 79 | EEPtr class. 80 | 81 | This object is a bidirectional pointer to EEPROM cells represented by EERef objects. 82 | Just like a normal pointer type, this can be dereferenced and repositioned using 83 | increment/decrement operators. 84 | ***/ 85 | 86 | struct EEPtr{ 87 | 88 | EEPtr( const int index ) 89 | : index( index ) {} 90 | 91 | operator int() const { return index; } 92 | EEPtr &operator=( int in ) { return index = in, *this; } 93 | 94 | //Iterator functionality. 95 | bool operator!=( const EEPtr &ptr ) { return index != ptr.index; } 96 | EERef operator*() { return index; } 97 | 98 | /** Prefix & Postfix increment/decrement **/ 99 | EEPtr& operator++() { return ++index, *this; } 100 | EEPtr& operator--() { return --index, *this; } 101 | EEPtr operator++ (int) { return index++; } 102 | EEPtr operator-- (int) { return index--; } 103 | 104 | int index; //Index of current EEPROM cell. 105 | }; 106 | 107 | /*** 108 | EEPROMClass class. 109 | 110 | This object represents the entire EEPROM space. 111 | It wraps the functionality of EEPtr and EERef into a basic interface. 112 | This class is also 100% backwards compatible with earlier Arduino core releases. 113 | ***/ 114 | 115 | struct EEPROMClass{ 116 | 117 | //Basic user access methods. 118 | EERef operator[]( const int idx ) { return idx; } 119 | uint8_t read( int idx ) { return EERef( idx ); } 120 | void write( int idx, uint8_t val ) { (EERef( idx )) = val; } 121 | void update( int idx, uint8_t val ) { (EERef( idx )) = val; } 122 | 123 | //STL and C++11 iteration capability. 124 | EEPtr begin() { return 0x00; } 125 | EEPtr end() { return length(); } //Standards requires this to be the item after the last valid entry. The returned pointer is invalid. 126 | uint16_t length() { return NVRAM.length(); } 127 | 128 | //Functionality to 'get' and 'put' objects to and from EEPROM. 129 | template< typename T > T &get( int idx, T &t ){ 130 | EEPtr e = idx; 131 | uint8_t *ptr = (uint8_t*) &t; 132 | for( int count = sizeof(T) ; count ; --count, ++e ) *ptr++ = *e; 133 | return t; 134 | } 135 | 136 | template< typename T > const T &put( int idx, const T &t ){ 137 | EEPtr e = idx; 138 | const uint8_t *ptr = (const uint8_t*) &t; 139 | for( int count = sizeof(T) ; count ; --count, ++e ) (*e).update( *ptr++ ); 140 | return t; 141 | } 142 | }; 143 | 144 | extern EEPROMClass EEPROM; 145 | #endif 146 | -------------------------------------------------------------------------------- /src/Flash.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Flash.cpp - Flash library 3 | Original Copyright (c) 2017 Frank Holtz. All right reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | #include "Flash.h" 20 | 21 | FlashClass Flash; 22 | 23 | uint32_t FlashClass::page_size() const { 24 | return (size_t)NRF_FICR->CODEPAGESIZE; 25 | } 26 | 27 | uint8_t FlashClass::page_size_bits() const { 28 | #if defined(NRF51) 29 | return 10; 30 | #elif defined(NRF52) 31 | return 12; 32 | #endif 33 | } 34 | 35 | uint32_t FlashClass::page_count() const { return (uint32_t)NRF_FICR->CODESIZE; } 36 | 37 | uint32_t FlashClass::specified_erase_cycles() const { 38 | return FLASH_ERASE_CYCLES; 39 | } 40 | 41 | uint32_t *FlashClass::page_address(size_t page) { 42 | return (uint32_t *)(page << page_size_bits()); 43 | } 44 | 45 | void FlashClass::erase(uint32_t *address, size_t size) { 46 | size_t end_address = (size_t)address + size; 47 | 48 | // align address 49 | address = 50 | (uint32_t *)((size_t)address & (size_t)((size_t)(~0) - FLASH_PAGE_SIZE)); 51 | 52 | // Wrong parameters? 53 | if ((size_t)address >= end_address) 54 | return; 55 | 56 | // get old nvm controller state 57 | uint32_t old_config = NRF_NVMC->CONFIG; 58 | 59 | // Enable erasing flash 60 | NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Een << NVMC_CONFIG_WEN_Pos; 61 | 62 | // Erase page(s) 63 | while ((size_t)address < end_address) { 64 | wait_for_ready(); 65 | // Erase one 1k/4k page 66 | NRF_NVMC->ERASEPAGE = (size_t)(address); 67 | address = (uint32_t *)((size_t)address + FLASH_PAGE_SIZE); 68 | } 69 | 70 | // Disable erasing 71 | wait_for_ready(); 72 | NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos; 73 | 74 | // Restore old state 75 | wait_for_ready(); 76 | NRF_NVMC->CONFIG = old_config; 77 | 78 | // Go back if controller is ready 79 | wait_for_ready(); 80 | } 81 | 82 | void FlashClass::erase_all() { 83 | // Enable erasing flash 84 | NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Een << NVMC_CONFIG_WEN_Pos; 85 | wait_for_ready(); 86 | 87 | // Erase Flash and UICR 88 | NRF_NVMC->ERASEALL = 1; 89 | wait_for_ready(); 90 | 91 | // Disable erasing 92 | NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos; 93 | wait_for_ready(); 94 | } 95 | 96 | void FlashClass::write(uint32_t *address, uint32_t value) { 97 | // Compare word 98 | if (*address != value) { 99 | // Enable write 100 | NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Wen << NVMC_CONFIG_WEN_Pos; 101 | wait_for_ready(); 102 | // Write word 103 | *address = value; 104 | // Disable write 105 | wait_for_ready(); 106 | NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos; 107 | wait_for_ready(); 108 | } 109 | } 110 | 111 | void FlashClass::write_block(uint32_t *dst_address, uint32_t *src_address, 112 | uint16_t word_count) { 113 | // Enable write 114 | NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Wen << NVMC_CONFIG_WEN_Pos; 115 | wait_for_ready(); 116 | 117 | while (word_count > 0) { 118 | if (*dst_address != *src_address) { 119 | *dst_address = *src_address; 120 | } 121 | word_count--; 122 | dst_address++; 123 | src_address++; 124 | } 125 | 126 | // Disable write 127 | wait_for_ready(); 128 | NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos; 129 | wait_for_ready(); 130 | } 131 | 132 | void FlashClass::wait_for_ready() { 133 | while (NRF_NVMC->READY == NVMC_READY_READY_Busy) { 134 | }; 135 | } 136 | -------------------------------------------------------------------------------- /src/Flash.h: -------------------------------------------------------------------------------- 1 | /* 2 | Flash.h - Flash library 3 | Original Copyright (c) 2017 Frank Holtz. All right reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #pragma once 21 | 22 | #include 23 | #include // for size_t 24 | 25 | #ifdef __RFduino__ 26 | #include 27 | #else 28 | #include 29 | #endif 30 | 31 | /* 32 | * Define characteristics of Flash 33 | * 34 | * FLASH_ERASE_CYCLES : Specified number of erase cycles 35 | * FLASH_PAGE_SIZE : Used/supported Flash page size 36 | * FLASH_ERASE_PAGE_TIME : Time in ms to delete a page 37 | * FLASH_WRITES_PER_WORD : How often a dataword (32 bit) can written 38 | * FLASH_WRITES_PER_PAGE : How many writes are allowed into a page 39 | * FLASH_SUPPORTS_RANDOM_WRITE: Set this if it is allowed to write to a page in 40 | * random order. 41 | */ 42 | 43 | #if defined(NRF51) 44 | #define FLASH_ERASE_CYCLES 20000 45 | #define FLASH_PAGE_SIZE 1024 46 | #define FLASH_ERASE_PAGE_TIME 23 47 | #define FLASH_SUPPORTS_RANDOM_WRITE true 48 | #define FLASH_WRITES_PER_WORD 2 49 | #define FLASH_WRITES_PER_PAGE 512 50 | #elif defined(NRF52) 51 | #define FLASH_ERASE_CYCLES 10000 52 | #define FLASH_PAGE_SIZE 4096 53 | #define FLASH_ERASE_PAGE_TIME 90 54 | #define FLASH_SUPPORTS_RANDOM_WRITE true 55 | #define FLASH_WRITES_PER_WORD 32 56 | #define FLASH_WRITES_PER_PAGE 181 57 | #elif defined(NRF52840) 58 | #define FLASH_ERASE_CYCLES 10000 59 | #define FLASH_PAGE_SIZE 4096 60 | #define FLASH_ERASE_PAGE_TIME 90 61 | #define FLASH_SUPPORTS_RANDOM_WRITE true 62 | #define FLASH_WRITES_PER_WORD 2 63 | #define FLASH_WRITES_PER_PAGE 403 64 | #else 65 | #define FLASH_ERASE_CYCLES 10000 66 | #define FLASH_PAGE_SIZE 4096 67 | #define FLASH_ERASE_PAGE_TIME 100 68 | //#define FLASH_SUPPORTS_RANDOM_WRITE true 69 | #define FLASH_WRITES_PER_WORD 1 70 | #warning "Unknown platform. Please check the code." 71 | #endif 72 | 73 | class FlashClass { 74 | public: 75 | FlashClass(){}; 76 | void begin(){}; 77 | void end(){}; 78 | 79 | /* 80 | * Physical flash geometry 81 | */ 82 | 83 | // Page size in bytes 84 | uint32_t page_size() const; 85 | 86 | // Page size in bits 87 | uint8_t page_size_bits() const; 88 | 89 | // Number of pages 90 | uint32_t page_count() const; 91 | 92 | // Number of erase cycles 93 | uint32_t specified_erase_cycles() const; 94 | 95 | // Get a address of a page 96 | uint32_t *page_address(size_t page); 97 | 98 | /* 99 | * Accessing flash memory 100 | */ 101 | 102 | // Erase a page of given size. Size must be page_size aligned! 103 | // Take care about RADIO, WDT and Interrupt timing! 104 | void erase(uint32_t *address, size_t size); 105 | 106 | // Erase the complete MCU. This can brick your device! 107 | void erase_all(); 108 | 109 | // write a aligned 32 bit word to flash. Depends on write_enable! 110 | void write(uint32_t *address, uint32_t value); 111 | 112 | // write a aligned 32 bit word to flash. Depends on write_enable! 113 | void write_block(uint32_t *dst_address, uint32_t *src_address, 114 | uint16_t word_count); 115 | 116 | private: 117 | // Wait until flash is ready 118 | void wait_for_ready(); 119 | }; 120 | 121 | extern FlashClass Flash; 122 | -------------------------------------------------------------------------------- /src/NVRAM.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | NVRAM.cpp - Byte wise storage for Virtual Pages. 3 | Original Copyright (c) 2017 Frank Holtz. All right reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #include "NVRAM.h" 21 | 22 | // VirtualPage magic 23 | #define NVRAM_MAGIC (0x7710fdb9) 24 | // Number of emulated cells 25 | #define NVRAM_LENGTH 3072 26 | // Log configuration: Address index in bits 27 | #define NVRAM_ADDR_POS 20 28 | // Log configuration: Mask for comparsion (4k space) 29 | #define NVRAM_ADDR_MASK 0xfff00000 30 | // Log configuration: Bit position of used address bitmap 31 | #define NVRAM_BITMAP_POS 8 32 | // Log configuration: used address bitmap calulation 33 | #define NVRAM_BITMAP_ADDR_SHIFT 8 34 | // Log configuration: Mask for bitmap extraction 35 | #define NVRAM_BITMAP_MASK 0x000fff00 36 | #define ADDR2BIT(index) \ 37 | ((1 << (index >> NVRAM_BITMAP_ADDR_SHIFT)) << NVRAM_BITMAP_POS) 38 | 39 | NVRAMClass NVRAM; 40 | 41 | uint16_t NVRAMClass::length() const { return (NVRAM_LENGTH); } 42 | 43 | void NVRAMClass::read_block(uint8_t *dst, uint16_t idx, uint16_t n) { 44 | uint32_t *vpage; 45 | uint16_t log_start, log_end; 46 | 47 | // find correct page 48 | vpage = get_page(); 49 | 50 | // copy 0xff to dst when no page is available 51 | if (vpage == (uint32_t *)~0) { 52 | for (uint32_t i = 0; i < n; i++) { 53 | ((uint8_t *)dst)[i] = 0xff; 54 | } 55 | return; 56 | } 57 | 58 | // calculate actual log position 59 | log_end = get_log_position(vpage); 60 | if (log_end == 0) { 61 | log_start = 1; 62 | } else { 63 | log_start = vpage[0] + 1; 64 | } 65 | /* 66 | Serial.print("\r\nread_block idx="); 67 | Serial.print(idx); 68 | Serial.print(" n="); 69 | Serial.print(n); 70 | Serial.print("("); */ 71 | while (n > 0) { 72 | // Read cell 73 | *dst = get_byte_from_page(vpage, log_start, log_end, idx); 74 | // Serial.print(*dst, HEX); 75 | // calculate next address 76 | n--; 77 | dst++; 78 | idx++; 79 | } 80 | // Serial.println(")"); 81 | } 82 | 83 | uint8_t NVRAMClass::read(const uint16_t idx) { 84 | uint8_t ret; 85 | read_block(&ret, idx, 1); 86 | return ret; 87 | } 88 | 89 | bool NVRAMClass::write_block(uint8_t *src, uint16_t idx, uint16_t n) { 90 | uint32_t *vpage; 91 | uint32_t bitmap; 92 | uint16_t log_start, log_end; 93 | 94 | // find correct page 95 | vpage = get_page(); 96 | 97 | // return on invalid page 98 | if (vpage == (uint32_t *)~0) { 99 | return false; 100 | } 101 | 102 | // calculate actual log position 103 | log_start = vpage[0] + 1; 104 | log_end = get_log_position(vpage); 105 | if (log_end > log_start) { 106 | bitmap = vpage[log_end - 1] & NVRAM_BITMAP_MASK; 107 | } else { 108 | bitmap = 0; 109 | } 110 | 111 | while (n > 0) { 112 | // Read cell 113 | uint8_t old_value = get_byte_from_page(vpage, log_start, log_end, idx); 114 | uint8_t new_value = *src; 115 | 116 | // Have to write into log? 117 | if (new_value != old_value) { 118 | 119 | // need to calculate a new page? 120 | if (log_end >= VirtualPage.length()) { 121 | vpage = switch_page(vpage, &log_start, &log_end); 122 | if (vpage == (uint32_t *)~0) { 123 | // do nothing if no page is available 124 | return false; 125 | } 126 | bitmap = 0; 127 | } 128 | 129 | // Add Entry into log 130 | Flash.write(&vpage[log_end], (idx << NVRAM_ADDR_POS) | bitmap | 131 | ADDR2BIT(idx) | (uint32_t)new_value); 132 | log_end++; 133 | } 134 | 135 | // calculate next address 136 | n--; 137 | src++; 138 | idx++; 139 | } 140 | return true; 141 | } 142 | 143 | bool NVRAMClass::write(uint16_t idx, uint8_t value) { 144 | return (write_block(&value, idx, 1)); 145 | } 146 | 147 | int NVRAMClass::write_prepare(uint16_t number) { 148 | // find correct page 149 | uint32_t *vpage = get_page(); 150 | // Want to write to much or into an invalid page? 151 | if ((vpage == (uint32_t *)~0) || (number > length())) 152 | return -1; 153 | 154 | // calculate actual log position 155 | uint16_t log_end = get_log_position(vpage); 156 | 157 | // Calculate number of free bytes in log 158 | int free_bytes = ((VirtualPage.length() - 1) - log_end); 159 | 160 | // switch page when 161 | if (free_bytes < number) { 162 | uint16_t log_start = vpage[0] + 1; 163 | vpage = switch_page(vpage, &log_start, &log_end); 164 | if (vpage == (uint32_t *)~0) { 165 | // do nothing if no page is available 166 | return -1; 167 | } 168 | log_end = get_log_position(vpage); 169 | free_bytes = ((VirtualPage.length() - 1) - log_end); 170 | } 171 | return free_bytes; 172 | } 173 | 174 | void NVRAMClass::clean_up(uint16_t write_preserve) { 175 | VirtualPage.clean_up(); 176 | if (write_preserve > 0) 177 | write_prepare(write_preserve); 178 | } 179 | 180 | uint32_t *NVRAMClass::switch_page(uint32_t *old_vpage, uint16_t *log_start, 181 | uint16_t *log_end) { 182 | // Mark old page as in release 183 | VirtualPage.release_prepare(old_vpage); 184 | 185 | // Get a blank page 186 | uint32_t *new_vpage = VirtualPage.allocate(NVRAM_MAGIC, VirtualPage.length()); 187 | if (new_vpage == (uint32_t *)~0) { 188 | // failed 189 | return new_vpage; 190 | } 191 | 192 | // Store four bytes for map creation 193 | uint32_t value; 194 | 195 | // Length of new map 196 | uint16_t map_length = 0; 197 | 198 | // Build map 199 | #ifdef FLASH_SUPPORTS_RANDOM_WRITE 200 | // Copy current values 201 | for (uint16_t i = 0; i < (NVRAM_LENGTH >> 2); i++) { 202 | read_block((uint8_t *)&value, i << 2, 4); 203 | if (value != (uint32_t)~0) { 204 | // Value found 205 | map_length = i + 1; 206 | Flash.write(&new_vpage[i + 1], value); 207 | } 208 | } 209 | // Store map length 210 | Flash.write(new_vpage, map_length); 211 | #else 212 | // find map length 213 | for (uint16_t i = (NVRAM_LENGTH >> 2); i > 0; i--) { 214 | read_block((uint8_t *)&value, i << 2, 4); 215 | if (value != (uint32_t)~0) { 216 | // Value found 217 | map_length = i; 218 | break; 219 | } 220 | } 221 | map_length++; 222 | 223 | // Store map length 224 | Flash.write(new_vpage, map_length); 225 | 226 | // Copy current values 227 | for (uint16_t i = 0; i <= map_length; i++) { 228 | read_block((uint8_t *)&value, i << 2, 4); 229 | if (value != (uint32_t)~0) { 230 | // Value found 231 | map_length = i; 232 | Flash.write(&new_vpage[i + 1], value); 233 | } 234 | } 235 | #endif 236 | 237 | // Release old page 238 | VirtualPage.release(old_vpage); 239 | 240 | // Set log position 241 | *log_start = map_length + 1; 242 | *log_end = *log_start; 243 | 244 | return new_vpage; 245 | } 246 | 247 | uint32_t *NVRAMClass::get_page() { 248 | uint32_t *vpage = VirtualPage.get(NVRAM_MAGIC); 249 | // Invalid page? 250 | if (vpage == (uint32_t *)~0) { 251 | // Allocate a new page 252 | vpage = VirtualPage.allocate(NVRAM_MAGIC, VirtualPage.length()); 253 | // Set map length to 0 254 | Flash.write(&vpage[0], 0x0); 255 | } 256 | return vpage; 257 | } 258 | 259 | uint16_t NVRAMClass::get_log_position(uint32_t *vpage) { 260 | uint16_t position_min = vpage[0] + 1; 261 | uint16_t position_max = VirtualPage.length(); 262 | 263 | // Return if page is not filled 264 | if ((vpage[0] == (uint32_t)~0) || (position_min >= position_max)) 265 | return 0; 266 | 267 | // loop until postition_min != position_max-1 268 | while (position_min != position_max - 1) { 269 | // Calculate middle between min and max 270 | uint16_t mid = position_min + ((position_max - position_min) >> 1); 271 | // Set max or min to current position 272 | if (vpage[mid] == (uint32_t)~0) 273 | position_max = mid; 274 | else 275 | position_min = mid; 276 | } 277 | 278 | return position_max; 279 | } 280 | 281 | uint8_t NVRAMClass::get_byte_from_page(uint32_t *vpage, uint16_t log_start, 282 | uint16_t log_end, uint16_t idx) { 283 | // mask matching a bit signaling wich address range is in log 284 | uint32_t address_mask = ADDR2BIT(idx); 285 | // mask matching the index address 286 | uint32_t address_match = idx << NVRAM_ADDR_POS; 287 | 288 | // Check the log backwards 289 | while (log_end > log_start) { 290 | log_end--; 291 | uint32_t value = vpage[log_end]; 292 | // end here if address map bit is not set 293 | if ((value & address_mask) == 0) 294 | break; 295 | // check address match -> update found -> return 296 | if ((value & NVRAM_ADDR_MASK) == address_match) 297 | return (uint8_t)value; 298 | } 299 | 300 | // Calculate address in the eeprom map at the beginning of a vpage 301 | uint16_t map_address = (idx >> 2); 302 | map_address++; // jump over log offset field 303 | 304 | // look at map if calculated addess before log start position 305 | if (map_address < log_start) { 306 | switch (idx % 4) { 307 | case 3: 308 | return (uint8_t)(vpage[map_address] >> 24); 309 | break; 310 | case 2: 311 | return (uint8_t)(vpage[map_address] >> 16); 312 | break; 313 | case 1: 314 | return (uint8_t)(vpage[map_address] >> 8); 315 | break; 316 | default: 317 | return (uint8_t)(vpage[map_address]); 318 | break; 319 | } 320 | } 321 | 322 | // empty cell 323 | return 0xff; 324 | } 325 | -------------------------------------------------------------------------------- /src/NVRAM.h: -------------------------------------------------------------------------------- 1 | /* 2 | NVRAM.h - Byte wise storage for Virtual Pages. 3 | Original Copyright (c) 2017 Frank Holtz. All right reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | #pragma once 20 | 21 | #include "Flash.h" 22 | #include "VirtualPage.h" 23 | #include 24 | 25 | class NVRAMClass { 26 | public: 27 | NVRAMClass(){}; 28 | void begin(){}; 29 | void end(){}; 30 | 31 | // Usable page size in bytes 32 | uint16_t length() const; 33 | 34 | // Read a block 35 | void read_block(uint8_t *dst, uint16_t idx, uint16_t n); 36 | // Read a byte 37 | uint8_t read(const uint16_t idx); 38 | 39 | // Write a block 40 | bool write_block(uint8_t *src, uint16_t idx, uint16_t n); 41 | // Write a byte 42 | bool write(const uint16_t idx, uint8_t value); 43 | 44 | // prepare a time critical write of given bytes 45 | int write_prepare(uint16_t number); 46 | 47 | // Clear log if full and prepare released pages for faster reallocation. 48 | // Plan with 0-5000ms. 49 | void clean_up(uint16_t write_preserve); 50 | 51 | private: 52 | // Return a virtual page 53 | uint32_t *get_page(); 54 | // Get actual log position 55 | uint16_t get_log_position(uint32_t *vpage); 56 | // Read a byte from page 57 | uint8_t get_byte_from_page(uint32_t *vpage, uint16_t log_start, 58 | uint16_t log_end, uint16_t idx); 59 | // switch a page 60 | uint32_t *switch_page(uint32_t *old_vpage, uint16_t *log_start, 61 | uint16_t *log_end); 62 | }; 63 | 64 | extern NVRAMClass NVRAM; 65 | -------------------------------------------------------------------------------- /src/VirtualPage.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | VirtualPage.cpp - Flash page management 3 | Original Copyright (c) 2017 Frank Holtz. All right reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #include "VirtualPage.h" 21 | 22 | VirtualPageClass VirtualPage; 23 | 24 | #ifndef VNM_VIRTUAL_PAGE_SIZE_BITS 25 | #define VNM_VIRTUAL_PAGE_SIZE_BITS 12 26 | #elif VNM_VIRTUAL_PAGE_SIZE_BITS < 12 27 | #error "VNM_VIRTUAL_PAGE_SIZE_BITS must be >= 12" 28 | #endif 29 | 30 | // check page size 31 | #ifndef VNM_VIRTUAL_PAGE_COUNT 32 | #if FLASH_ERASE_CYCLES >= 20000 33 | // use 16k of flash memory 34 | #define VNM_VIRTUAL_PAGE_COUNT 4 35 | #else 36 | // use 32k of flash memory 37 | #define VNM_VIRTUAL_PAGE_COUNT 8 38 | #endif 39 | #endif 40 | 41 | /* 42 | * How many virtual pages are skipped from top of flash 43 | */ 44 | #ifndef VNM_VIRTUAL_PAGE_SKIP_FROM_TOP 45 | #define VNM_VIRTUAL_PAGE_SKIP_FROM_TOP 0 46 | #endif 47 | 48 | /* 49 | * Calculate things around VNM_VIRTUAL_PAGE_SIZE 50 | */ 51 | #define VNM_VIRTUAL_PAGE_SIZE (1 << (VNM_VIRTUAL_PAGE_SIZE_BITS)) 52 | #define VNM_VIRTUAL_PAGE_ADDRESS_MASK (~(VNM_VIRTUAL_PAGE_SIZE - 1)) 53 | #define VNM_VIRTUAL_PAGE_ALIGN(address) \ 54 | { address = (uint32_t *)((uint32_t)address & VNM_VIRTUAL_PAGE_ADDRESS_MASK); } 55 | 56 | /* 57 | * Defines the position of status words in a page. 58 | * Offsets are defined in words! 59 | */ 60 | #ifdef FLASH_SUPPORTS_RANDOM_WRITE 61 | // use first 8 byte for magic, erase counter and status 62 | #define OFFSET_MAGIC 0 63 | #define OFFSET_ERASE_COUNTER 1 64 | #if FLASH_WRITES_PER_WORD > 2 65 | // use first 12 bytes for magic, erase counter and status 66 | #define MASK_ERASE_COUNTER 0x00FFFFFF 67 | #define OFFSET_STATUS_RELEASE_PREPARE 1 68 | #define OFFSET_STATUS_RELEASE_END 1 69 | #define METADATA_SIZE 8 70 | #define OFFSET_DATA 2 71 | #elif FLASH_WRITES_PER_WORD == 2 72 | #define MASK_ERASE_COUNTER 0x00FFFFFF 73 | #define OFFSET_STATUS_RELEASE_PREPARE 2 74 | #define OFFSET_STATUS_RELEASE_END 2 75 | #define METADATA_SIZE 12 76 | #define OFFSET_DATA 3 77 | #else 78 | // use first 12 bytes for erase counter, and magic 79 | #define OFFSET_MAGIC 1 80 | #define OFFSET_COUNTER 0 81 | #define MASK_ERASE_COUNTER 0x00FFFFFF 82 | #define OFFSET_STATUS_RELEASE_PREPARE VNM_VIRTUAL_PAGE_SIZE - 8 83 | #define OFFSET_STATUS_RELEASE_END VNM_VIRTUAL_PAGE_SIZE - 4 84 | #define METADATA_SIZE 16 85 | #define OFFSET_DATA 4 86 | #endif 87 | 88 | #define BIT_STATUS_RELEASE_PREPARE (1 << 30) 89 | #define BIT_STATUS_RELEASE_END (1 << 31) 90 | 91 | #define VNM_VIRTUAL_PAGE_DATA_SIZE (VNM_VIRTUAL_PAGE_SIZE - METADATA_SIZE) 92 | #else 93 | // use first 8 byte for magic and erase counter and last 8 byte for page release 94 | #define OFFSET_MAGIC 1 95 | #define OFFSET_ERASE_COUNTER 0 96 | #define OFFSET_DATA 2 97 | #define OFFSET_STATUS_RELEASE_PREPARE \ 98 | ((VNM_VIRTUAL_PAGE_SIZE - 8) / sizeof(uint32_t)) 99 | #define OFFSET_STATUS_RELEASE_END \ 100 | ((VNM_VIRTUAL_PAGE_SIZE - 4) / sizeof(uint32_t)) 101 | 102 | #define MASK_ERASE_COUNTER 0xFFFFFFFF 103 | 104 | #define BIT_STATUS_RELEASE_PREPARE 1 105 | #define BIT_STATUS_RELEASE_END 1 106 | 107 | #define VNM_VIRTUAL_PAGE_DATA_SIZE (VNM_VIRTUAL_PAGE_SIZE - 16) 108 | 109 | #endif 110 | 111 | uint16_t VirtualPageClass::size() const { return (VNM_VIRTUAL_PAGE_DATA_SIZE); } 112 | 113 | uint16_t VirtualPageClass::length() const { 114 | return (VNM_VIRTUAL_PAGE_DATA_SIZE / 4); 115 | } 116 | 117 | uint16_t VirtualPageClass::page_count() const { 118 | return (VNM_VIRTUAL_PAGE_COUNT - 1); 119 | } 120 | 121 | uint32_t VirtualPageClass::wear_level() { 122 | uint32_t max_erase_cycles = 0; 123 | for (int i = 1; i <= VNM_VIRTUAL_PAGE_COUNT; i++) { 124 | uint32_t erase_cycles = get_page_erase_cycles(get_page_address(i)); 125 | if (erase_cycles > max_erase_cycles) 126 | max_erase_cycles = erase_cycles; 127 | } 128 | return (uint32_t)((((uint64_t)max_erase_cycles * 10000)) / 129 | Flash.specified_erase_cycles()); 130 | } 131 | 132 | uint32_t *VirtualPageClass::get(uint32_t magic) { 133 | 134 | // Give back a page prepared for release and not closed 135 | for (int i = 1; i <= VNM_VIRTUAL_PAGE_COUNT; i++) { 136 | uint32_t *page = get_page_address(i); 137 | if ( 138 | // correct magic is set 139 | (page[OFFSET_MAGIC] == magic) && 140 | // page is in release_prepare mode 141 | ((page[OFFSET_STATUS_RELEASE_PREPARE] & BIT_STATUS_RELEASE_PREPARE) == 142 | 0) && 143 | // page is not released 144 | ((page[OFFSET_STATUS_RELEASE_END] & BIT_STATUS_RELEASE_END) > 0)) { 145 | // Return page in release process with priority 146 | return &page[OFFSET_DATA]; 147 | } 148 | } 149 | 150 | // check if a unreleased page is available 151 | for (int i = 1; i <= VNM_VIRTUAL_PAGE_COUNT; i++) { 152 | uint32_t *page = get_page_address(i); 153 | if ( 154 | // correct magic is set 155 | (page[OFFSET_MAGIC] == magic) && 156 | // page is not released 157 | ((page[OFFSET_STATUS_RELEASE_END] & BIT_STATUS_RELEASE_END) > 0)) { 158 | // return page in normal operation 159 | return &page[OFFSET_DATA]; 160 | } 161 | } 162 | 163 | return (uint32_t *)(~0); 164 | } 165 | 166 | uint32_t *VirtualPageClass::allocate(uint32_t magic) { 167 | uint32_t *return_page = (uint32_t *)(~0); 168 | uint32_t max_erase_cycles = (uint32_t)~0; 169 | 170 | // Avoid duplicate allocation of pages, look for the less used page 171 | for (int i = 1; i <= VNM_VIRTUAL_PAGE_COUNT; i++) { 172 | uint32_t *page = get_page_address(i); 173 | 174 | // Delete duplicated pages 175 | if ( 176 | // same magic 177 | (page[OFFSET_MAGIC] == magic) && 178 | // Not in release_end state 179 | ((page[OFFSET_STATUS_RELEASE_END] & BIT_STATUS_RELEASE_END) > 0) && 180 | // Not in release_prepare state 181 | (!release_started(page))) { 182 | // clear the page 183 | build_page(page, (uint32_t)~0); 184 | } 185 | 186 | uint32_t erase_cycles = get_page_erase_cycles(page); 187 | // When the page has less erase cycles and is not marked as failed 188 | if ((erase_cycles < max_erase_cycles) && (page[OFFSET_MAGIC] > 0) && 189 | ( 190 | // magic is empty 191 | (page[OFFSET_MAGIC] == (uint32_t)~0) || 192 | // marked as released 193 | ((page[OFFSET_STATUS_RELEASE_END] & BIT_STATUS_RELEASE_END) == 194 | 0))) { 195 | max_erase_cycles = erase_cycles; 196 | return_page = page; 197 | } 198 | } 199 | 200 | // return if no page was found 201 | if (return_page == (uint32_t *)~0) { 202 | return return_page; 203 | } 204 | 205 | build_page(return_page, magic); 206 | return &return_page[OFFSET_DATA]; 207 | } 208 | 209 | uint32_t *VirtualPageClass::allocate(uint32_t magic, uint32_t max_writes) { 210 | // max_writes is not implemented yet -> page is erased with every allocate 211 | (void)max_writes; 212 | return allocate(magic); 213 | } 214 | 215 | void VirtualPageClass::release_prepare(uint32_t *address) { 216 | // move pointer to beginning of the page 217 | VNM_VIRTUAL_PAGE_ALIGN(address); 218 | 219 | // Nothing to do at a empty page 220 | if (address[OFFSET_MAGIC] == (uint32_t)~0) 221 | return; 222 | 223 | if (release_started(address) == false) { 224 | // Clear bit BIT_PAGE_RELEASED 225 | Flash.write(&address[OFFSET_STATUS_RELEASE_PREPARE], 226 | address[OFFSET_STATUS_RELEASE_PREPARE] & 227 | ~BIT_STATUS_RELEASE_PREPARE); 228 | } 229 | return; 230 | } 231 | 232 | void VirtualPageClass::release(uint32_t *address) { 233 | // move pointer to beginning of the page 234 | VNM_VIRTUAL_PAGE_ALIGN(address); 235 | 236 | // Nothing to do at a empty page 237 | if (address[OFFSET_MAGIC] == (uint32_t)~0) 238 | return; 239 | 240 | // Check if status bit already cleared 241 | if ((address[OFFSET_STATUS_RELEASE_END] & BIT_STATUS_RELEASE_END) > 0) { 242 | // Clear bit BIT_PAGE_RELEASED 243 | Flash.write(&address[OFFSET_STATUS_RELEASE_END], 244 | address[OFFSET_STATUS_RELEASE_END] & ~BIT_STATUS_RELEASE_END); 245 | } 246 | return; 247 | } 248 | 249 | bool VirtualPageClass::release_started(uint32_t *address) { 250 | // move pointer to beginning of the page 251 | VNM_VIRTUAL_PAGE_ALIGN(address); 252 | 253 | return (address[OFFSET_STATUS_RELEASE_PREPARE] & 254 | BIT_STATUS_RELEASE_PREPARE) == 0; 255 | } 256 | 257 | void VirtualPageClass::fail(uint32_t *address) { 258 | // move pointer to beginning of the page 259 | VNM_VIRTUAL_PAGE_ALIGN(address); 260 | 261 | build_page(address, 0x00000000); 262 | return; 263 | } 264 | 265 | void VirtualPageClass::clean_up() { 266 | // No page found -> try to give back a page prepared for release 267 | for (int i = 1; i <= VNM_VIRTUAL_PAGE_COUNT; i++) { 268 | uint32_t *page = get_page_address(i); 269 | if ((page[OFFSET_STATUS_RELEASE_END] & BIT_STATUS_RELEASE_END) == 0) { 270 | build_page(get_page_address(i), ~0); 271 | return; // a maximum of a page is cleaned -> return 272 | } 273 | } 274 | } 275 | 276 | void VirtualPageClass::format() { 277 | for (int i = 1; i <= VNM_VIRTUAL_PAGE_COUNT; i++) { 278 | uint32_t *address = get_page_address(i); 279 | build_page(address, (uint32_t)~0); 280 | } 281 | } 282 | 283 | uint32_t *VirtualPageClass::get_page_address(uint16_t page) { 284 | return (uint32_t *)((Flash.page_count() << Flash.page_size_bits()) - 285 | ((page + VNM_VIRTUAL_PAGE_SKIP_FROM_TOP) 286 | << VNM_VIRTUAL_PAGE_SIZE_BITS)); 287 | } 288 | 289 | void VirtualPageClass::build_page(uint32_t *address, uint32_t magic) { 290 | // move pointer to beginning of the page 291 | VNM_VIRTUAL_PAGE_ALIGN(address); 292 | // get erase counter 293 | uint32_t erase_counter = get_page_erase_cycles(address); 294 | 295 | // Check if a magic is set 296 | if (address[OFFSET_MAGIC] != (uint32_t)~0) { 297 | Flash.erase(address, VNM_VIRTUAL_PAGE_SIZE); 298 | } else { 299 | // check if page is empty 300 | for (int i = OFFSET_DATA; i < (VNM_VIRTUAL_PAGE_SIZE / 4); i++) { 301 | if (address[i] != (uint32_t)~0) { 302 | Flash.erase(address, VNM_VIRTUAL_PAGE_SIZE); 303 | break; 304 | } 305 | } 306 | } 307 | 308 | // write a new page 309 | Flash.write(&address[OFFSET_MAGIC], magic); 310 | if (address[OFFSET_ERASE_COUNTER] == (uint32_t)~0) { 311 | Flash.write(&address[OFFSET_ERASE_COUNTER], 312 | erase_counter | ~MASK_ERASE_COUNTER); 313 | } 314 | } 315 | 316 | uint32_t VirtualPageClass::get_page_erase_cycles(uint32_t *address) { 317 | // Return number of cycles 318 | return ((uint32_t)address[OFFSET_ERASE_COUNTER] & 319 | (uint32_t)MASK_ERASE_COUNTER) + 320 | 1; 321 | } 322 | -------------------------------------------------------------------------------- /src/VirtualPage.h: -------------------------------------------------------------------------------- 1 | /* 2 | VirtualPage.h - Flash page management 3 | Original Copyright (c) 2017 Frank Holtz. All right reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | /* 21 | * Virtual page management: 22 | * The managed pages are organized into VirtualPage.size() sized pages. 23 | * The first and last 8 Bytes are reserved for magic number and page marking. 24 | * 25 | */ 26 | 27 | #pragma once 28 | 29 | #include "Flash.h" 30 | #include 31 | 32 | class VirtualPageClass { 33 | public: 34 | VirtualPageClass(){}; 35 | void begin(){}; 36 | void end(){}; 37 | 38 | // Usable page size in bytes 39 | uint16_t size() const; 40 | 41 | // Usable page size in data words 42 | uint16_t length() const; 43 | 44 | // Maximum number of allocatable pages 45 | uint16_t page_count() const; 46 | 47 | // Calculates rate of wear in percent*100. 48 | // Values grater than 10000 indicates exeeding the chip specification 49 | // this value is only valid for fresh controllers. 50 | uint32_t wear_level(); 51 | 52 | // Search for a page by given, uniqe magic number. 53 | // Returns a pointer to (uint32_t *)~0 if there is no page. Don't write to 54 | // this address. 55 | uint32_t *get(uint32_t magic); 56 | 57 | // Returns an address to an blank page or (uint32_t *)~0 if no space 58 | // available. 59 | // Take care about RADIO, WDT and Interrupt timing! Plan with 0-100ms 60 | uint32_t *allocate(uint32_t magic); 61 | 62 | // Search for a blank page from top of flash to do max_writes write operations 63 | // Take care about RADIO, WDT and Interrupt timing! Plan with 0-100ms 64 | uint32_t *allocate(uint32_t magic, uint32_t max_writes); 65 | 66 | // Start releasing a page. You have to allocate a new one and than release the 67 | // old page 68 | void release_prepare(uint32_t *address); 69 | 70 | // Page is marked as available for next allocation 71 | void release(uint32_t *address); 72 | 73 | // Returns true if page is in release_prepare state 74 | bool release_started(uint32_t *address); 75 | 76 | // mark a page as defect 77 | void fail(uint32_t *address); 78 | 79 | // Prepare released pages for faster reallocation. Plan with 0-100ms. 80 | void clean_up(); 81 | 82 | // Release all pages 83 | void format(); 84 | 85 | private: 86 | // convert page number 1..max_pages into an address 87 | uint32_t *get_page_address(uint16_t page); 88 | // build a page 89 | void build_page(uint32_t *address, uint32_t magic); 90 | // return number of erase cycles 91 | uint32_t get_page_erase_cycles(uint32_t *address); 92 | }; 93 | 94 | extern VirtualPageClass VirtualPage; 95 | -------------------------------------------------------------------------------- /src/avr_eeprom.h: -------------------------------------------------------------------------------- 1 | /* 2 | avr_eeprom.cpp - Emulate some avr/eeprom.h functionality. 3 | Original Copyright (c) 2017 Frank Holtz. All right reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #include 21 | 22 | #define E2END (NVRAM.length() - 1) 23 | #define eeprom_write_byte(idx, val) NVRAM.write(idx, val) 24 | #define eeprom_read_byte(idx) NVRAM.read(idx) 25 | #define eeprom_write_block(src, idx, n) \ 26 | NVRAM.write_block((uint8_t *)src, (size_t)idx, n) 27 | #define eeprom_read_block(dst, idx, n) \ 28 | NVRAM.read_block((uint8_t *)dst, (size_t)idx, n) 29 | --------------------------------------------------------------------------------