Difference between revisions of "DHT22"

From Noisebridge
Jump to: navigation, search
(temp)
 
(client/server)
 
Line 1: Line 1:
 
Connects to specified network with static ip configuration and hosts a basic web page to show current sensor information, you can also query with <code>/data</code> to get a "|" delimeted plain text version.
 
Connects to specified network with static ip configuration and hosts a basic web page to show current sensor information, you can also query with <code>/data</code> to get a "|" delimeted plain text version.
 +
 +
== MicroPython Client Code ==
 +
 +
<pre>
 +
import machine
 +
import ssd1306
 +
import socket
 +
import network
 +
from time import sleep_ms
 +
 +
s = network.WLAN(network.STA_IF)
 +
 +
btn = machine.Pin(0, machine.Pin.IN)
 +
 +
i2c = machine.I2C(-1, machine.Pin(4), machine.Pin(5))
 +
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
 +
 +
oled.text("nubcore (blue)", 0, 0)
 +
oled.show()
 +
 +
temp_data = ""
 +
 +
def http_get(url):
 +
        global temp_data, oled
 +
        oled.fill(0)
 +
        oled.text("Querying...", 0, 0)
 +
        oled.show()
 +
        _, _, host, path = url.split('/', 3)
 +
        addr = socket.getaddrinfo(host, 80)[0][-1]
 +
        s = socket.socket()
 +
        s.connect(addr)
 +
        s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
 +
        while True:
 +
                data = s.recv(100)
 +
                if data:
 +
                        print(str(data, 'utf8'), end='')
 +
                        temp_data = str(data, 'utf8')
 +
                else:
 +
                        break
 +
        s.close()
 +
 +
def updateTemp():
 +
        global temp_data, oled
 +
        #http_get("http://10.20.0.77/data")
 +
        http_get("http://10.10.10.222/data")
 +
        oled.fill(0)
 +
        oled.text(temp_data, 0, 0)
 +
        oled.show()
 +
 +
def main():
 +
        global btn, oled, temp_data
 +
        while 1:
 +
                if btn.value() == 0:
 +
                        # do button
 +
                        updateTemp()
 +
                sleep_ms(10)
 +
 +
main()
 +
</pre>
 +
 +
 +
== Arduino Server Code ==
  
 
<pre>
 
<pre>

Latest revision as of 02:33, 12 January 2018

Connects to specified network with static ip configuration and hosts a basic web page to show current sensor information, you can also query with /data to get a "|" delimeted plain text version.

MicroPython Client Code[edit]

import machine
import ssd1306
import socket
import network
from time import sleep_ms

s = network.WLAN(network.STA_IF)

btn = machine.Pin(0, machine.Pin.IN)

i2c = machine.I2C(-1, machine.Pin(4), machine.Pin(5))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)

oled.text("nubcore (blue)", 0, 0)
oled.show()

temp_data = ""

def http_get(url):
        global temp_data, oled
        oled.fill(0)
        oled.text("Querying...", 0, 0)
        oled.show()
        _, _, host, path = url.split('/', 3)
        addr = socket.getaddrinfo(host, 80)[0][-1]
        s = socket.socket()
        s.connect(addr)
        s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
        while True:
                data = s.recv(100)
                if data:
                        print(str(data, 'utf8'), end='')
                        temp_data = str(data, 'utf8')
                else:
                        break
        s.close()

def updateTemp():
        global temp_data, oled
        #http_get("http://10.20.0.77/data")
        http_get("http://10.10.10.222/data")
        oled.fill(0)
        oled.text(temp_data, 0, 0)
        oled.show()

def main():
        global btn, oled, temp_data
        while 1:
                if btn.value() == 0:
                        # do button
                        updateTemp()
                sleep_ms(10)

main()


Arduino Server Code[edit]

// DHT code adapted from code written by ladyada, public domain

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

#include "DHT.h"

#define DHTPIN 5     // sensor data pin D1 == 5
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321


const char* ssid = "nubnano";
const char* password = "1234567890";
const String esp-name = "blue-esp";

IPAddress ip(10, 10, 10, 222);
IPAddress gateway(10, 10, 10, 1);
IPAddress subnet(255, 255, 255, 0);

ESP8266WebServer server(80);

const int led = 13;

// DHT Params
DHT dht(DHTPIN, DHTTYPE);
unsigned long nextTime = 1;

float humidity = dht.readHumidity();
float celsius = dht.readTemperature();
float fahrenheit = dht.readTemperature(true);

void handleRoot() {
  String response = "";
  
  digitalWrite(led, 1);

  response += "Humidity: " +  String(humidity) + "%<br/>";
  response += "Temperature: " + String(celsius) + "C/" + String(fahrenheit) + "F<br/>";
  response += "Garden Mesh sensor node";
  server.send(200, "text/html", response);
  
  digitalWrite(led, 0);
}

void handleData() {
  String response = "";
  
  digitalWrite(led, 1);

  response += String(humidity) + "|";
  response += String(celsius) + "|" + String(fahrenheit);
  server.send(200, "text/plain", response);
  
  digitalWrite(led, 0);
}

void handleNotFound(){
  digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  digitalWrite(led, 0);
}

void setup(void){
  pinMode(led, OUTPUT);
  digitalWrite(led, 0);
  Serial.begin(115200);

  WiFi.config(ip, gateway, subnet);
  WiFi.begin(ssid, password);
  
  
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin(esp-name)) {
    Serial.println("MDNS responder started");
    MDNS.addService("http", "tcp", 80);
  }

  server.on("/", handleRoot);

  server.on("/data", handleData);

  server.on("/inline", [](){
    server.send(200, "text/plain", "this works as well");
  });

  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started");

  Serial.println("Initialize DHT22 Sensor");
  dht.begin();
}

void sampleDHT() {
  humidity = dht.readHumidity();
  celsius = dht.readTemperature();
  fahrenheit = dht.readTemperature(true);
  
  // Check if any reads failed and exit early (to try again).
  if (isnan(humidity) || isnan(celsius) || isnan(fahrenheit)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  nextTime = millis() + 2000;
}

void loop(void) {
  server.handleClient();

  if (millis() > nextTime)
    sampleDHT();
}