Skip to content

call scaled microphone API instead of using our own scaling #6194

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 20 additions & 14 deletions libs/microphone/microphone.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@
#include "LevelDetectorSPL.h"
#endif

#define MICROPHONE_MIN 52.0f
#define MICROPHONE_MAX 120.0f

enum class DetectedSound {
//% block="loud"
Loud = 2,
Expand All @@ -23,6 +20,20 @@ enum class SoundThreshold {
};
namespace input {

#if MICROBIT_CODAL
bool didInit;

void init() {
if (didInit) {
return;
}

didInit = true;
uBit.audio.levelSPL->setUnit(LEVEL_DETECTOR_SPL_8BIT);
}

#endif

/**
* Registers an event that runs when a sound is detected
*/
Expand All @@ -33,6 +44,7 @@ namespace input {
//% group="micro:bit (V2)"
void onSound(DetectedSound sound, Action handler) {
#if MICROBIT_CODAL
init();
uBit.audio.levelSPL->activateForEvents(true);
const auto thresholdType = sound == DetectedSound::Loud ? LEVEL_THRESHOLD_HIGH : LEVEL_THRESHOLD_LOW;
registerWithDal(DEVICE_ID_SYSTEM_LEVEL_DETECTOR, thresholdType, handler);
Expand All @@ -51,12 +63,8 @@ void onSound(DetectedSound sound, Action handler) {
//% group="micro:bit (V2)"
int soundLevel() {
#if MICROBIT_CODAL
LevelDetectorSPL* level = uBit.audio.levelSPL;
if (NULL == level)
return 0;
const int micValue = level->getValue();
const int scaled = max(MICROPHONE_MIN, min(micValue, MICROPHONE_MAX)) - MICROPHONE_MIN;
return min(0xff, scaled * 0xff / (MICROPHONE_MAX - MICROPHONE_MIN));
init();
return uBit.audio.levelSPL->getValue();
#else
target_panic(PANIC_VARIANT_NOT_SUPPORTED);
return 0;
Expand All @@ -75,16 +83,14 @@ int soundLevel() {
//% group="micro:bit (V2)"
void setSoundThreshold(SoundThreshold sound, int threshold) {
#if MICROBIT_CODAL
init();
LevelDetectorSPL* level = uBit.audio.levelSPL;
if (NULL == level)
return;

threshold = max(0, min(0xff, threshold));
const int scaled = MICROPHONE_MIN + threshold * (MICROPHONE_MAX - MICROPHONE_MIN) / 0xff;
if (SoundThreshold::Loud == sound)
level->setHighThreshold(scaled);
level->setHighThreshold(threshold);
else
level->setLowThreshold(scaled);
level->setLowThreshold(threshold);
#else
target_panic(PANIC_VARIANT_NOT_SUPPORTED);
#endif
Expand Down
Loading