Skip to content

Instantly share code, notes, and snippets.

@kazuho
Last active August 8, 2021 00:23
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 kazuho/6feb2985c3401308d38cc1821e8e9720 to your computer and use it in GitHub Desktop.
Save kazuho/6feb2985c3401308d38cc1821e8e9720 to your computer and use it in GitHub Desktop.
micro:bit v2 controller for RIGID Micro DC Aircon https://www.rigidhvac.com/micro-dc-aircon-12v
#include <algorithm>
#include <cstdio>
#include "MicroBit.h"
static MicroBit uBit;
static int targetTemp = 35;
static int showCount;
static void setPower(int newPeriod, NRF52Pin &pin)
{
static int curPeriod = 0;
// to minimize the noise, change the variables only when we have to
if (curPeriod == newPeriod)
return;
pin.setAnalogValue(511);
pin.setAnalogPeriodUs(newPeriod);
curPeriod = newPeriod;
}
static void showState()
{
showCount = 3;
}
static void onButtonA(MicroBitEvent)
{
if (showCount > 0 && targetTemp > 20)
--targetTemp;
showState();
}
static void onButtonB(MicroBitEvent)
{
if (showCount > 0 && targetTemp < 35)
++targetTemp;
showState();
}
// when idle for 10 minutes, report that using sound tone
static void reportIdle(int powerLevel)
{
static unsigned long lastOnAt = 0;
unsigned long now = uBit.systemTime();
if (powerLevel != 0)
goto UpdateNow;
if (now - lastOnAt < 10 * 60 * 1000)
return;
uBit.io.speaker.setAnalogValue(0);
static const unsigned tones[] = {1000000 / 440, 1000000 / 494, 1000000 / 554, 1000000 / 587, 1000000 / 659};
for (size_t i = 0; i < sizeof(tones) / sizeof(tones[0]); ++i) {
uBit.io.speaker.setAnalogPeriodUs(tones[i]);
uBit.io.speaker.setAnalogValue(511);
uBit.sleep(250);
}
uBit.sleep(500);
uBit.io.speaker.setAnalogValue(0);
UpdateNow:
// report after predefined seconds
lastOnAt = now;
}
int main()
{
uBit.init();
uBit.messageBus.listen(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK, onButtonA);
uBit.messageBus.listen(MICROBIT_ID_BUTTON_B, MICROBIT_BUTTON_EVT_CLICK, onButtonB);
MicroBitThermometer thermo;
showState();
while(1) {
// reported temp is 1~2 degrees higher than the actual value
int currentTemp = thermo.getTemperature() - 1;
int powerLevel = currentTemp - targetTemp + 1;
powerLevel = max(min(powerLevel, 3), 0);
#if 1 /* for pin 0 */
static const unsigned periods[] = {1000000 / 400, 1000000 / 2000, 1000000 / 6000, 1000000 / 10000};
setPower(periods[powerLevel], uBit.io.P0);
#else /* to test with speaker */
static const unsigned periods[] = {1000000 / 110, 1000000 / 220, 1000000 / 440, 1000000 / 880};
setPower(periods[powerLevel], uBit.io.speaker);
#endif
if (showCount > 0) {
char buf[32];
sprintf(buf, "%d%c %d", targetTemp, "oLmh"[powerLevel], currentTemp);
uBit.display.scroll(buf);
--showCount;
}
reportIdle(powerLevel);
uBit.sleep(1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment