Apple Home sensor station on the MKR WiFi 1010, no bridge
Temperature, humidity, light, presence, a programmable button and a color light show up natively in the Home app: HomeSpan runs on the board's own Wi-Fi chip.
Devices & Components
1
40 colored male-female jumper wires
1
40 colored male-male jumper wires
1
Breadboard - 400 contacts
1
Arduino MKR WiFi 1010
1
Pushbutton, 6 mm
1
LD2410C 24 GHz presence radar
1
RGB LED, common cathode, 5 mm
1
Resistors: 220 ohm x1 and 100 ohm x2
1
BH1750 light sensor module (GY-302)
1
DHT11 temperature and humidity module (KY-015)
Software & Tools
Arduino IDE
Project description
Code
Wi-Fi chip (NINA-W102): HomeSpan and the HomeKit accessory
cpp
Runs on the NINA: upload as ESP32 Dev Module.
1// ============================================================================ 2// MKR WiFi 1010 sensor station: the NINA-W102 (ESP32) side, with HomeSpan. 3// 4// This sketch does NOT run on the SAMD21: it runs on the Wi-Fi chip of the 5// MKR, the NINA-W102, which is an ESP32 with 2 MB of flash. It replaces the 6// Arduino Wi-Fi firmware with HomeSpan, so the board pairs directly with the 7// Apple Home app, with no bridge. 8// 9// One accessory, "MKR 1010", with the light of the board itself plus what the 10// SAMD21 sends over the serial port (mkr-station-samd/): 11// 12// temperature · humidity · light · presence (radar) · programmable button 13// (single, double and long press, each one triggers its own automation in 14// Home) and a color light, "Desk LED": the RGB LED on the breadboard, with 15// on/off, brightness and color from the Home app. 16// 17// Protocol with the SAMD (115200): receives S T=24.3 H=55 L=123 P=1 18// B 0|1|2 19// sends @RGB 255 120 0 20// Everything goes over Serial, which on the NINA is the port shared with the 21// SAMD. HomeSpan stops reading its console there (setSerialInputDisable): 22// lines that are not data are passed to it as commands, so "U", "L1" and "?" 23// still work. 24// 25// HOW TO UPLOAD IT FROM THE ARDUINO IDE: 26// 1. Board "Arduino MKR WiFi 1010": upload the example 27// WiFiNINA > Tools > SerialNINAPassthrough (the SAMD21 becomes a USB bridge). 28// 2. Board "ESP32 Dev Module", on the same port, with: 29// Flash Size 2MB · Flash Mode DIO · Flash Frequency 40MHz · 30// Partition Scheme "Huge APP (3MB No OTA)" · Upload Speed 115200 31// and upload this sketch. The real table is the partitions.csv in this 32// folder (1.94 MB); "Huge APP" is only there so the IDE accepts the size. 33// DIO at 40 MHz is REQUIRED: with QIO/80 MHz the NINA reboots in a loop. 34// 3. Board "Arduino MKR WiFi 1010" again: upload mkr-station-samd. 35// 36// Going back: flash the original NINA firmware again with the Firmware Updater 37// of the Arduino IDE. 38// ============================================================================ 39#if !defined(ESP32) 40#error "THIS SKETCH IS FOR THE WI-FI CHIP (NINA). Select the board ESP32 Dev Module and follow the steps in the comment above." 41#endif 42#include "HomeSpan.h" 43#include "Secrets.h" 44 45// Measured on the board: red on 25 and green on 26 (the other way round from 46// the Arduino examples). Blue on 27. 47constexpr int LED_RED = 25, LED_GREEN = 26, LED_BLUE = 27; 48 49// The RGB LED of the board itself, which is wired to the NINA 50struct BoardLight : Service::LightBulb { 51 SpanCharacteristic *on, *brightness, *hue, *saturation; 52 BoardLight() { 53 // The `true` stores each value in NVS: after a restart the light comes 54 // back as it was (on, color and brightness), not off. 55 on = new Characteristic::On(false, true); 56 brightness = new Characteristic::Brightness(100, true); 57 hue = new Characteristic::Hue(210, true); 58 saturation = new Characteristic::Saturation(80, true); 59 paint(on->getVal(), brightness->getVal(), hue->getVal<float>(), saturation->getVal<float>()); 60 } 61 boolean update() override { 62 paint(on->getNewVal(), brightness->getNewVal(), hue->getNewVal<float>(), saturation->getNewVal<float>()); 63 return true; 64 } 65 static void paint(bool isOn, int brightness, float h, float s) { 66 float r = 0, g = 0, b = 0; 67 if (isOn) LedPin::HSVtoRGB(h, s / 100.0, brightness / 100.0, &r, &g, &b); 68 ledcWrite(LED_RED, (int)(r * 255)); ledcWrite(LED_GREEN, (int)(g * 255)); ledcWrite(LED_BLUE, (int)(b * 255)); 69 } 70}; 71 72// The RGB LED on the breadboard belongs to the SAMD (D5, D2, D1): here the 73// color from Home (hue, saturation, brightness) becomes red-green-blue and is 74// requested from it. 75struct DeskLed : Service::LightBulb { 76 SpanCharacteristic *on, *brightness, *hue, *saturation; 77 DeskLed() { 78 new Characteristic::Name("Desk LED"); 79 on = new Characteristic::On(false, true); 80 brightness = new Characteristic::Brightness(100, true); 81 hue = new Characteristic::Hue(30, true); 82 saturation = new Characteristic::Saturation(100, true); 83 send(on->getVal(), brightness->getVal(), hue->getVal<float>(), saturation->getVal<float>()); 84 } 85 boolean update() override { 86 send(on->getNewVal(), brightness->getNewVal(), hue->getNewVal<float>(), saturation->getNewVal<float>()); 87 return true; 88 } 89 static void send(bool isOn, int brightness, float h, float s) { 90 float r = 0, g = 0, b = 0; 91 if (isOn) LedPin::HSVtoRGB(h, s / 100.0, brightness / 100.0, &r, &g, &b); 92 Serial.printf("@RGB %d %d %d\n", (int)(r * 255), (int)(g * 255), (int)(b * 255)); 93 } 94}; 95 96SpanCharacteristic *temperature, *humidity, *light, *presence, *button; 97SpanCharacteristic *batteryLevel, *charging, *lowBattery; 98 99// One line from the SAMD: sensor data, a button event, or a command for the 100// HomeSpan console. 101void handleLine(char *line) { 102 if (strncmp(line, "S ", 2) == 0) { 103 float t, h, l; int p; 104 if (sscanf(line + 2, "T=%f H=%f L=%f P=%d", &t, &h, &l, &p) == 4) { 105 if (t > -50) temperature->setVal(t); 106 if (h >= 0) humidity->setVal(h); 107 // HomeKit does not accept 0 lux 108 if (l >= 0) light->setVal(l < 0.0001 ? 0.0001 : l); 109 presence->setVal(p ? 1 : 0); 110 } 111 return; 112 } 113 if (strncmp(line, "B ", 2) == 0) { button->setVal(atoi(line + 2)); return; } 114 // The optional battery meter (INA219): counted %, charging or not, and low. 115 if (strncmp(line, "W ", 2) == 0) { 116 float mA, v; int n; 117 if (sscanf(line + 2, "I=%f V=%f N=%d", &mA, &v, &n) == 3) { 118 batteryLevel->setVal(constrain(n, 0, 100)); 119 // 1 = charging, 0 = not charging 120 charging->setVal(mA > 20 ? 1 : 0); 121 lowBattery->setVal(n < 15 ? 1 : 0); 122 } 123 return; 124 } 125 homeSpan.processSerialCommand(line); 126} 127 128// Alternates between the main network and the backup one on every attempt 129void connectWifi(const char*, const char*) { 130 static bool backup = false; 131 const char* ssid = backup ? WIFI_SSID_BACKUP : WIFI_SSID; 132 Serial.printf("WIFI: trying %s%s\n", ssid, backup ? " (backup)" : ""); 133 WiFi.begin(ssid, backup ? WIFI_PASSWORD_BACKUP : WIFI_PASSWORD); 134 backup = !backup; 135} 136 137void setup() { 138 Serial.begin(115200); 139 for (int pin : {LED_RED, LED_GREEN, LED_BLUE}) ledcAttach(pin, 5000, 8); 140 homeSpan.setLogLevel(0); 141 homeSpan.setSerialInputDisable(true); 142 homeSpan.setWifiCredentials(WIFI_SSID, WIFI_PASSWORD); 143 homeSpan.setWifiBegin(connectWifi); 144 // The HomeSpan default setup code: 466-37-726 145 homeSpan.setPairingCode("46637726"); 146 homeSpan.setHostNameSuffix(""); 147 WiFi.setHostname("arduino-mkr1010"); 148 homeSpan.begin(Category::Sensors, "MKR 1010", "arduino-mkr1010"); 149 150 // A single accessory with several services: Home shows them as separate tiles. 151 new SpanAccessory(); 152 new Service::AccessoryInformation(); 153 new Characteristic::Identify(); 154 new Characteristic::Name("MKR Station"); 155 new Characteristic::Manufacturer("DIY"); 156 new Characteristic::Model("MKR WiFi 1010 (NINA-W102)"); 157 new BoardLight(); 158 new Service::TemperatureSensor(); 159 new Characteristic::Name("Temperature"); 160 temperature = new Characteristic::CurrentTemperature(20); 161 temperature->setRange(-40, 100); 162 new Service::HumiditySensor(); 163 new Characteristic::Name("Humidity"); 164 humidity = new Characteristic::CurrentRelativeHumidity(50); 165 new Service::LightSensor(); 166 new Characteristic::Name("Light"); 167 light = new Characteristic::CurrentAmbientLightLevel(1); 168 new Service::OccupancySensor(); 169 new Characteristic::Name("Presence"); 170 presence = new Characteristic::OccupancyDetected(0); 171 new Service::BatteryService(); 172 new Characteristic::Name("Battery"); 173 batteryLevel = new Characteristic::BatteryLevel(50); 174 charging = new Characteristic::ChargingState(0); 175 lowBattery = new Characteristic::StatusLowBattery(0); 176 new Service::StatelessProgrammableSwitch(); 177 new Characteristic::Name("Button"); 178 button = new Characteristic::ProgrammableSwitchEvent(0); 179 new DeskLed(); 180} 181 182void loop() { 183 homeSpan.poll(); 184 static char line[160]; static uint8_t n = 0; 185 while (Serial.available()) { 186 const char c = Serial.read(); 187 if (c == '\n') { line[n] = 0; if (n > 0) handleLine(line); n = 0; } 188 else if (c != '\r' && n < sizeof(line) - 1) line[n++] = c; 189 } 190}
Main chip (SAMD21): sensors, button and RGB LED
cpp
Runs on the SAMD21: upload as MKR WiFi 1010.
1// ============================================================================ 2// MKR WiFi 1010 sensor station: the SAMD21 side. 3// 4// It reads the sensors on the breadboard and hands them to the Wi-Fi chip 5// (NINA-W102, running HomeSpan: mkr-station-nina/) over the serial port that 6// already joins the two chips. The NINA publishes them in the Apple Home app. 7// The SAMD never touches Wi-Fi. 8// 9// D4 DHT11 (KY-015) temperature and humidity 10// D11/D12 BH1750 (I2C) light, in lux 11// D7 LD2410C radar, OUT presence (1 = someone is there) 12// D3 pushbutton to GND INPUT_PULLUP: single, double and long press (D6 is the on-board LED) 13// D5/D2/D1 RGB LED common cathode; 220 ohm on red, 100 ohm on green and blue. 14// The color is chosen in the Home app (the "Desk LED" light) 15// D13/D14 (Serial1) UART of the radar, reserved for reading distance 16// D11/D12 INA219 (I2C) optional: a battery meter (current, voltage and counted mAh) 17// 18// To the NINA, every 2 s: S T=24.3 H=55 L=123 P=1 19// W I=512.3 V=3.98 N=67 (mA: + charging, - discharging; N = estimated %) 20// On a button press: B 0 (single) B 1 (double) B 2 (long) 21// From the NINA: @RGB 255 120 0 (0-255 per color; anything else is its log, and is 22// forwarded to USB with the [NINA] prefix) 23// ============================================================================ 24#include <DHT.h> 25#include <BH1750.h> 26#include <Wire.h> 27#include <DFRobot_INA219.h> 28 29const uint8_t PIN_DHT = 4; 30const uint8_t PIN_RADAR = 7; 31// D3, and NOT D6: D6 is the LED of the board itself 32const uint8_t PIN_BUTTON = 3; 33// Desk RGB LED: all three pins have PWM and each one uses a different timer 34// (D5 TCC0, D2 TCC1, D1 TC4), so they do not step on each other. 35const uint8_t PIN_RED = 5, PIN_GREEN = 2, PIN_BLUE = 1; 36 37// At 3.3 V the red die (about 2 V drop) is much brighter than green and blue 38// (about 3 V): it is turned down so that white does not look pink. Tune by eye. 39const float RED_BALANCE = 0.45; 40 41void paintRgb(int r, int g, int b) { 42 analogWrite(PIN_RED, (int)(constrain(r, 0, 255) * RED_BALANCE)); 43 analogWrite(PIN_GREEN, constrain(g, 0, 255)); 44 analogWrite(PIN_BLUE, constrain(b, 0, 255)); 45} 46 47DHT dht(PIN_DHT, DHT11); 48 49// --- optional battery meter --------------------------------------------------- 50// The INA219 goes in series with the + of a Li-ion cell: IN+ to the cell, OUT+ 51// to the load. That way it reads positive when current LEAVES the cell. SIGN 52// flips it so that "+" means charging. If it comes out backwards, change it to 1. 53const float SIGN = -1.0; 54// Capacity of the cell being measured 55const float CAPACITY_MAH = 3300; 56DFRobot_INA219_IIC *ina = nullptr; 57// Charge inside the cell, counted 58float mAh = 0; 59bool levelKnown = false; 60unsigned long lastInaAt = 0; 61 62// The module can be at 0x40, 0x41, 0x44 or 0x45 depending on its DIP switch: look for it. 63void findIna() { 64 const uint8_t addresses[4] = {INA219_I2C_ADDRESS4, INA219_I2C_ADDRESS1, INA219_I2C_ADDRESS2, INA219_I2C_ADDRESS3}; 65 for (uint8_t a : addresses) { 66 Wire.beginTransmission(a); 67 if (Wire.endTransmission() == 0) { 68 ina = new DFRobot_INA219_IIC(&Wire, a); 69 if (ina->begin()) { Serial.print("[INA219] at 0x"); Serial.println(a, HEX); return; } 70 delete ina; ina = nullptr; 71 } 72 } 73 Serial.println("[INA219] not found: the battery meter stays off"); 74} 75 76// First level from the resting voltage (curve of a lithium cell); from there 77// on, the mAh count rules. 78float percentFromVoltage(float v) { 79 const float tv[] = {4.20, 4.10, 4.00, 3.90, 3.80, 3.70, 3.60, 3.50, 3.30}; 80 const float tp[] = {100, 90, 80, 65, 45, 25, 12, 5, 0}; 81 if (v >= tv[0]) return 100; 82 for (uint8_t i = 1; i < 9; i++) 83 if (v >= tv[i]) return tp[i] + (v - tv[i]) / (tv[i - 1] - tv[i]) * (tp[i - 1] - tp[i]); 84 return 0; 85} 86 87void measureBattery() { 88 if (!ina) return; 89 unsigned long now = millis(); 90 float hours = (now - lastInaAt) / 3600000.0; 91 lastInaAt = now; 92 float mA = SIGN * ina->getCurrent_mA(); 93 float v = ina->getBusVoltage_V(); 94 if (!levelKnown && v > 2.5) { mAh = percentFromVoltage(v) / 100.0 * CAPACITY_MAH; levelKnown = true; } 95 mAh += mA * hours; 96 // Full: the charger barely pushes any more and the cell is at the top. Pin it at 100 %. 97 if (mA > 0 && mA < 100 && v >= 4.15) mAh = CAPACITY_MAH; 98 mAh = constrain(mAh, 0, CAPACITY_MAH); 99 int level = (int)(mAh / CAPACITY_MAH * 100 + 0.5); 100 SerialNina.print("W I="); SerialNina.print(mA, 1); 101 SerialNina.print(" V="); SerialNina.print(v, 3); 102 SerialNina.print(" N="); SerialNina.println(level); 103 Serial.print("[BATTERY] "); Serial.print(mA, 1); Serial.print(" mA "); 104 Serial.print(v, 3); Serial.print(" V "); Serial.print(mAh, 0); Serial.print(" mAh "); Serial.print(level); Serial.println(" %"); 105} 106BH1750 lightMeter; 107bool hasBH1750 = false; 108 109// --- the button: single, double or long ---------------------------------------- 110const unsigned long DEBOUNCE_MS = 30, LONG_MS = 700, DOUBLE_MS = 350; 111// LOW = pressed (pull-up) 112bool buttonDown = false; 113unsigned long buttonSince = 0, lastChange = 0, releasedSince = 0; 114uint8_t shortPresses = 0; 115bool longReported = false; 116 117// 0 single · 1 double · 2 long (the same numbers HomeKit uses) 118void reportButton(uint8_t kind) { 119 SerialNina.print("B "); SerialNina.println(kind); 120 Serial.print("[BUTTON] "); Serial.println(kind == 0 ? "single" : kind == 1 ? "double" : "long"); 121} 122 123void readButton() { 124 unsigned long now = millis(); 125 bool down = digitalRead(PIN_BUTTON) == LOW; 126 if (down != buttonDown && now - lastChange > DEBOUNCE_MS) { 127 lastChange = now; buttonDown = down; 128 if (down) { buttonSince = now; longReported = false; } 129 else if (!longReported) { shortPresses++; releasedSince = now; } 130 } 131 if (buttonDown && !longReported && now - buttonSince >= LONG_MS) { longReported = true; shortPresses = 0; reportButton(2); } 132 if (!buttonDown && shortPresses > 0 && now - releasedSince > DOUBLE_MS) { 133 reportButton(shortPresses >= 2 ? 1 : 0); 134 shortPresses = 0; 135 } 136} 137 138// --- what the NINA says --------------------------------------------------------- 139void serviceNina() { 140 static char line[160]; static uint8_t n = 0; 141 while (SerialNina.available()) { 142 const char c = SerialNina.read(); 143 if (c == '\n') { 144 line[n] = 0; 145 int r, g, b; 146 if (sscanf(line, "@RGB %d %d %d", &r, &g, &b) == 3) paintRgb(r, g, b); 147 else if (n > 0) { Serial.print("[NINA] "); Serial.println(line); } 148 n = 0; 149 } else if (c != '\r' && n < sizeof(line) - 1) line[n++] = c; 150 } 151} 152 153void setup() { 154 Serial.begin(115200); 155 SerialNina.begin(115200); 156 pinMode(PIN_BUTTON, INPUT_PULLUP); 157 pinMode(PIN_RADAR, INPUT); 158 pinMode(PIN_RED, OUTPUT); pinMode(PIN_GREEN, OUTPUT); pinMode(PIN_BLUE, OUTPUT); 159 paintRgb(0, 0, 0); 160 161 // Start the NINA in normal mode (the reset logic is inverted on the MKR). 162 pinMode(NINA_GPIO0, OUTPUT); digitalWrite(NINA_GPIO0, HIGH); 163 pinMode(NINA_RESETN, OUTPUT); digitalWrite(NINA_RESETN, HIGH); 164 delay(100); 165 digitalWrite(NINA_RESETN, LOW); 166 167 dht.begin(); 168 Wire.begin(); 169 hasBH1750 = lightMeter.begin(BH1750::CONTINUOUS_HIGH_RES_MODE); 170 Serial.println(hasBH1750 ? "[BH1750] ready" : "[BH1750] not found: check SDA/SCL"); 171 findIna(); 172 lastInaAt = millis(); 173} 174 175void loop() { 176 // The HomeSpan console: what you type on USB goes to the NINA 177 while (Serial.available()) SerialNina.write(Serial.read()); 178 serviceNina(); 179 readButton(); 180 181 static unsigned long lastReadingAt = 0; 182 if (millis() - lastReadingAt >= 2000) { 183 lastReadingAt = millis(); 184 float t = dht.readTemperature(), h = dht.readHumidity(); 185 float lux = hasBH1750 ? lightMeter.readLightLevel() : -1; 186 int presence = digitalRead(PIN_RADAR); 187 SerialNina.print("S T="); SerialNina.print(isnan(t) ? -99 : t, 1); 188 SerialNina.print(" H="); SerialNina.print(isnan(h) ? -1 : h, 0); 189 SerialNina.print(" L="); SerialNina.print(lux, 0); 190 SerialNina.print(" P="); SerialNina.println(presence); 191 Serial.print("[SENSORS] T="); Serial.print(t, 1); Serial.print(" H="); Serial.print(h, 0); 192 Serial.print(" L="); Serial.print(lux, 0); Serial.print(" P="); Serial.println(presence); 193 measureBattery(); 194 } 195}
Comments
Only logged in users can leave comments