Skip to content

Instantly share code, notes, and snippets.

@LittleWat
Last active July 18, 2021 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LittleWat/2b3f4aad42b2f35e88fc12ab315b8aad to your computer and use it in GitHub Desktop.
Save LittleWat/2b3f4aad42b2f35e88fc12ab315b8aad to your computer and use it in GitHub Desktop.
Move switchbot using m5stack with PIR sensor
#include "BLEDevice.h"
#include "Free_Fonts.h"
#include <M5Stack.h>
#define SWITCHBOT_MAC "E6:21:7F:F9:06:69" // FIXME
static BLEUUID serviceUUID("CBA20D00-224D-11E6-9FB8-0002A5D5C51B");
static BLEUUID characteristicUUID("CBA20002-224D-11E6-9FB8-0002A5D5C51B");
static BLEAdvertisedDevice* myDevice;
static uint8_t cmdPress[3] = {0x57, 0x01, 0x00};
static uint8_t cmdUp[3] = {0x57, 0x01, 0x01};
static uint8_t cmdDown[3] = {0x57, 0x01, 0x02};
void pressSwitchBot(uint8_t *cmd) {
BLEClient* pClient = BLEDevice::createClient();
pClient->connect(myDevice);
BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
if (pRemoteService == nullptr) {
pClient->disconnect();
return;
}
BLERemoteCharacteristic* pCharacteristic = pRemoteService->getCharacteristic(characteristicUUID);
if (pCharacteristic == nullptr) {
pClient->disconnect();
return;
}
pCharacteristic->writeValue(cmd, 3, false);
pClient->disconnect();
}
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID) && advertisedDevice.getAddress().equals(BLEAddress(SWITCHBOT_MAC))) {
BLEDevice::getScan()->stop();
myDevice = new BLEAdvertisedDevice(advertisedDevice);
}
}
};
void setup() {
M5.begin();
M5.Power.begin();
// for saving battery, but this makes error: lld_pdu_get_tx_flush_nb HCI packet count mismatch (0, 1)
// M5.Lcd.writecommand(ILI9341_DISPOFF);
// M5.Lcd.setBrightness(0);
BLEDevice::init("");
BLEScan* pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setInterval(1349);
pBLEScan->setWindow(449);
pBLEScan->setActiveScan(true);
pBLEScan->start(5, false);
pinMode(36, INPUT);
}
static uint32_t count = 0;
static bool isoff = false;
void loop() {
if (myDevice == NULL) {
return;
}
if(digitalRead(36)==1){
Serial.println(" value: 1");
if(isoff) {
Serial.println("Turn on!!!");
pressSwitchBot(cmdUp);
isoff = false;
}
count = 0;
} else {
Serial.println(" value: 0");
if(count > 2 * 5) { // 5 seconds
if(!isoff){
Serial.println("Turn off...");
pressSwitchBot(cmdDown);
isoff = true;
}
}
count += 1;
}
delay(500);
M5.update();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment