Skip to content
Permalink
ebc11f6e49
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
115 lines (91 sloc) 2.78 KB
#include <Arduino.h>
#include "DHT.h"
#include <iostream>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include "mqttcert.h"
WiFiClientSecure espClient;
PubSubClient mqttClient(espClient);
//DHT setup
#define DHTPIN 4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
void mqttConnect()
{
while (!mqttClient.connected())
{
Serial.print("In mqttConnect(), connecting... ");
if (mqttClient.connect(MQTT_CLIENT_ID, MQTT_USERNAME.c_str(), MQTT_PASSWORD))
{
Serial.println("...connected to mqtt server!");
Serial.print("Subscribing to topic: ");
Serial.println(MQTT_TOPIC_NAME.c_str());
// Subscribe topic with default QoS 0
// Let's just subscribe to the same feed we are publishing to, to see if our message gets recorded.
mqttClient.subscribe(MQTT_TOPIC_NAME.c_str());
}
else
{
Serial.println("...mqttConnect() failed, status code =");
Serial.println(mqttClient.state());
Serial.println("try again in 5 seconds...");
delay(5000); // Wait 5 seconds before retrying
}
}
}
void setup()
{
Serial.begin(9600);
Serial.println();
Serial.println("Hello MQTT program");
Serial.print("Attempting to connect to WiFi SSID: ");
Serial.println(WIFI_SSID);
Serial.print("Connecting");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Setting up MQTT...");
espClient.setCACert(CA_CERT);
mqttClient.setServer(MQTT_SERVER, 8883);
dht.begin();
}
void loop()
{
delay(2000);
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
if (isnan(h) || isnan(t) || isnan(f))
{
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
mqttConnect();
// String dataToSend = String(millis()); // dataToSend could be a sensor reading instead
String dataToSend = String(h, t);
Serial.print("Publishing data: ");
Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.print(F("°C "));
Serial.print(f);
Serial.print(F("°C "));
Serial.println(F("°F"));
Serial.println(dataToSend);
mqttClient.publish(MQTT_TOPIC_NAME.c_str(), dataToSend.c_str());
}