四、在ESP8266上模拟Form的提交动作
前面工作都正常完成后,就可以使用ESP8266模拟addlog.html,实现提交数据的处理。
代码如下:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
const char* ssid = "你的WIFI的识别ID";
const char* password = "你的WIFI接入密码";
const char* serverUrl = "http://192.168.1.96/addlog.php";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("WiFi connected!");
}
void sendFormData() {
// 准备表单数据
String formData = "name=1&info=28";
// 发送HTTP POST请求
WiFiClient client; //新添加
HTTPClient http;
http.begin(client, serverUrl);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpResponseCode = http.POST(formData);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.printf("HTTP Response code: %d\n", httpResponseCode);
Serial.println("Response: " + response);
} else {
Serial.printf("Error on sending POST: %s\n", http.errorToString(httpResponseCode).c_str());
}
// 处理可能的错误
if (httpResponseCode == 401) {
Serial.println("Unauthorized access. Please check your credentials.");
} else if (httpResponseCode == 404) {
Serial.println("Server not found. Please check the URL.");
} else if (httpResponseCode >= 500) {
Serial.println("Server error. Please try again later.");
}
http.end();
}
void loop() {
sendFormData();
delay(5000);
}代码中
String formData = "name=1&info=28";
实际只需要name一个参数,为了提示在多参数下的应用,特意追加了一个不被处理的参数info,中间用&分开。从第二个参数开始,前面都要加& 分隔,这样才能保证在服务器端被正确提取出来。
const char* serverUrl = "http://192.168.1.96/addlog.php";
上记地址,是实际响应处理用的服务器网页。
处理中每间隔5秒追加一条记录。上传到ESP8266后运行,效果如下:

回到数据库工具中刷新查看,会看到数据被一条条追加进去。

至此,在树莓派5上建立数据库,并在单片机中提交记录的处理,就全部完成了。
我要赚赏金
