LoginSignup
6
6

More than 3 years have passed since last update.

格安BLE温湿度計のデータをESP32で取得してみた

Posted at

※自分用メモです。

最近話題のXiaomiの格安BLE温湿度計のデータをESP32で取得してみた。

試したのはXiaomiのLYWSD03MMCというやつ。
スマフォのアプリと接続すると、BLEのアドバタイズパケットにデータを載せて飛ばしてくるみたい。

以下ソースコード。


#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>

int scanTime = 5; //In seconds
BLEScan* pBLEScan;

std::string strDeviceName = "LYWSD03MMC";

class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
    void putHex(uint8_t *ptr, size_t len) {
      for( size_t i=0; i<len; i++) {
        Serial.printf("%02X", *ptr++);  
      }
      Serial.println("");
    }
    void onResult(BLEAdvertisedDevice advertisedDevice) {

      int n = strDeviceName.compare(advertisedDevice.getName());
      if ( n == 0){ 
        uint8_t *pPayload = advertisedDevice.getPayload();
        size_t len = advertisedDevice.getPayloadLength();

        if ((*(pPayload + 0x03) == 0x0f) && (*(pPayload + 0x04) == 0x16) && (*(pPayload + 0x03) == 0x0f) && (*(pPayload + 0x05) == 0x95) && (*(pPayload + 0x06) == 0xfe)) {
          int16_t temp = *(pPayload + 18) + *(pPayload + 19) * 256;
          uint8_t humidity =  *(pPayload + 21);

          Serial.printf("Temp: %d Humidity:%d\n", temp, humidity);
        }
      }
    }
};

void setup() {
  Serial.begin(115200);
  Serial.println("Scanning...");

  BLEDevice::init("");
  pBLEScan = BLEDevice::getScan(); //create new scan
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster
  pBLEScan->setInterval(100);
  pBLEScan->setWindow(99);  // less or equal setInterval value
}

void loop() {
  // put your main code here, to run repeatedly:
  BLEScanResults foundDevices = pBLEScan->start(scanTime, false);
  Serial.print("Devices found: ");
  Serial.println(foundDevices.getCount());
  Serial.println("Scan done!");
  pBLEScan->clearResults();   // delete results fromBLEScan buffer to release memory
  delay(2000);
}

結構簡単。

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6