zondag 17 april 2016

ESP8266 en DHT22

UPDATE: Ik was vergeten erbij te zetten dat je een library nodig hebt om makkelijk met de DHT22 te kunnen werken, ik heb dit nu toegevoegd, voor de sketch.

Nu de ESP8266 werkt, gaan we verder en ga ik de DHT22 aansluiten om te zien of ik dat ook werkend krijg.

Ik heb de DHT22 aangesloten op het ESP8266 Yellow-board.

DHT22     ESP8266
Pin 1         VCC
Pin 2         GPIO2
Pin 3         -
Pin 4         GND

In de Arduino IDE de volgende Sketch gemaakt (Aangepast op de versie van Adafruit) Heb uiteraard de OTA update mogelijkheid weer toegevoegd, dat werk lekker makkelijk en snel, tevens heb ik de temperaturr van Fahrenheit aangepast zodat hij Celcius en Fahrenheit weergeeft.

Arduino IDE

om makkelijk met de DHT22 (of DHT11) te kunnen werken in Arduino, is er door Adafruit een library gemaakt.
Als je de Aduino IDE hebt draaien sluit deze dan nu eerst af.
Deze kun je downloaden op https://github.com/adafruit/DHT-sensor-library, rechts op de pagina boven de bestanden staat een knop [Download ZIP]
Vervolgens pak je de map en bestanden in de zip uit naar de map arduino\libraries\ welke je kan vinden in je Documenten map (normaal geproken "Mijn Documenten" of "Documenten" geheten)
Nu kan je de Arduino IDE weer opstarten en de volgende sketch maken.

Sketch

/* 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 <arduinoota.h>
#include <wifiudp.h>
#include <dht.h>
#define DHTTYPE DHT22
#define DHTPIN  2
 
const char* ssid = "SSID";
const char* password = "SSID_PASSWORD";

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, temp_c;  // Values read from sensor
String webString="";     // String to display
String webString1="";     // String to display
String webString2="";     // 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() {
  webString= "Hello from the weather esp8266, read from /temp or /humidity";
  server.send(200, "text/plain", webString);
  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
 
  // 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.println("Versie: " + versie);
  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
//    webString1="Temperature: "+String((int)temp_f)+" F";   // Arduino has a hard time with float to string
//    webString2="Temperature: "+String((int)temp_c)+" C";   // Arduino has a hard time with float to string
    webString1="Temperature: "+String(temp_f)+" F";   // Arduino has a hard time with float to string
    webString2="Temperature: "+String(temp_c)+" C";   // Arduino has a hard time with float to string
    webString=webString1 + "\n" + webString2;
    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)+"%";
    webString="Humidity: "+String(humidity)+"%";
    server.send(200, "text/plain", webString);               // send to someones browser when asked
  });
  
  server.begin();
  Serial.println("HTTP server started");

  ArduinoOTA.onStart([]() {
    Serial.println("Start");
  });
  
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
    for (int i=0;i<30;i++)
      {
        analogWrite(12,(i*100) % 1001);
        delay(150);
        analogWrite(12, 0);
        analogWrite(13,(i*100) % 1001);
        delay(150);
        analogWrite(13, 0);
        analogWrite(15,(i*100) % 1001);
        delay(150);
        analogWrite(15, 0);
      }
    Serial.println("\nRebooting....");
    delay(50);
  });

  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("End Failed");
  });
  
  ArduinoOTA.begin();
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.print("Sketch size: ");
  Serial.println(ESP.getSketchSize());
  Serial.print("Free size: ");
  Serial.println(ESP.getFreeSketchSpace());
  Serial.print("Chip size: ");
  Serial.println(ESP.getFlashChipSize());
  pinMode(0, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(14, OUTPUT);
  pinMode(15, OUTPUT);
  pinMode(16, OUTPUT);
  digitalWrite(0, HIGH);
  digitalWrite(4, HIGH);
  digitalWrite(5, HIGH);
  digitalWrite(12, LOW);
  digitalWrite(13, LOW);
  digitalWrite(14, HIGH);
  digitalWrite(15, LOW);
  digitalWrite(16, HIGH);

}
 
void loop(void)
{
  server.handleClient();
  ArduinoOTA.handle();
} 
 
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(true);     // Read temperature as Fahrenheit
    temp_c = dht.convertFtoC(temp_f);
    // Check if any reads failed and exit early (to try again).
    Serial.println(String(temp_c) + " C   " + String(humidity) + " %   " + String(temp_f) + "F");
    if (isnan(humidity) || isnan(temp_f)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }
  }
}
Als deze sketch geüpload is (hoe je OTA je sketch kan uploaden kan je lezen in mijn blog bericht :
ESP8266), kan je eventueel met een FTDI-kabel en Putty zien welk IP-adres de ESP8266 heeft gekregen (Je zou ook FING - Network Tools  kunnen gebruiken op je smartphone of tablet).

Als je nu vervolgens een browser opent en gaat naar het IP-adres van de ESP8266, zie je de volgende regel "Hello from the weather esp8266, read from /temp or /humidity".
Als je nu naar IP-adres/temp of IP-adres/humidity gaat, zal je de gemeten temperatuur (Fahrenheit en Celsius) of luchtvochtigheid zien (Omdat de sketch iedere 2 seconden de waarden uitleest uit de DHT22, kan je iedere 2 seconden de pagina verversen om de nieuwe waarden te zien.


Geen opmerkingen:

Een reactie posten