Skip to content

Instantly share code, notes, and snippets.

@screenzone
Created September 20, 2017 19:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save screenzone/7ddbb18b94b2acc2e8ad526dc503ad16 to your computer and use it in GitHub Desktop.
Save screenzone/7ddbb18b94b2acc2e8ad526dc503ad16 to your computer and use it in GitHub Desktop.
Arduino sketch for ESP8266 - Wemos D1 Mini. Read temperature from BMP180 via I2C and publish value to MQTT topic.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Adafruit_BMP085.h>
Adafruit_BMP085 bmp;
const char* ssid = "ArduinoSensor";
const char* password = "ArduinoSensorNetwork";
const char* mqttServer = "192.168.1.1";
const int sleepTimeS = 60;
WiFiClient espClient;
PubSubClient client(espClient);
char valTemperature[5];
char valPressure[5];
void setup() {
pinMode(BUILTIN_LED, OUTPUT);
Serial.begin(115200);
setup_wifi();
client.setServer(mqttServer, 1883);
if (!bmp.begin()) {
Serial.println("BMP085 not found");
while (1) {}
}
}
void setup_wifi() {
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("esp2", "arduino", "arduino")) {
Serial.println("connected");
client.publish("sensors/esp2", "hello world");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// read temperature
dtostrf(bmp.readTemperature(), 3, 1, valTemperature);
String payload;
payload = "sensor2 temperature=";
payload += valTemperature;
// publish temperature
client.publish("sensors/node2/temperature", (char*) payload.c_str());
// read pressure
dtostrf(bmp.readPressure(), 3, 1, valPressure);
payload = "sensor2 pressure=";
payload += valPressure;
// publish pressure
client.publish("sensors/node2/pressure", (char*) payload.c_str());
// fall into sleep
ESP.deepSleep(sleepTimeS * 1000000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment