the code has been hashed together from several sources however but was working
Code: Select all
#include <Adafruit_Sensor.h>
//#include "DHT.h"
#include <WiFi.h>
#include <PubSubClient.h>
#include "SparkFunHTU21D.h"
//Create an instance of the object
HTU21D myHumidity;
const char* ssid = "skynet";
const char* password = "Sexyfrog9919";
const char* mqttServer = "192.168.0.196";
const int mqttPort = 1883;
const char* mqttUser = "ojosbourne";
const char* mqttPassword = "Skingsking9919";
#define temperature_topic "topic/temp" //Topic temperature
#define humidity_topic "topic/humid" //Topic humidity
//#define debug_topic "debug" //Topic for debugging
//here we use pin IO23 of ESP32 to read data
//#define DHTPIN 14
//our sensor is DHT22 type
//#define DHTTYPE DHT22
//create an instance of DHT sensor
//DHT dht(DHTPIN, DHTTYPE);
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
//void setup() (
// connect to wifi
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(200);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
// connect to mqtt
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP32Client", mqttUser, mqttPassword )) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(200);
}
//}
//Serial.begin(115200);
//Serial.println("DHT22 sensor!");
//call begin to start sensor
//dht.begin();
Serial.println("HTU21D Example!");
myHumidity.begin();
}
}
void loop() {
float h = myHumidity.readHumidity();
float t = myHumidity.readTemperature();
//use the functions which are supplied by library.
//float h = dht.readHumidity();
// Read temperature as Celsius (the default)
//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 htu21d sensor!");
return;
}
// print the result to Terminal
//client.publish(humidity_topic, (h));
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
// client.publish(temperature_topic, (t));
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" *C ");
// Publish values to MQTT topics
client.publish(temperature_topic, String(t).c_str(), true); // Publish temperature on mosohomes/temp1
//if ( debug ) {
Serial.println("Temperature sent to MQTT.");
//}
delay(200); //some delay is needed for the mqtt server to accept the message
client.publish(humidity_topic, String(h).c_str(), true); // Publish humidity on mosohomes/humid1
//if ( debug ) {
Serial.println("Humidity sent to MQTT.");
//}
//we delay a little bit for next read
delay(10000);
}