#include <Wire.h>
#include <SPI.h>
#include <Adafruit_BMP280.h>
#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 10
#define SEALEVELPRESSURE_HPA (1013.25)
#include "BC26.h"
//Adafruit_BMP280 bmp; // I2C
Adafruit_BMP280 bmp(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
unsigned long delayTime;
/*這一段是偵測電池電量的變數宣告*/
int analogInPin = A4; // Analog input pin
int sensorValue; // Analog Output of Sensor
float calibration = 0.67; // Check Battery voltage using multimeter & add/subtract the value
int bat_percentage;
float voltage;
/*這一段是偵測電池電量的變數宣告*/
void setup() {
Serial.begin(9600);
mySerial.begin(9600);
delay(500);
while(!Serial); // time to get serial running
Serial.println(F("BME280 test"));
BC26_initail(); // 啟動與設定連線的伺服器
delay(5000);
bool status;
// default settings
status = bmp.begin();
if (!status) {
Serial.println("Could not find a valid BMP280 sensor, check wiring, address, sensor ID!");
while (1);
}
Serial.println("-- Default Test --");
delayTime = 1800000;
Serial.println();
int sta_pre = sta;
build_MQTT_connect(server_IP, server_port);
delay(5000);
reading(sta_pre, sta);
connect_MQTT();
delay(5000);
reading(sta_pre, sta);
delay(10000);
}
void loop() {
sendBatteryValue();//傳送偵測到的電池電量值
printBME280Values();//傳送BME280偵測到的值
delay(delayTime);
}
void printBME280Values() {
Serial.println("GetTemp&Humi&Pre&Alt OK! ");
float Temperature = bmp.readTemperature();
Serial.print(Temperature); Serial.println(" °C");
//float Humidity = bmp.readHumidity();
//Serial.println(Humidity); Serial.println(" %");
float Pressure = bmp.readPressure() / 100.0F;
Serial.print(Pressure); Serial.println(" hPa");
float Altitude = bmp.readAltitude(SEALEVELPRESSURE_HPA);
Serial.print(Altitude); Serial.println(" m");
MQTTtopic="nbiot/bmp";
MQTTmessage=String(Temperature)+","+String(Pressure)+","+String(Altitude)
+","+String(sensorValue)+","+String(voltage)+","+String(bat_percentage);
Publish_MQTT(MQTTtopic, MQTTmessage);
Serial.println("PutTemp&Humi&Pre&Alt OK! ");
}
void sendBatteryValue(){
sensorValue = analogRead(analogInPin);
voltage = (((sensorValue * 3.3) / 1024) * 2 + calibration); //multiply by two as voltage divider network is 100K & 100K Resistor
bat_percentage = mapfloat(voltage, 2.8, 4.2, 0, 100); //2.8V as Battery Cut off Voltage & 4.2V as Maximum Voltage
if (bat_percentage >= 100)
{
bat_percentage = 100;
}
if (bat_percentage <= 0)
{
bat_percentage = 1;
}
Serial.print("Analog Value = ");
Serial.print(sensorValue);
Serial.print("\t Output Voltage = ");
Serial.print(voltage);
Serial.print("\t Battery Percentage = ");
Serial.println(bat_percentage);
}
float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}