在上一个帖子中我们使用ESP8266 AP模式下,设备直接连接到ESP8266实现访问Web页面( 帖子地址)。 在本教程中使用的广播是使用ESP8266 Web服务器代码和响应网络请求(如在浏览器或Web客户端)返回温湿度数据(以REST类型的格式)。 也就是说任何和ESP8266连接上相同的路由的设备都可以享受到该服务(不是远程哦,局域网内)!根据下面的电路图,连接好DHT11与ESP8266 Wifi模块:
烧写程序代码:
[C] 纯文本查看 复制代码 /* DHTServer - ESP8266 Webserver with a DHT sensor as an input
Based on ESP8266Webserver, DHTexample, and BlinkWithoutDelay (thank you)
Version 1.0 5/3/2014 Version 1.0 Mike Barela for Adafruit Industries
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <DHT.h>
#define DHTTYPE DHT11
#define DHTPIN 4
const char* ssid = "YFROBOT";
const char* password = "yfrobot2016";
ESP8266WebServer server(80);
// Initialize DHT sensor
// NOTE: For working with a faster than ATmega328p 16 MHz Arduino chip, like an ESP8266,
// you need to increase the threshold for cycle counts considered a 1 or 0.
// You can do this by passing a 3rd parameter for this threshold. It's a bit
// of fiddling to find the right value, but in general the faster the CPU the
// higher the value. The default for a 16mhz AVR is a value of 6. For an
// Arduino Due that runs at 84mhz a value of 30 works.
// This is for the ESP8266 processor on ESP-01
DHT dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266
float humidity, temp_f; // Values read from sensor
String webString=""; // String to display
// Generally, you should use "unsigned long" for variables that hold time
unsigned long previousMillis = 0; // will store last temp was read
const long interval = 2000; // interval at which to read sensor
void handle_root() {
server.send(200, "text/plain", "Hello from the weather esp8266, read from /temp or /humidity");
delay(100);
}
void setup(void)
{
// You can open the Arduino IDE Serial Monitor window to see what the code is doing
Serial.begin(115200); // Serial connection from ESP-01 via 3.3v console cable
dht.begin(); // initialize temperature sensor
WiFi.mode(WIFI_STA);
// Connect to WiFi network
WiFi.begin(ssid, password);
Serial.print("\n\r \n\rWorking to connect");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("DHT Weather Reading Server");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
server.on("/", handle_root);
server.on("/temp", [](){ // if you add this subdirectory to your webserver call, you get text below :)
gettemperature(); // read sensor
webString="Temperature: "+String((int)temp_f)+" C"; // Arduino has a hard time with float to string
server.send(200, "text/plain", webString); // send to someones browser when asked
});
server.on("/humidity", [](){ // if you add this subdirectory to your webserver call, you get text below :)
gettemperature(); // read sensor
webString="Humidity: "+String((int)humidity)+"%";
server.send(200, "text/plain", webString); // send to someones browser when asked
});
server.begin();
Serial.println("HTTP server started");
}
void loop(void)
{
server.handleClient();
}
void gettemperature() {
// Wait at least 2 seconds seconds between measurements.
// if the difference between the current time and last time you read
// the sensor is bigger than the interval you set, read the sensor
// Works better than delay for things happening elsewhere also
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval) {
// save the last time you read the sensor
previousMillis = currentMillis;
// Reading temperature for humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
humidity = dht.readHumidity(); // Read humidity (percent)
temp_f = dht.readTemperature(); // Read temperature as Celsius
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temp_f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
}
}
更改程序中的 ssid 及 password为自己的路由配置!
程序下载地址:
使用到的DHT库:
程序烧写完成后,打开串口,找到IP地址,下图红框中:
在手机、电脑或者其他设备上,打开改地址,下图为电脑浏览器截图:
获取当前环境温度:
获取当前环境湿度
下面再送一个控制LED例程(无需电路,ESP-12E),与上面的例程有些区别:
[C] 纯文本查看 复制代码 /*
This sketch demonstrates how to set up a simple HTTP-like server.
The server will set a GPIO pin depending on the request
http://server_ip/gpio/0 will set the GPIO2 low,
http://server_ip/gpio/1 will set the GPIO2 high
server_ip is the IP address of the ESP8266 module, will be
printed to Serial when the module is connected.
*/
#include <ESP8266WiFi.h>
#define LED 2
const char* ssid = "YFROBOT";
const char* password = "yfrobot2016";
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);
void setup() {
WiFi.mode(WIFI_STA);
Serial.begin(115200);
delay(10);
// prepare GPIO2
pinMode(LED, OUTPUT);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.println(WiFi.localIP());
digitalWrite(LED, 1); // LOW
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
delay(10);
// Match the request
int val = 1;
if (req.indexOf("/gpio/0") != -1)
val = 1;
else if (req.indexOf("/gpio/1") != -1)
val = 0;
else {
Serial.println("invalid request");
client.stop();
return;
}
// Set GPIO2 according to the request
digitalWrite(LED, val);
// Prepare the response
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
s += (val) ? "low" : "high";
s += "</html>\n";
// Send the response to the client
client.print(s);
delay(1);
Serial.println("Client disonnected");
// The client will actually be disconnected
// when the function returns and 'client' object is detroyed
}
提示:需要更改程序中的 ssid 及 password。
程序下载:
和上面的操作步骤相似,打开串口找到IP地址,这里依然是:"192.168.1.117"。
在浏览其中输入:
http://192.168.1.117/gpio/0 -- 关闭LED
http://192.168.1.117/gpio/1 -- 点亮LED
可以尝试其他设备打开(记得连接上当前的路由)。
|