YFROBOT创客社区

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 13809|回复: 12
打印 上一主题 下一主题

ESP8266 core for Arduino应用:ESP8266 Web Server -- read DHT11

[复制链接]

签到天数: 866 天

[LV.10]以坛为家III

跳转到指定楼层
楼主
发表于 2016-8-19 17:54:19 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

在上一个帖子中我们使用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


可以尝试其他设备打开(记得连接上当前的路由)。


本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 支持支持 反对反对

该用户从未签到

沙发
发表于 2018-5-8 22:48:52 | 只看该作者
非常感谢!非常用用!!
回复 支持 反对

使用道具 举报

该用户从未签到

板凳
发表于 2018-11-6 16:54:53 | 只看该作者
非常感谢!非常用用!!
回复 支持 反对

使用道具 举报

签到天数: 22 天

[LV.4]偶尔看看III

地板
发表于 2019-5-6 17:25:33 | 只看该作者
不错,很值得学习一下
回复 支持 反对

使用道具 举报

签到天数: 3 天

[LV.2]偶尔看看I

5#
发表于 2019-6-24 07:01:28 | 只看该作者
编译出错,什么原因?

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x

点评

编译错误就这些吗?看不出来什么错误  发表于 2019-6-24 08:18
回复 支持 反对

使用道具 举报

签到天数: 3 天

[LV.2]偶尔看看I

6#
发表于 2019-6-24 21:40:10 | 只看该作者
在这个贴上下的代码,总是编译出错?不知什么原因?

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
回复 支持 反对

使用道具 举报

签到天数: 3 天

[LV.2]偶尔看看I

7#
发表于 2019-6-24 22:26:04 | 只看该作者


用的是这个8266板子,运行示例都没问题,

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
回复 支持 反对

使用道具 举报

签到天数: 866 天

[LV.10]以坛为家III

8#
 楼主| 发表于 2019-6-25 22:23:41 | 只看该作者
lvshiyu 发表于 2019-6-24 21:40
在这个贴上下的代码,总是编译出错?不知什么原因?

少文件 adafruit_sensor.h 文件,github上找下
回复 支持 反对

使用道具 举报

签到天数: 3 天

[LV.2]偶尔看看I

9#
发表于 2019-6-27 08:28:56 | 只看该作者
谢谢楼主,搞定了!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|小黑屋|联系我们|YFROBOT ( 苏ICP备20009901号-2  

GMT+8, 2024-4-25 06:08 , Processed in 0.100841 second(s), 25 queries .

Powered by Discuz! X3.1

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表