Advertisement
baldengineer

MQTT print a float

Feb 16th, 2016
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 KB | None | 0 0
  1.  
  2. #include <ESP8266WiFi.h>
  3. #include <PubSubClient.h>
  4. #define mqtt_server "192.168.1.148"
  5. #define mqtt_user "your_username"
  6. #define mqtt_password "your_password"
  7. const char* ssid = "Tower of Power";
  8. const char* password = "m00m00m00";  
  9.  
  10.  
  11. #include "DHT.h"
  12. // DHT 11 sensor
  13. #define DHTPIN 2
  14. #define DHTTYPE DHT11
  15. DHT dht(DHTPIN, DHTTYPE, 15);
  16. WiFiClient wifiClient;
  17. PubSubClient client(wifiClient);
  18.  
  19. void setup() {
  20.   Serial.begin(115200);
  21.   Serial.print("Connecting to ");
  22.   Serial.println(ssid);
  23.   WiFi.begin(ssid, password);
  24.   while (WiFi.status() != WL_CONNECTED) {
  25.     delay(500);
  26.     Serial.print(".");
  27.   }
  28.   Serial.println("");
  29.   Serial.println("WiFi connected");
  30.   Serial.println("IP address: ");
  31.   Serial.println(WiFi.localIP());
  32.   client.setServer(mqtt_server, 1883);
  33.   client.connect(mqtt_server);
  34.   dht.begin();
  35. }
  36.  
  37. void loop() {
  38.   float h = dht.readHumidity();
  39.   float t = dht.readTemperature();
  40.   if (isnan(h) || isnan(t)) {
  41.     Serial.println("Failed to read from DHT sensor!");
  42.     return;
  43.   }
  44.  
  45.   // create a temporary buffer (aka string)
  46.   char msg[16];
  47.   // format the float into the string buffer
  48.   sprintf(msg, "%0.2f", h);
  49.   // publish the temp buffer, containing our float as a string
  50.   client.publish("chicken1/humidity", msg);
  51.   Serial.print("Humdity: ");
  52.   Serial.println(msg);
  53.  
  54.  
  55.   // do the same thing for temperature
  56.   sprintf(msg, "%0.2f", t);
  57.   client.publish("chicken1/temp", msg);
  58.   Serial.print("Temp: ");
  59.   Serial.println(msg);
  60.  
  61.   delay(2000);
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement