ESP8266 家庭自动化项目中文版目录
有两个函数返回 File 对象,SPIFFS.open 和 dir.OpenFile,这个 File 对象允许我们读取字节,查看文件,获取文件中的当前位置,获取文件名或文件大小。以下是 File 对象使用的各种函数:
- close:关闭文件。 调用 close() 函数后,不应对 File 对象执行任何其他操作:
file_name.close();
- name:返回当前文件的名称:
String name = my_file.name();
- position: Returns the current position in the file in bytes. You can use it if you are storing same size data and iterare in the file
- position:以字节为单位返回文件中的当前位置。如果要在文件中存储相同大小的数据和迭代,则可以使用它。
- seek: 允许您移动到文件中。 它需要两个参数; 一个是文件中的偏移量,另一个是模式。 成功时返回true,否则返回false
- 参数模式可以具有与C函数中 fseek() 相同的值:
- 如果 mode 是 SeekSet,则为从头开始偏移字节设置位置
- 如果 mode 是 SeekCur,则从当前位置移动偏移字节
- 如果 mode 是 SeekEnd,则为偏离文件末尾的字节设置位置
- size: 以字节为单位获取当前文件大小:
Serial.println(my_file.size());
作为一个例子,让我们创建一个文件,在其中写入内容,并阅读所写的内容;如果 GPIO 4 接通 GND ,它将格式化闪存。
如果您还记得,需要包含 FS.h 才能访问 SPIFFS 对象:
#include "FS.h"
将 interruptPin 设置为值 4,并将 interruptCounter 实例化为零:
const byte interruptPin = 4;
volatile byte interruptCounter = 0;
如果 GPIO 接通到GND,将调用此函数。在函数内部将递增 interruptCounter 并将在 loop() 函数中验证其值。尽量不要在中断层次分配内存,这是一个会导致灾难的操作方式:
void handleInterrupt() {
interruptCounter++;
}
在 setup() 中,我们将 GPIO 4 设置为输入引脚,并使用 attacheInterrupt 函数进行 FALLING(VCC 至 GND)以触发handleInterrupt 函数。接下来我们打开 my_file.txt 并在其中写一条消息。文件关闭后,它将再次打开,但现在它处于读取模式,它将读取其中的内容:
void setup() {
Serial.begin(115200);delay(10);
// GPIO 4 格式化SPIFFS
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin) , handleInterrupt, FALLING);
if(SPIFFS.begin()) {
Serial.println(F("File system was mounted."));
//打开文件写
File my_file = SPIFFS.open("/my_file.txt", "w+");
if (!my_file) {
Serial.println("file open failed");
}
Serial.println(F("Writing to SPIFFS"));
//print something to my_file.txt
my_file.println("SPIFFS is cool!");
/ /现在关闭文件
my_file.close();
// 打开文件进行阅读。现在我可以使用其他 File 对象
File object
File f = SPIFFS.open("/my_file.txt", "r");
if (!f)
{
Serial.println(F("Failed to open my_file.txt"));
}
// 现在阅读文件内容
String s=f.readStringUntil('n');
Serial.println(s);
//现在关闭文件
f.close();
}
else
{
Serial.println(F("Failed to mount SPIFFS. Restart"));
ESP.restart();
}
}
在 loop 函数中,我们检查 intrruptCounter 值,如果它大于零,它将 格式化 文件系统并重新启动 ESP:
void loop()
{
if(interruptCounter>0)
{
interruptCounter--;
Serial.println(F("Formating the file system. . . Please wait!"));
SPIFFS.format();
Serial.println(F("Done formating the file System"));
ESP.restart();
}
}
串行输出将显示从文件读取的内容,以及格式化消息和之后的新重新启动,如以下屏幕截图所示:
现在您已经设法了解SPIFFS,我确信您将在所有项目中使用它,因为它是保存配置数据或存储各种信息(如传感器读数)的一种非常方便的方法,尤其是你靠电池运行的设备。您可以将所有读数以JSON格式存储在文件中,并且每天一次连接到Wi-Fi,读取文件,并立即发送所有数据。
经过这个漫长但有用的介绍之后,让我们回到我们的项目,一个使用ESP8266的恒温器。为了完成这一点,除了ESP8266,我们还需要:
- 温度感应器
- 继电器板