arduino/esp32_logger/esp32_logger.ino
2018-11-03 20:21:33 +00:00

134 lines
2.9 KiB
C++

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>
#include <WiFi.h>
#include <PubSubClient.h>
#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11
#define BMP_CS 10
#define ALT_BMP280_ADDRESS (0x76)
Adafruit_BMP280 bme; // I2C
const char* networkName = "W1ztM.4omNj";
const char* networkPswd = "MPReoa43";
const char* mqtt_server = "192.168.1.156";
const int LED_PIN = 13;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
// Connect to the WiFi network (see function below loop)
InitTempSensor();
connectToWiFi(networkName, networkPswd);
digitalWrite(LED_PIN, LOW); // LED off
client.setServer(mqtt_server, 1883);
}
void connectToWiFi(const char * ssid, const char * pwd)
{
int ledState = 0;
printLine();
Serial.println("Connecting to WiFi network: " + String(ssid));
WiFi.begin(ssid, pwd);
while (WiFi.status() != WL_CONNECTED)
{
// Blink LED while we're connecting:
digitalWrite(LED_PIN, ledState);
ledState = (ledState + 1) % 2; // Flip ledState
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void InitTempSensor() {
if (!bme.begin(ALT_BMP280_ADDRESS)) {
Serial.println("Could not find a valid BMP280 sensor, check wiring!");
int ledState = 0;
while (1) {
digitalWrite(LED_PIN, ledState);
ledState = (ledState + 1) % 2; // Flip ledState
delay(100);
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP32Client")) {
digitalWrite(LED_PIN, LOW);
Serial.println("connected");
client.subscribe("bedroomTemp");
} else {
digitalWrite(LED_PIN, HIGH);
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void printLine()
{
Serial.println();
for (int i = 0; i < 30; i++)
Serial.print("-");
Serial.println();
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()) {
reconnect();
}
client.loop();
char szEventInfo[64];
float tempReading = bme.readTemperature();
float presReading = bme.readPressure() / 100.0;
Serial.print("Temperature = ");
Serial.print(tempReading);
Serial.println(" *C");
Serial.print("Pressure = ");
Serial.print(presReading);
Serial.println(" mBar");
String strTemp = "{\"temp\":" + String(tempReading, 2) + "}";
strTemp.toCharArray(szEventInfo, 64);
Serial.print("Publish message: ");
Serial.println(szEventInfo);
client.publish("bedroomTemp", szEventInfo);
delay(10000);
}