Last active
June 11, 2019 18:15
-
-
Save HectorTorres/8bdc80ba109f76545efd25654953435c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "DHT.h" | |
#include <WiFiEspClient.h> | |
#include <WiFiEsp.h> | |
#include <WiFiEspUdp.h> | |
#include <PubSubClient.h> | |
#include "SoftwareSerial.h" | |
//AQUI ESCRIBIR EL NOMBRE DE LA RED DE WIFI, OJO ESCRIBIR TAL CUAL APARECE EN NUESTROS DISPOSITVOS CONSIDERANDO MAYUSCULAS Y ESPACIOS | |
#define WIFI_AP "YOUR_WIFI_AP" | |
//AQUI ESCRIBIR EL PASSWORD O CONTRASEÑA DE NUESTRA RED INALAMBRICA | |
#define WIFI_PASSWORD "YOUR_WIFI_PASSWORD" | |
//AQUI ESCRIBIR EL TOKEN DE ACCESO, ESTE ES EL QUE NOS DA THINGS BOARD | |
#define TOKEN "YOUR_ACCESS_TOKEN" | |
// DHT | |
#define DHTPIN 4 | |
#define DHTTYPE DHT22 | |
char thingsboardServer[] = "YOUR_THINGSBOARD_HOST_OR_IP"; | |
// Initialize the Ethernet client object | |
WiFiEspClient espClient; | |
// Initialize DHT sensor. | |
DHT dht(DHTPIN, DHTTYPE); | |
PubSubClient client(espClient); | |
//AQUI CONFIGURAR LOS PINES DE COMUNICACIÓN SERIAL DEL ARDUINO CON EL ESP8266 | |
//RECORDEMOS QUE ESTAMOS USANDO EL MÓDULO DE SOFTWARE SERIAL | |
SoftwareSerial soft(10, 10); // RX, TX | |
int status = WL_IDLE_STATUS; | |
unsigned long lastSend; | |
void setup() { | |
// initialize serial for debugging | |
Serial.begin(9600); | |
dht.begin(); | |
InitWiFi(); | |
client.setServer( thingsboardServer, 1883 ); | |
lastSend = 0; | |
} | |
void loop() { | |
status = WiFi.status(); | |
if ( status != WL_CONNECTED) { | |
while ( status != WL_CONNECTED) { | |
Serial.print("Attempting to connect to WPA SSID: "); | |
Serial.println(WIFI_AP); | |
// Connect to WPA/WPA2 network | |
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD); | |
delay(500); | |
} | |
Serial.println("Connected to AP"); | |
} | |
if ( !client.connected() ) { | |
reconnect(); | |
} | |
if ( millis() - lastSend > 1000 ) { // Update and send only after 1 seconds | |
getAndSendTemperatureAndHumidityData(); | |
lastSend = millis(); | |
} | |
client.loop(); | |
} | |
void getAndSendTemperatureAndHumidityData() | |
{ | |
Serial.println("Collecting temperature data."); | |
// Reading temperature or humidity takes about 250 milliseconds! | |
//AQUI PODEMOS CAMBIAR EL CODIGO SI QUEREMOS VALIDAR Y NO TENEMOS UN SENSORE DE HUMEDAD Y TEMPERATURA | |
//POR EJEMPLO PODEMOS PROBAR CON EL ADC Y UN POTENCIOMETRO ESCRIBIENDO ALGO COMO | |
//También si usamos el ADC mejor dividirlo entre 8 para bajar la resolución a 8 bits. | |
//float h = analogRead(A0)/8; | |
float h = dht.readHumidity(); | |
// Read temperature as Celsius (the default) | |
//AQUI PODEMOS CAMBIAR EL CODIGO SI QUEREMOS VALIDAR Y NO TENEMOS UN SENSORE DE HUMEDAD Y TEMPERATURA | |
//POR EJEMPLO PODEMOS PROBAR CON EL ADC Y UN POTENCIOMETRO ESCRIBIENDO ALGO COMO | |
//También si usamos el ADC mejor dividirlo entre 8 para bajar la resolución a 8 bits. | |
//float h = analogRead(A1)/8; | |
float t = dht.readTemperature(); | |
// Check if any reads failed and exit early (to try again). | |
if (isnan(h) || isnan(t)) { | |
Serial.println("Failed to read from DHT sensor!"); | |
return; | |
} | |
Serial.print("Humidity: "); | |
Serial.print(h); | |
Serial.print(" %\t"); | |
Serial.print("Temperature: "); | |
Serial.print(t); | |
Serial.print(" *C "); | |
String temperature = String(t); | |
String humidity = String(h); | |
// Just debug messages | |
Serial.print( "Sending temperature and humidity : [" ); | |
Serial.print( temperature ); Serial.print( "," ); | |
Serial.print( humidity ); | |
Serial.print( "] -> " ); | |
// Prepare a JSON payload string | |
String payload = "{"; | |
payload += "\"temperature\":"; payload += temperature; payload += ","; | |
payload += "\"humidity\":"; payload += humidity; | |
payload += "}"; | |
// Send payload | |
char attributes[100]; | |
payload.toCharArray( attributes, 100 ); | |
client.publish( "v1/devices/me/telemetry", attributes ); | |
Serial.println( attributes ); | |
} | |
void InitWiFi() | |
{ | |
// initialize serial for ESP module | |
soft.begin(9600); | |
// initialize ESP module | |
WiFi.init(&soft); | |
// check for the presence of the shield | |
if (WiFi.status() == WL_NO_SHIELD) { | |
Serial.println("WiFi shield not present"); | |
// don't continue | |
while (true); | |
} | |
Serial.println("Connecting to AP ..."); | |
// attempt to connect to WiFi network | |
while ( status != WL_CONNECTED) { | |
Serial.print("Attempting to connect to WPA SSID: "); | |
Serial.println(WIFI_AP); | |
// Connect to WPA/WPA2 network | |
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD); | |
delay(500); | |
} | |
Serial.println("Connected to AP"); | |
} | |
void reconnect() { | |
// Loop until we're reconnected | |
while (!client.connected()) { | |
Serial.print("Connecting to ThingsBoard node ..."); | |
// Attempt to connect (clientId, username, password) | |
if ( client.connect("Arduino Uno Device", TOKEN, NULL) ) { | |
Serial.println( "[DONE]" ); | |
} else { | |
Serial.print( "[FAILED] [ rc = " ); | |
Serial.print( client.state() ); | |
Serial.println( " : retrying in 5 seconds]" ); | |
// Wait 5 seconds before retrying | |
delay( 5000 ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment