醬是創客的ESP32教學主題第五篇,以Ai-Thinker安信可NodeMCU-32S(使用Arduino語言)來實作教學,本篇教學將著重於讀取/寫入資料至EEPROM記憶體,重開機資料依舊存在,通常我們會存放SSID、Password、User ID和授權碼等資訊進去EEPROM,ESP32的EEPROM有512個位置,每個位置可以放一個byte(0~255)
以下是我們今天的目標
- 開發板使用EEPROM 160個位置
- EEPROM位置0~31區域寫入iot
- EEPROM位置32~95區域寫入chosemaker
- EEPROM位置96~159區域寫入iot-chosemaker-best
- 讀取EEPROM位置0~31並合成String
- 讀取EEPROM位置32~95並合成String
- 讀取EEPROM位置96~159並合成String
Arduino 範例程式碼如下
//醬是創客 開發實作的好夥伴 #include "WiFi.h" #include <EEPROM.h> String write_ssid = "iot"; String write_password = "chosemaker"; String write_uid = "iot-chosemaker-best"; String read_ssid = ""; String read_password = ""; String read_uid = ""; void setup() { Serial.begin(115200); //宣告使用EEPROM 160個位置 EEPROM.begin(160); //清空EEPROM 0~160的位置 Serial.println("clearing eeprom"); for (int i = 0; i < 160; ++i) { EEPROM.write(i, 0); } //寫入EEPROM 0~31的位置 Serial.println("writing eeprom ssid:"); for (int i = 0; i < write_ssid.length(); ++i) { EEPROM.write(i, write_ssid[i]); Serial.print("Wrote: "); Serial.println(write_ssid[i]); } //寫入EEPROM 32~95的位置 Serial.println("writing eeprom pass:"); for (int i = 0; i < write_password.length(); ++i) { EEPROM.write(32+i, write_password[i]); Serial.print("Wrote: "); Serial.println(write_password[i]); } //寫入EEPROM 96~159的位置 Serial.println("writing eeprom uid:"); for (int i = 0; i < write_uid.length(); ++i) { EEPROM.write(96+i, write_uid[i]); Serial.print("Wrote: "); Serial.println(write_uid[i]); } //一次寫入 EEPROM.commit(); Serial.println("Reading EEPROM"); //讀取EEPROM 0~32的位置 for (int i = 0; i < 32; ++i) { read_ssid += char(EEPROM.read(i)); } Serial.print("read_ssid: "); Serial.println(read_ssid); //讀取EEPROM 32~95的位置 for (int i = 32; i < 96; ++i) { read_password += char(EEPROM.read(i)); } Serial.print("read_password: "); Serial.println(read_password); //讀取EEPROM 96~159的位置 for (int i = 96; i < 160; ++i) { read_uid += char(EEPROM.read(i)); } Serial.print("read_uid: "); Serial.println(read_uid); } void loop() { }
Arduino 序列埠監控視窗 輸出如下
clearing eeprom writing eeprom ssid: Wrote: i Wrote: o Wrote: t writing eeprom pass: Wrote: c Wrote: h Wrote: o Wrote: s Wrote: e Wrote: m Wrote: a Wrote: k Wrote: e Wrote: r writing eeprom uid: Wrote: i Wrote: o Wrote: t Wrote: - Wrote: c Wrote: h Wrote: o Wrote: s Wrote: e Wrote: m Wrote: a Wrote: k Wrote: e Wrote: r Wrote: - Wrote: b Wrote: e Wrote: s Wrote: t Reading EEPROM read_ssid: iot read_password: chosemaker read_uid: iot-chosemaker-best