Skip to content

Instantly share code, notes, and snippets.

@zdila
Last active August 21, 2018 06:17
Show Gist options
  • Save zdila/956cd52163f88e6934770db8a9bbaedf to your computer and use it in GitHub Desktop.
Save zdila/956cd52163f88e6934770db8a9bbaedf to your computer and use it in GitHub Desktop.
gas01.cpp
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "DHT.h"
const char* ssid = "mywifi";
const char* password = "mysecret";
const char* host = "192.168.0.102";
DHT dht;
void setup() {
Serial.begin(115200);
delay(10);
pinMode(A0, INPUT);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
/* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
would try to act as both a client and an access-point and could cause
network-issues with your other WiFi-devices on your WiFi-network. */
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
dht.setup(4);
}
int value = 0;
void loop() {
delay(dht.getMinimumSamplingPeriod());
float humidity = dht.getHumidity();
float temperature = dht.getTemperature();
int gas = analogRead(A0);
Serial.print(dht.getStatusString());
Serial.print("\t");
Serial.print(humidity, 1);
Serial.print("\t\t");
Serial.print(temperature, 1);
Serial.print("\t\t");
Serial.println(gas, 1);
String payload("{\"humidity:\":" + String(humidity)
+ ",\"temperature\":" + temperature + ",\"gas\":" + gas + "}");
delay(1000);
return;
delay(5000);
++value;
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 10080;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// We now create a URI for the request
Serial.print("Requesting URL: /");
// This will send the request to the server
client.print(String("POST / HTTP/1.0\r\n") +
"Host: " + host + "\r\n" +
"Content-Type: application/json\r\n" +
"Content-Length: " + payload.length() + "\r\n" +
"Connection: close\r\n\r\n");
client.print(payload);
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
// Read all the lines of the reply from server and print them to Serial
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment