概述:
1.wifi连接,扫描WiFi连接json序列化,http.get和http.post。
2.数据的存储和全局常量的flash定义。
3.文件的存储读写。
4.板子外设资源的访问:Libraries - Arduino Reference
注意:开发板未nodeMCU1.0(esp-12e)(esp8266-01s上调试的。)
1.添加arduino提供的库
代码:
#include //默认,加载WIFI头文件
#include //加载解析文件库
#include //加载http客户端库
WiFiClient espClient;
const char * ssid="wifi_name";//wifi名称
const chat * pwd="wifi_password";//WiFi 密码
HttpClient http = HttpClient(espClient,"www.baidu.com",80);//定义一个http客户端
String mes;
void setup(){
WiFi.begin(ssid.pwd);//连接wifi
if(WiFi.state()==3)
printf("连接成功");
delay(500);
int n=WiFi.scanNetworks();//扫描附近wifi
mes=JsonSerialization(n); //将扫描出的WiFi信息json序列化
printf(mes);//打印出扫描到的附近wifi
delay(100);
}
void loop(){
String contentType="application/json"; //请求内容格式
String url=""; //数据路径
httpm.get(url);//发送get请求,所有的东西都在url中
int mhttpCode = http.responseStatusCode();//阻塞响应,就是等待响应,一般10s超时跳过
String mresponse = http.responseBody(); //获得响应数据
JSONVar mtemp=JSON.parse(mresponse);//将字符串转成json格式
if (JSON.typeof(mtemp) == "undefined") {
Serial.println("Parsing input failed!");
return;
}
delay(1000);
String contentType="application/json";
String url="";
http.post(url, contentType, message); //可以发现post和get还是比较像的,数据和url不在一起
int httpCode = http.responseStatusCode();
String response = http.responseBody();
printf(response);
delay(1000);
}
总结:
非常简单,基本上全部封装到位,只需要简单的调用填参数就行。http中的get和post本质没有区别,只不过在封装的时候考虑了标志,数据的位置,服务器的解析。
2.数据的动态存储和读写
#include //这个库包含了arduino.h和eeprom.h
//可以读取1字节到32字节的数据
void setup(){
SE_EEPROM my_eeprom;//建立对象
unsigned short eeprom_size=256;//flash存储区大小
my_eeprom.SetEEPROMSize(256);//申请一个256字节的flash存储区
my_eeprom.WriteEEPROMByte(1, ver);//写1到数据区索引1
ver=my_eeprom.ReadEEPROMByte(1);//在数据区索引1读取数据
my_eeprom.WriteEEPROMStr32(64, "Hello World!!!");//写字符串到数据区索引64
Serial.println(my_eeprom.ReadEEPROMStr32(64));//从数据区索引64读取字符串
}
//这个库是毛子写的,可以发现这个库非常好用
//直接搜就可以在ide上搜到
void loop(){
}
6.全局常量定义在flash节省ram空间
//字节和整数
// 保存无符号整型
const PROGMEM uint16_t charSet[] = { 65000, 32796, 16843, 10, 11234};
// 保存字符
const char signMessage[] PROGMEM = {"I AM PREDATOR, UNSEEN COMBATANT. CREATED BY THE UNITED STATES DEPART"};
unsigned int displayInt;
char myChar;
void setup() {
Serial.begin(9600);
while (!Serial); // wait for serial port to connect. Needed for native USB
// put your setup code here, to run once:
// 读回一个2字节长整型
for (byte k = 0; k < 5; k++) {
displayInt = pgm_read_word_near(charSet + k);
Serial.println(displayInt);
}
Serial.println();
// 读回一个字符
int signMessageLength = strlen_P(signMessage);
for (byte k = 0; k < signMessageLength; k++) {
myChar = pgm_read_byte_near(signMessage + k);
Serial.print(myChar);
}
Serial.println();
}
void loop() {
// put your main code here, to run repeatedly:
}
//存储字符串
/*
PROGMEM string demo
How to store a table of strings in program memory (flash),
and retrieve them.
Information summarized from:
http://www.nongnu.org/avr-libc/user-manual/pgmspace.html
Setting up a table (array) of strings in program memory is slightly complicated, but
here is a good template to follow.
Setting up the strings is a two-step process. First, define the strings.
*/
#include
const char string_0[] PROGMEM = "String 0"; // "String 0" 等将以表格式存储
const char string_1[] PROGMEM = "String 1";
const char string_2[] PROGMEM = "String 2";
const char string_3[] PROGMEM = "String 3";
const char string_4[] PROGMEM = "String 4";
const char string_5[] PROGMEM = "String 5";
//字符串
// 把字符串放到表中.
const char *const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5};
char buffer[30]; // 确认能够存储字符串的最大长度
void setup() {
Serial.begin(9600);
while (!Serial); // wait for serial port to connect. Needed for native USB
Serial.println("OK");
}
void loop() {
/* Using the string table in program memory requires the use of special functions to retrieve the data.
The strcpy_P function copies a string from program space to a string in RAM ("buffer").
Make sure your receiving string in RAM is large enough to hold whatever
you are retrieving from program space. */
/*这段话的意思是使用字符串表编程到内存,需要特殊的函数复原数据,而strcpy_P就是把数据从内存拷贝到ram区域,保证ram区有足够的空间。*/
for (int i = 0; i < 6; i++) {
strcpy_P(buffer, (char *)pgm_read_ptr(&(string_table[i]))); // 必要的格式转换和定义
Serial.println(buffer);
delay(500);
}
}
/*ram是程序运行区,flash也就是eeprom就是程序存储区*/
/*大部分程序都是三级流水线*/
//取指:把数据从存储区取出来放到缓存区
//译码:把缓存区的数据解析,它们该去哪?有的去寄存器,有的去堆栈,有的去外设
//执行:把数据放到它应该去的地方,然后晶振一动,数据就被运行,然后pc+1
代码是官网上抄的,官网全英文,不想区去官网看英文的可以看这个。
官网地址:PROGMEM - Arduino Reference
3.文件的操作(有的开发板不支持,差一些开发板的资料)
esp32和esp8266架构支持。毛子的话看不懂,但是代码很清晰简单。
#include
#include
#include
struct Data {
uint8_t val8;
uint16_t val16;
uint32_t val32 = 12345;
char str[20];
};
Data mydata;
FileData data(&LittleFS, "/data.dat", 'B', &mydata, sizeof(mydata));
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println();
LittleFS.begin();
// прочитать данные из файла в переменную
// при первом запуске в файл запишутся данные из структуры
FDstat_t stat = data.read();
switch (stat) {
case FD_FS_ERR: Serial.println("FS Error");
break;
case FD_FILE_ERR: Serial.println("Error");
break;
case FD_WRITE: Serial.println("Data Write");
break;
case FD_ADD: Serial.println("Data Add");
break;
case FD_READ: Serial.println("Data Read");
break;
default:
break;
}
Serial.println("Data read:");
Serial.println(mydata.val8);
Serial.println(mydata.val16);
Serial.println(mydata.val32);
Serial.println(mydata.str);
}
void loop() {
// data.tick(); // вызывать тикер в loop
// можно отловить момент записи
if (data.tick() == FD_WRITE) Serial.println("Data updated!");
// запишем в данные строку из монитора порта
// а также присвоим остальным переменным случайные значения
if (Serial.available()) {
int len = Serial.readBytes(mydata.str, 20);
mydata.str[len] = '\0';
mydata.val8 = random(255);
mydata.val16 = random(65000);
Serial.println("Update");
// отложить обновление
data.update();
}
}
代码地址:GitHub - GyverLibs/FileData: Замена EEPROM для ESP8266/32 для хранения любых данных в файлах