Advertisement
Guest User

Untitled

a guest
Sep 20th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>
  3. #include <Adafruit_BMP085.h>
  4.  
  5. Adafruit_BMP085 bmp;
  6.  
  7. const char* ssid = "ArduinoSensor";
  8. const char* password = "ArduinoSensorNetwork";
  9. const char* mqttServer = "192.168.1.1";
  10. const int sleepTimeS = 60;
  11.  
  12. WiFiClient espClient;
  13. PubSubClient client(espClient);
  14.  
  15. char valTemperature[5];
  16. char valPressure[5];
  17.  
  18. void setup() {
  19. pinMode(BUILTIN_LED, OUTPUT);
  20.  
  21. Serial.begin(115200);
  22. setup_wifi();
  23.  
  24. client.setServer(mqttServer, 1883);
  25.  
  26. if (!bmp.begin()) {
  27. Serial.println("BMP085 not found");
  28. while (1) {}
  29. }
  30. }
  31.  
  32. void setup_wifi() {
  33.  
  34. Serial.println();
  35. Serial.print("Connecting to ");
  36. Serial.println(ssid);
  37.  
  38. WiFi.begin(ssid, password);
  39.  
  40. while (WiFi.status() != WL_CONNECTED) {
  41. delay(500);
  42. Serial.print(".");
  43. }
  44.  
  45. Serial.println("");
  46. Serial.println("WiFi connected");
  47. Serial.println("IP address: ");
  48. Serial.println(WiFi.localIP());
  49. }
  50.  
  51.  
  52. void reconnect() {
  53. while (!client.connected()) {
  54. Serial.print("Attempting MQTT connection...");
  55. if (client.connect("esp2", "arduino", "arduino")) {
  56. Serial.println("connected");
  57. client.publish("sensors/esp2", "hello world");
  58. } else {
  59. Serial.print("failed, rc=");
  60. Serial.print(client.state());
  61. Serial.println(" try again in 5 seconds");
  62. // Wait 5 seconds before retrying
  63. delay(5000);
  64. }
  65. }
  66. }
  67.  
  68. void loop() {
  69. if (!client.connected()) {
  70. reconnect();
  71. }
  72. client.loop();
  73.  
  74. // read temperature
  75. dtostrf(bmp.readTemperature(), 3, 1, valTemperature);
  76. String payload;
  77. payload = "sensor2 temperature=";
  78. payload += valTemperature;
  79. // publish temperature
  80. client.publish("sensors/node2/temperature", (char*) payload.c_str());
  81.  
  82. // read pressure
  83. dtostrf(bmp.readPressure(), 3, 1, valPressure);
  84. payload = "sensor2 pressure=";
  85. payload += valPressure;
  86. // publish pressure
  87. client.publish("sensors/node2/pressure", (char*) payload.c_str());
  88.  
  89. // fall into sleep
  90. ESP.deepSleep(sleepTimeS * 1000000);
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement