Discuss here different C compiler set ups, and compiling executables for the ESP8266
User avatar
By Jovial_Jack
#77453 I learned of the usefulness of ESP8266 with sensors like DHT22 last month so I went ahead an ordered a bunch that just arrived.

Compiling, flashing & the MQTT broker setup have gone okay. I can see the MQTT publish stream. However, something is coded incorrectly in my sketch because the stream shows DHT temp and humidity values of 0. It does correctly report wifi signal strength.

Attempting MQTT connection...connected
{"Temp":"0.00","humidity":"0.00","heatIndex":"nan","signal_strength":"-43"}


I know for certain I have the pinout connected correctly, because if I flash of the following code the sensor values successfully publish via MQTT https://github.com/bruhautomation/ESP-MQTT-JSON-Multisensor/blob/master/bruh_mqtt_multisensor_github/bruh_mqtt_multisensor_github.ino

Not being a coder, I'd greatly appreciate some extra eyes to identify what I've goofed in the sketch.

A post of my non-working code follows...

Code: Select all#include <ESP8266WiFi.h>
#include <DHT.h>
#include <PubSubClient.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <ArduinoJson.h>



/************ WIFI and MQTT INFORMATION (CHANGE THESE FOR YOUR SETUP) ******************/
#define wifi_ssid "REMOVED" //type your WIFI information inside the quotes
#define wifi_password "REMOVED"
#define mqtt_server "REMOVED"
#define mqtt_user "yourMQTTusername"
#define mqtt_password "yourMQTTpassword"
#define mqtt_port 1883



/************* MQTT TOPICS (change these topics as you wish)  **************************/
#define sensornode1_state_topic "bruh/sensornode1"
#define sensornode1_set_topic "bruh/sensornode1/set"

const char* on_cmd = "ON";
const char* off_cmd = "OFF";



/**************************** FOR OTA **************************************************/
#define SENSORNAME "sensornode1"
#define OTApassword "REMOVED" // change this to whatever password you want to use when you upload OTA
int OTAport = 8266;



/**************************** PIN DEFINITIONS ********************************************/
#define DHTPIN    D7
#define DHTTYPE   DHT22



/**************************** SENSOR DEFINITIONS *******************************************/
float diffTEMP = 0.2;
float tempValue;

float diffHUM = 1;
float humValue;

char message_buff[100];

int calibrationTime = 0;

const int BUFFER_SIZE = 300;

#define MQTT_MAX_PACKET_SIZE 512

WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(DHTPIN, DHTTYPE);



/********************************** START SETUP*****************************************/
void setup() {

  Serial.begin(115200);

  pinMode(DHTPIN, INPUT);

  Serial.begin(115200);
  delay(10);

  ArduinoOTA.setPort(OTAport);

  ArduinoOTA.setHostname(SENSORNAME);

  ArduinoOTA.setPassword((const char *)OTApassword);

  Serial.print("calibrating sensor ");
  for (int i = 0; i < calibrationTime; i++) {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("Starting Node named " + String(SENSORNAME));


  setup_wifi();

  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);


  ArduinoOTA.onStart([]() {
    Serial.println("Starting");
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  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("IPess: ");
  Serial.println(WiFi.localIP());
  reconnect();
}




/********************************** START SETUP WIFI*****************************************/
void setup_wifi() {

  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(wifi_ssid, wifi_password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}



/********************************** START CALLBACK*****************************************/
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");

  char message[length + 1];
  for (int i = 0; i < length; i++) {
    message[i] = (char)payload[i];
  }
  message[length] = '\0';
  Serial.println(message);

  if (!processJson(message)) {
    return;
  }
}



/********************************** START PROCESS JSON*****************************************/
bool processJson(char* message) {
  StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;

  JsonObject& root = jsonBuffer.parseObject(message);

  if (!root.success()) {
    Serial.println("parseObject() failed");
    return false;
  }
  return true;
}



/********************************** START SEND STATE*****************************************/
void sendState() {
  StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;

  JsonObject& root = jsonBuffer.createObject();

  root["Temp"] = (String)tempValue;
  root["humidity"] = (String)humValue;
  root["signal_strength"] = (String)WiFi.RSSI();

  char buffer[root.measureLength() + 1];
  root.printTo(buffer, sizeof(buffer));

  Serial.println(buffer);
  client.publish(sensornode1_state_topic, buffer, true);
}

/********************************** START RECONNECT*****************************************/
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(SENSORNAME, mqtt_user, mqtt_password)) {
      Serial.println("connected");
      client.subscribe(sensornode1_set_topic);
      sendState();
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}



/********************************** START CHECK SENSOR **********************************/
bool checkBoundSensor(float newValue, float prevValue, float maxDiff) {
  return newValue < prevValue - maxDiff || newValue > prevValue + maxDiff;
}


/********************************** START MAIN LOOP***************************************/
void loop() {

  ArduinoOTA.handle();
 
  if (!client.connected()) {
    // reconnect();
    software_Reset();
  }
  client.loop();

    float newTempValue = dht.readTemperature(true); //to use celsius remove the true text inside the parentheses 
    float newHumValue = dht.readHumidity();
}


/****reset***/
void software_Reset() // Restarts program from beginning but does not reset the peripherals and registers
{
Serial.print("resetting");
ESP.reset();
}
User avatar
By schufti
#77644 HI,
just some remarks as I am not using MQTT or DHT22:

a) why did you post under "Compiler Chat" ???
b) did you try
Code: Select allSerial.println(tempValue);
in sendState() to see if there is any value retruned from your sensor?
c) did you try to set
Code: Select alltempValue=33.3;
in sendState() to see if it works in general?
User avatar
By rudy
#77645 You initialized tempValue (and humValue) but you never change it.

What you do change is newTempValue

Code: Select allfloat newTempValue = dht.readTemperature(true);   
float newHumValue = dht.readHumidity();

This is what you are getting from the sensor, but not what you are sending.

Code: Select allroot["Temp"] = (String)tempValue;
root["humidity"] = (String)humValue;