当我将此代码加载到我的 Arduino 中时,他连接到 WiFi 并出现在我的 IP 扫描仪上。但是当我在 FireFox 中打开设备的 IP 时,什么都没有加载。( http://10.0.0.40/env ) 我的代码是否有问题,或者它不是这样工作的。我有一个读取温度和湿度的传感器。这两个值应该在我的网络中可用于 fetch()。使用 Javascript,我想在我的本地 html 页面上显示这些内容。网络凭据只是被审查。
#include <ArduinoJson.h>
#include <WiFi.h>
#include <WebServer.h>
#include <DHT.h>
#define DHTPIN 13
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
const char *ssid = "XXX";
const char *pwd = "XXX";
StaticJsonDocument<250> jsonDocument;
char buffer[250];
float temperature;
float humidity;
WebServer server(80);
void connectToWiFi() {
Serial.print("Connect to: ");
Serial.println(ssid);
WiFi.begin(ssid, pwd);
while (WiFi.status() !=WL_CONNECTED){
Serial.print(".");
delay(1000);
}
Serial.print("Connected. IP: ");
Serial.println(WiFi.localIP());
}
void setup_routing(){
server.on("/temperature", getTemperature);
server.on("/humidity", getHumidity);
server.on("/env", getEnv);
server.begin();
}
void create_json(char *tag, float value, char *unit){
jsonDocument.clear();
jsonDocument["type"] = tag;
jsonDocument["value"] = value;
jsonDocument["unit"] = unit;
serializeJson(jsonDocument, buffer);
}
void add_json_object(char *tag, float value, char *unit){
JsonObject obj = jsonDocument.createNestedObject();
obj["type"] = tag;
obj["value"] = value;
obj["unit"] = unit;
}
void read_sensor_data(void * parameter) {
for (;;) {
temperature = dht.readTemperature();
humidity = dht.readHumidity();
}
delay(2000);
}
void getTemperature(){
create_json("temperature", temperature,"°C");
server.send(200, "application/json", buffer);
Serial.println(temperature);
}
void getHumidity(){
create_json("humidty", humidity, "%");
server.send(200, "application/json", buffer);
Serial.println(humidity);
}
void getEnv() {
jsonDocument.clear();
add_json_object("temperature", temperature, "°C");
add_json_object("humidity", humidity, "%");
serializeJson(jsonDocument, buffer);
server.send(200, "application/json", buffer);
}
void setup() {
dht.begin();
Serial.begin(115200);
Serial.println(WiFi.localIP());
connectToWiFi();
setup_routing();
}
void loop() {
// put your main code here, to run repeatedly:
delay(2000);
float temperature = dht.readTemperature();
float humidty = dht.readHumidity();
}