Skip to content

Instantly share code, notes, and snippets.

@thinkier
Last active November 4, 2024 07:23
Show Gist options
  • Save thinkier/061bc69f71aa8442f78cbdaa168ec014 to your computer and use it in GitHub Desktop.
Save thinkier/061bc69f71aa8442f78cbdaa168ec014 to your computer and use it in GitHub Desktop.
Test script for reporting temperature and humidity to a central using an Arduino Nano 33 BLE Sense Rev2
#include <ArduinoBLE.h>
#include <Arduino_HS300x.h>
BLEService envSvc("181A");
BLEShortCharacteristic tempChar("2A6E", BLERead | BLENotify);
BLEUnsignedShortCharacteristic humChar("2A6F", BLERead | BLENotify);
void setup() {
Serial.begin(9600);
for (int i = 0; i < 500; i++) {
if (Serial) break;
delay(1);
}
if (!HS300x.begin()) {
Serial.println("Failed to initialize humidity temperature sensor!");
while (1);
}
if (!BLE.begin()) {
Serial.println("Failed to start Bluetooth® Low Energy module!");
while (1);
}
BLE.setDeviceName("TempHumProbe");
BLE.setLocalName("TempHumProbe");
BLE.setAdvertisedService(envSvc);
envSvc.addCharacteristic(tempChar);
envSvc.addCharacteristic(humChar);
BLE.addService(envSvc);
tempChar.writeValue(0);
humChar.writeValue(0);
BLE.advertise();
Serial.println("Bluetooth® device active, waiting for connections...");
}
void loop() {
BLE.poll();
if (schedule(1000)) {
update();
}
}
bool schedule(int everyMillis) {
delay(1);
static unsigned long last = -1;
unsigned long now = millis();
if (last > now || last + everyMillis < now) {
last = now;
return true;
} else {
return false;
}
}
void update() {
float temperature = HS300x.readTemperature() * 100;
float humidity = HS300x.readHumidity() * 100;
if (tempChar.value() != temperature) {
tempChar.writeValue(temperature);
}
if (humChar.value() != humidity) {
humChar.writeValue(humidity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment