StartCounter

はじめに

NVS(Non-volatile storage)へのデータの読み書きを行います。不揮発性のメモリ(フラッシュメモリ)に、キー・バリューペアの読み書きができます。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
/*
 ESP32 startup counter example with Preferences library.

 This simple example demonstrates using the Preferences library to store how many times
 the ESP32 module has booted. The Preferences library is a wrapper around the Non-volatile
 storage on ESP32 processor.

 created for arduino-esp32 09 Feb 2017
 by Martin Sloup (Arcao)
*/

#include <Preferences.h>

Preferences preferences;
 

Preferences型の変数(オブジェクト)preferencesを定義します。

setup()

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
void setup() {
  Serial.begin(115200);
  Serial.println();

  // Open Preferences with my-app namespace. Each application module, library, etc
  // has to use a namespace name to prevent key name collisions. We will open storage in
  // RW-mode (second parameter has to be false).
  // Note: Namespace name is limited to 15 chars.
  preferences.begin("my-app", false);

  // Remove all preferences under the opened namespace
  //preferences.clear();

  // Or remove the counter key only
  //preferences.remove("counter");

  // Get the counter value, if the key does not exist, return a default value of 0
  // Note: Key name is limited to 15 chars.
  unsigned int counter = preferences.getUInt("counter", 0);

  // Increase counter by 1
  counter++;

  // Print the counter to Serial Monitor
  Serial.printf("Current counter value: %u\n", counter);

  // Store the counter to the Preferences
  preferences.putUInt("counter", counter);

  // Close the Preferences
  preferences.end();

  // Wait 10 seconds
  Serial.println("Restarting in 10 seconds...");
  delay(10000);

  // Restart ESP
  ESP.restart();
}
 

preferences.begin()で、NVSの利用を開始します。第1引数はネームスペースで、プログラムごとに変えることで、キーの衝突を避けます。

コメントアウトされていますが、preferences.clear()は、ネームスペース内の全てのキーバリューペアを削除します。preferences.remove()で、指定したキーを削除します、

preferences.getUInt()で、値を読み取り、読み取った値をインクリメントして、preferences.putUInt()で、値を書き込みます。

その後、preferences.end()で、使用を終了します。

最後に、ESP.restart()で、ESP32を再起動します。起動するたびに、counterの値が1ずつ増えていきます。

loop()

56
void loop() {}

何もしません。

バージョン

Hardware:ESP-WROOM-32
Software:Arduino core for the ESP32 2.0.4

最終更新日

September 4, 2022

inserted by FC2 system