一 .EEPROM
在EPS32中已經(jīng)將EEPROM棄用。對于ESP32上的新應(yīng)用程序,建議使用NVS為首選項(xiàng)。提供EEPROM是為了向后兼容現(xiàn)有的Arduino應(yīng)用程序巢块。
Arduino core for the ESP32中的EEPROM是在flash中開辟的存儲區(qū)域;
1. 調(diào)用EEPROM
調(diào)用#include <EEPROM.h>
來使用EEPROM巧号;
2. 初始化EEPROM
/*
* 初始化EEPROM
* 參數(shù): size:容量大小, 默認(rèn)4096, size為需要讀寫的數(shù)據(jù)字節(jié)最大地址+1族奢,取值1~4096;
* 返回值: 設(shè)置成功否?
*/
bool EEPROMClass::begin(size_t size)
EEPROM.begin(4096);
3. 往EEPROM中寫一個字節(jié)的值
/*
* 初始化EEPROM
* 參數(shù):
* address:地址
* val: 值
* 返回值: 無
*/
void EEPROMClass::write(int address, uint8_t val)
EEPROM.write(1,'a');
4. 真正的提交到EEPROM中保存
EEPROM.write();并不能保證斷電不丟失,需要提交.
EEPROM.commit();
5. EEPROM中讀取數(shù)據(jù)
/*
* 讀EEPROM
* 參數(shù):
* address:地址
* 返回值: 讀取的字節(jié)
*/
uint8_t EEPROMClass::read(int address){}
例
通過串口往EEPROM中寫入, 按x可以讀取EEPROM中的數(shù), 給ESP32斷一次電,再上電讀取
#include <Arduino.h>
#include <EEPROM.h>
bool flag = false;
void setup()
{
Serial.begin(115200);
EEPROM.begin(4096);
}
void loop()
{
if (Serial.available())
{
char temp = Serial.read();
if (temp != 'x')
{
EEPROM.write(1, temp);
EEPROM.commit();
Serial.print("寫入EEPROM:");
Serial.println(EEPROM.read(1));
}
else
{
Serial.print("EEPROM里的數(shù)據(jù)是:");
Serial.println(EEPROM.read(1));
}
}
}
二. NTP對時
1. NTP對時原理
連接網(wǎng)絡(luò), 從網(wǎng)絡(luò)中請求NTP對時數(shù)據(jù), 這里我們選取了阿里云的NTP服務(wù)器 ntp1.aliyun.com
此外,我們在東八區(qū), 所以應(yīng)該偏移時間 8小時
2. 初始化一個NTP服務(wù)客戶端
NTPClient(UDP& udp, const char* poolServerName, int timeOffset, int updateInterval);
/*
參數(shù):
1. udp : 創(chuàng)建的UDP連接
2. poolServerName : 服務(wù)器地址, 字符串類型 默認(rèn): time.nist.gov
3. timeOffset: 偏移時間, 默認(rèn)0, 單位秒, 北京時間需要偏移 3600*8
4. milliseconds : 更新時間間隔, 單位毫秒
*/
這里注意, 需要傳入一個UPD連接, 詳見后面的例子
3. 更新時間
timeClient.update();
4. 獲取格式化的時間
timeClient.getFormattedTime();
5.獲取時間戳(格林威治時間讀秒)
timeClient.getEpochTime();
6.獲取天(從NTP服務(wù)客戶端開啟至今的天數(shù))
程序啟動當(dāng)天是1
timeClient.getDay();
7. 獲取時分秒
Serial.println(timeClient.getHours());
Serial.println(timeClient.getMinutes());
Serial.println(timeClient.getSeconds());
8.單獨(dú)設(shè)置時間偏移
timeClient.setTimeOffset(3600*8);
9. 單獨(dú)設(shè)置更新頻率
timeClient.setUpdateInterval(1000);
10. 例子
#include <Arduino.h>
#include "WiFi.h"
#include "NTPClient.h"
const char *ssid = "anleng";
const char *password = "al77776666";
WiFiUDP ntpUDP; // 創(chuàng)建一個WIFI UDP連接
NTPClient timeClient(ntpUDP, "ntp1.aliyun.com", 60*60*8, 30*60*1000);
void setup(){
Serial.begin(115200);
WiFi.begin(ssid, password);
while ( WiFi.status() != WL_CONNECTED ) {
delay ( 500 );
Serial.print ( "." );
}
timeClient.begin();
}
void loop() {
timeClient.update();
Serial.println(timeClient.getFormattedTime());
delay(1000);
}
三. 藍(lán)牙透傳
#include <Arduino.h>
#include "BluetoothSerial.h"
BluetoothSerial bt1;
void setup()
{
Serial.begin(115200);
delay(5000);
bt1.begin("ESP32BLUE");
Serial.println("藍(lán)牙串口透傳已經(jīng)打開");
}
void loop()
{
if (Serial.available())
{
bt1.write(Serial.read());
}
if (bt1.available())
{
Serial.write(bt1.read());
}
delay(20);
}