mirror of
https://github.com/morgan9e/ESP32
synced 2026-04-14 00:14:03 +09:00
104 lines
2.5 KiB
C++
104 lines
2.5 KiB
C++
#include <Wire.h>
|
|
#include <Adafruit_BME680.h>
|
|
#include <Adafruit_INA219.h>
|
|
#include <NimBLEDevice.h>
|
|
|
|
Adafruit_BME680 bme;
|
|
Adafruit_INA219 ina219(0x41);
|
|
|
|
#define ADVERTISE_MS 500
|
|
#define SLEEP_TIME_MS 15000
|
|
#define DEBUG
|
|
|
|
void setup() {
|
|
#ifdef DEBUG
|
|
Serial.begin(115200);
|
|
delay(100);
|
|
#endif
|
|
|
|
Wire.begin();
|
|
|
|
bme.begin();
|
|
ina219.begin();
|
|
|
|
delay(100);
|
|
|
|
NimBLEDevice::init("EnvSensor");
|
|
NimBLEDevice::setPower(ESP_PWR_LVL_P9);
|
|
|
|
uint16_t nonce = (uint16_t)esp_random();
|
|
|
|
float temp = bme.readTemperature();
|
|
float hum = bme.readHumidity();
|
|
float pres = bme.readPressure() / 100.0;
|
|
float busVoltage = ina219.getBusVoltage_V();
|
|
|
|
float total_current = 0;
|
|
for(int i = 0; i < 10; i++) {
|
|
total_current += ina219.getCurrent_mA();
|
|
delay(5);
|
|
}
|
|
float wake_current = total_current / 10.0;
|
|
|
|
#ifdef DEBUG
|
|
Serial.printf("Nonce: 0x%04X\n", nonce);
|
|
Serial.printf("T:%.1f H:%.1f P:%.0f V:%.2fV I:%.1fmA\n",
|
|
temp, hum, pres, busVoltage, wake_current);
|
|
#endif
|
|
|
|
uint8_t payload[18];
|
|
payload[0] = 0xFF;
|
|
payload[1] = 0xFF;
|
|
payload[2] = nonce & 0xFF;
|
|
payload[3] = (nonce >> 8) & 0xFF;
|
|
|
|
int16_t temp_raw = (int16_t)(temp * 100);
|
|
payload[4] = temp_raw & 0xFF;
|
|
payload[5] = (temp_raw >> 8) & 0xFF;
|
|
|
|
uint16_t hum_raw = (uint16_t)(hum * 100);
|
|
payload[6] = hum_raw & 0xFF;
|
|
payload[7] = (hum_raw >> 8) & 0xFF;
|
|
|
|
uint32_t pres_raw = (uint32_t)(pres * 10);
|
|
payload[8] = pres_raw & 0xFF;
|
|
payload[9] = (pres_raw >> 8) & 0xFF;
|
|
payload[10] = (pres_raw >> 16) & 0xFF;
|
|
payload[11] = (pres_raw >> 24) & 0xFF;
|
|
|
|
uint16_t voltage_raw = (uint16_t)(busVoltage * 100);
|
|
payload[12] = voltage_raw & 0xFF;
|
|
payload[13] = (voltage_raw >> 8) & 0xFF;
|
|
|
|
int32_t current_raw = (int32_t)(wake_current * 100);
|
|
payload[14] = current_raw & 0xFF;
|
|
payload[15] = (current_raw >> 8) & 0xFF;
|
|
payload[16] = (current_raw >> 16) & 0xFF;
|
|
payload[17] = (current_raw >> 24) & 0xFF;
|
|
|
|
#ifdef DEBUG
|
|
Serial.print("Payload: ");
|
|
for(int i=0; i<18; i++) {
|
|
Serial.printf("%02X ", payload[i]);
|
|
}
|
|
Serial.println();
|
|
#endif
|
|
|
|
NimBLEAdvertising *pAdvertising = NimBLEDevice::getAdvertising();
|
|
std::string payloadStr((char*)payload, 18);
|
|
pAdvertising->setManufacturerData(payloadStr);
|
|
pAdvertising->start();
|
|
|
|
delay(ADVERTISE_MS);
|
|
pAdvertising->stop();
|
|
|
|
#ifdef DEBUG
|
|
Serial.printf("Sleep: %d ms\n", SLEEP_TIME_MS);
|
|
#endif
|
|
|
|
delay(50);
|
|
esp_sleep_enable_timer_wakeup(SLEEP_TIME_MS * 1000ULL);
|
|
esp_deep_sleep_start();
|
|
}
|
|
|
|
void loop() {} |