hi everyone, I'm doing a project that consists on read data from a DHT11 and I need to send it to the module ESP8266 to be upload to thingspeak.
the question is, do I am doing the things ok?. I don't know if the ESP8266 can read the data correctly or the arduino can't send it right.
for the Serial comunication I use: SoftwareSerial library.
please, I any one can help me I'll be really grateful
Here is the code From Arduino
/* Arduino+esp8266 thingSpeak
* name = "Write temperature and humidity to Thingspeak channel"
*/
// Code to use SoftwareSerial
#include <SoftwareSerial.h>
#define RX 2// connect 2
#define TX 3// connect 3
SoftwareSerial espSerial(RX,TX); // arduino RX pin=2 arduino TX pin=3
#include <Adafruit_Sensor.h>
#include <DHT.h>
//Attention: For new DHT11 version libraries you will need the Adafruit_Sensor library
#define DHTPIN 6 // Connect the signal pin of DHT11 sensor to digital pin 6
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
boolean DEBUG=true;
//=================Function to send data to ESP8266==============
boolean thingSpeakWrite(int temp, int hum){
if(espSerial.find("Error")){
if (DEBUG) Serial.println("error");
return false;
}
// Send value to ESP via Serial
espSerial.write(temp);
if(espSerial.find(">")){
}
else{
if (DEBUG) Serial.println("close");
return false;
}
return true;
}================================== setup
void setup() {
DEBUG=true; // enable debug serial
dht.begin(); // Start DHT sensor
Serial.begin(9600);
// set the data rate for the SoftwareSerial port
espSerial.begin(9600); // enable software serial
if (DEBUG) Serial.println("Setup completed");
}
// ============================= loop
void loop() {
// Read sensor values
int temp = dht.readTemperature();
int humidity = dht.readHumidity();
delay(100);
if ((isnan(temp)) || (isnan(humidity))) {
if (DEBUG) Serial.println("Failed to read from DHT");
}
else {
if (DEBUG) Serial.println("Temp="+String(temp)+" *C");
if (DEBUG) Serial.println("Humidity="+String(humidity)+" %");
thingSpeakWrite(temp,humidity); // Write values to thingspeak
}
// delay 1 second to update data to ESP,
delay(1000);
}
Here is the code of ESP8266
/*
* This sketch sends data via HTTP GET requests to thingspeak service every 30 SECONDS
* You have to set your wifi credentials and your thingspeak key.
*/
#include <ESP8266WiFi.h>
extern "C" {
#include "user_interface.h"
}
const char* ssid = "XXXXXXXXXX";
const char* password = "XXXXXXX";
const char* host = "api.thingspeak.com";
const char* thingspeak_key = "XXXXXXXXXXXXXXXX";
void setup() {
Serial.begin(9600);
delay(10);
// We start by connecting to a WiFi network
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");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
int recived = 0;
// read the data until pause:
if(Serial.available()){
while(Serial.available()>0)
{
//change value on case receive data
recived = Serial.read();
}
}
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
/*URL for update to thingspeak*/
String url = "/update?key=";
url += thingspeak_key;
url += "&field1=";
url += recived;
delay(100);
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
// 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("Uploading data. Waiting to recibe...");
// go to deepsleep for 30 seconds
delay(30000);
}
The problem is that the ESP always upload the number 0. That means the variable "recived" never change.
EduardoGtzL:
hi everyone, I'm doing a project that consists on read data from a DHT11 and I need to send it to the module ESP8266 to be upload to thingspeak.
All that just for a DHT11.........
It looks like th Arduino is redundant and the ESP8266 should be able to do all that by itself.
What type does the write() method take? What type are you giving it?
Are you expecting negative temperatures? Negative humidity values?
Are you expecting temperatures above 255 degrees? More than 255% relative humidity?
If you said no to all of these int is NOT the correct type to be using.
if(Serial.available()){
while(Serial.available()>0)
{
//change value on case receive data
recived = Serial.read();
}
}
You are sending one byte. Why do you have a while loop to read all one of them?
And, why on earth do you connect, and do all that other crap unless you HAVE received serial data?
I give it an INT type...
And the answer for that questions is NOT, So what could be the correct form to be using?
I'm new at arduino but that's right, if I only send one byte I don't need a loop to read it
the last one is a Great thing to implement, thanks!.
Connection is wrong. Dht needs 4.7k resistor as per datasheet esp needs separate power supply and resistors too.
In code you can use int if you want but as guys said not to waste memory of 2 byte use 1byte storage i.e. byte or char. Then end marker is needed or else you will get not what you are expecting. Search forum for other esp threads where questions were answered.
surepic:
Connection is wrong. Dht needs 4.7k resistor as per datasheet esp needs separate power supply and resistors too.
In code you can use int if you want but as guys said not to waste memory of 2 byte use 1byte storage i.e. byte or char. Then end marker is needed or else you will get not what you are expecting. Search forum for other esp threads where questions were answered.
Thank you so much!
Exactly the connections were wrong, But actually what I did was altrnate between RX of ESP with TX of ESP, and thats it, now works perfectly and ESP can receive data.
I was looking for the end marker as you said, I found a code that uses start'<' and end '>' markers. I'm very happy that finally it works.
/* Invernadero autimatizado IoT
* Arduino que enviara datos a ESP8266 y los subira a thingspeak
* Manda los datos de la temperatura y la humedad del aire
*/
// codigo para usar con el software serial
#include <SoftwareSerial.h>
#define RX 2// pin 2 del arduino
#define TX 3// pin 3 del arduino
SoftwareSerial espSerial(RX,TX);// arduino RX pin=2 arduino TX pin=3
//ESP RX - TX arduino
//ESP TX - RX arduino
//Libreria para que funcione el DHT11
#include <Adafruit_Sensor.h>
#include <DHT.h>
#define DHTPIN 12 //conectar la señal del sensor DHT11 al pin digital 12
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
boolean DEBUG=true;
//======================Funcion que envia datos al ESP8266================================
boolean espWrite(int temp, int hum){
String espsend = "<";
espsend += hum;
espsend += ",";
espsend += temp;
espsend += ">";
Serial.print("recibi: ");
Serial.println(espsend);
// Enviar la temperatura y humedad al ESP
espSerial.print(espsend);
if(espSerial.find(">")){
}
else{
if (DEBUG) Serial.println("CLOSE");
return false;
}
return true;
}
//============================== Setup ==================
void setup() {
DEBUG=true; // habilitar debug serial
dht.begin(); // Inicia el sensor DHT
Serial.begin(9600);
// asignar el rango de datos para el puerto de software serial
espSerial.begin(9600); // Habilita el software serial
if (DEBUG) Serial.println("Setup completado");
}
// ============================= Loop =====================
void loop() {
// Leer los datos del sensor
int temp = dht.readTemperature();
int hume = dht.readHumidity();
if ((isnan(temp)) || (isnan(hume))) {
if (DEBUG) Serial.println("Failed to read from DHT");
}
else {
// imprime los datos en el monitor serial
if (DEBUG) Serial.print("Temp= ");
if (DEBUG) Serial.println(temp);
if (DEBUG) Serial.print("Humidity= ");
if (DEBUG) Serial.println(hume);
// Envia los datos a la funcion para ser mandados al ESP
espWrite(temp,hume);
}
// delay 5 second to update data to ESP,
delay(5000);
}
ESP8266-01 CODE
/*
* Este sketch recibe datos del arduino via Serial y
* envia datos via HTTP GET requests hacia el servicio de thingspeak cada 30 SEGUNDOS
*/
#include <ESP8266WiFi.h>
extern "C" {
#include "user_interface.h"
}
// Declarar el nombre de la red y su contraseña
const char* ssid = "XXXXXXXXXXX";
const char* password = "XXXXXX";
//Declarar el Host de thingspeak y la llave del canal
const char* host = "api.thingspeak.com";
const char* thingspeak_key = "XXXXXXXXXXXX";
const byte numChars = 20;
char receivedChars[numChars];
boolean newData = false;
int integer1 = 0;
int integer2 = 0;
void setup() {
Serial.begin(9600);
delay(10);
// Comienza conectandose a la red WIFI
Serial.print("Conectandose a ");
Serial.println(ssid);
WiFi.begin(ssid, password);
//Esperar hasta que el ESP se conecte a la red
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
//imprimir la IP del ESP
Serial.println("WiFi conectado");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
//contador
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
byte rc;
char * strtokIndx;
/*Verificar si hay algun dato en la cominicacion Serial*/
//if(Serial.available() > 0){
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (recvInProgress == true) {
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
recvInProgress = false;
ndx = 0;
newData = true;
/*separate the data*/
strtokIndx = strtok(receivedChars,",");
integer1 = atoi(strtokIndx);
strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
integer2 = atoi(strtokIndx); // convert this part to an integer
}
}
else if (rc == startMarker) {
recvInProgress = true;
}
}
if (newData == true) {
newData = false;
Serial.print("conectandose a ");
Serial.println(host);
// Usar la clase de WiFiClient para crear una conection TCP
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
/*URL para actualizar el canal de thingspeak*/
String url = "/update?key=";
url += thingspeak_key;
url += "&field1=";
url += integer1;
url += "&field2=";
url += integer2;
delay(100);
Serial.print(" URL: ");
Serial.println(url);
// Esto enviara la url al servidor de thingspeak
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
}
Serial.println("Esperando a recibir datos...");
// Espera 30 segundos para realizar nuevamente la operacion
delay(30000);
}