Skip to content

Commit 9047314

Browse files
committed
codal_app/microbithal_microphone: Use levelSPL for level detection.
With a range of values for CODAL determined empirically. Fixes issue #114. Signed-off-by: Damien George <[email protected]>
1 parent 2233d79 commit 9047314

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

src/codal_app/microbithal_microphone.cpp

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,15 @@
2828
#include "microbithal.h"
2929
#include "MicroBitDevice.h"
3030

31-
#define SOUND_LEVEL_MAXIMUM (20000)
31+
// Range of level values used by CODAL.
32+
#define CODAL_LEVEL_MIN (52)
33+
#define CODAL_LEVEL_MAX (86)
34+
#define CODAL_LEVEL_RANGE (CODAL_LEVEL_MAX - CODAL_LEVEL_MIN)
35+
36+
// Range of level values used by this micro:bit HAL.
37+
#define HAL_LEVEL_MIN (0)
38+
#define HAL_LEVEL_MAX (255)
39+
#define HAL_LEVEL_RANGE (HAL_LEVEL_MAX - HAL_LEVEL_MIN)
3240

3341
extern "C" void microbit_hal_level_detector_callback(int);
3442

@@ -48,7 +56,8 @@ void microbit_hal_microphone_init(void) {
4856
}
4957

5058
void microbit_hal_microphone_set_threshold(int kind, int value) {
51-
value = value * SOUND_LEVEL_MAXIMUM / 255;
59+
value = (value - HAL_LEVEL_MIN) * CODAL_LEVEL_RANGE / HAL_LEVEL_RANGE + CODAL_LEVEL_MIN;
60+
value = min(max(value, CODAL_LEVEL_MIN), CODAL_LEVEL_MAX);
5261
if (kind == 0) {
5362
uBit.audio.level->setLowThreshold(value);
5463
} else {
@@ -57,9 +66,10 @@ void microbit_hal_microphone_set_threshold(int kind, int value) {
5766
}
5867

5968
int microbit_hal_microphone_get_level(void) {
60-
int l = uBit.audio.level->getValue();
61-
l = min(255, l * 255 / SOUND_LEVEL_MAXIMUM);
62-
return l;
69+
int value = uBit.audio.levelSPL->getValue();
70+
value = (value - CODAL_LEVEL_MIN) * HAL_LEVEL_RANGE / CODAL_LEVEL_RANGE + HAL_LEVEL_MIN;
71+
value = min(max(value, HAL_LEVEL_MIN), HAL_LEVEL_MAX);
72+
return value;
6373
}
6474

6575
}

0 commit comments

Comments
 (0)