Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement