平台
esp32 +vscode + platformio
引脚:
/** PIN **
* OLED:VCC --- ESP32:3.3V
* OLED:GND --- ESP32:GND
* OLED:SCL --- ESP32:D22
* OLED:SDA --- ESP32:D21
* *
* */
需要安装的库
#include "HTTPClient.h"
#include <ArduinoJson.h>
难点
网上很多都是使用http get, 很少用http post的,但是往服务器传数据一般都是post
直接上代码
#include <Arduino.h>
#include "HTTPClient.h"
#include <ArduinoJson.h>
/** PIN **
* OLED:VCC --- ESP32:3.3V
* OLED:GND --- ESP32:GND
* OLED:SCL --- ESP32:D22
* OLED:SDA --- ESP32:D21
* *
* */
const char *ssid = "LinuxRT"; //wifi名
const char *password = "88888888"; //wifi密码
const char *host = "http://192.168.31.221:5000";
const char *query_addr = "/upload_data";
WiFiClient wifi_Client;
HTTPClient http_client;
String req;
String rsp;
//Wifi连接
void setupWifi()
{
delay(10);
Serial.println("connecting WIFI");
WiFi.begin(ssid, password);
while (!WiFi.isConnected())
{
Serial.print(".");
delay(500);
}
Serial.println("Wifi connected ok!");
}
void setUpHttpClient()
{
req = (String)host + query_addr;
Serial.println(req);
if (http_client.begin(req))
{
Serial.println("HTTPclient setUp done!");
}
}
void setup()
{
Serial.begin(115200);
delay(3000);
setupWifi();
setUpHttpClient();
}
void loop()
{
uint8_t buffx[]="hello world";
// 转换为json
StaticJsonDocument<200> doc;
doc["current"] = 1;
String ouput;
// 序列化
serializeJsonPretty(doc, ouput);
// 添加http头
http_client.addHeader("Content-Type","application/json");
// 发送请求
int http_code = http_client.POST((uint8_t*)ouput.c_str(),ouput.length());
if(http_code == 200)
{
rsp = http_client.getString();
DynamicJsonDocument doc(1024);
// json序列化
deserializeJson(doc, rsp);
JsonObject obj = doc.as<JsonObject>();
// 获得key
String state = obj["state"];
Serial.println(state);
}
delay(1000);
}
flask服务器核心代码
@app.route('/upload_data',methods=['POST', 'GET'])
def hello_world1_post():
data = request.get_json()
print(data['current'])
return jsonify({"state": "ok"})
下载地址:https://github.com/KiritoGoLeon/esp_project/tree/master/esp32_current_mearuse