|
28 | 28 | #include "microbithal.h"
|
29 | 29 | #include "MicroBitDevice.h"
|
30 | 30 |
|
31 |
| -extern "C" { |
32 |
| - |
33 | 31 | #define SOUND_LEVEL_MAXIMUM (20000)
|
34 | 32 |
|
35 |
| -static NRF52ADCChannel *mic = NULL; |
36 |
| -static StreamNormalizer *processor = NULL; |
37 |
| -static LevelDetector *level = NULL; |
| 33 | +extern "C" void microbit_hal_level_detector_callback(int); |
38 | 34 |
|
39 |
| -void microbit_hal_microphone_init(void) { |
40 |
| - if (mic == NULL) { |
41 |
| - mic = uBit.adc.getChannel(uBit.io.microphone); |
42 |
| - mic->setGain(7, 0); |
| 35 | +static void level_detector_event_handler(Event evt) { |
| 36 | + microbit_hal_level_detector_callback(evt.value); |
| 37 | +} |
43 | 38 |
|
44 |
| - processor = new StreamNormalizer(mic->output, 0.05, true, DATASTREAM_FORMAT_8BIT_SIGNED); |
45 |
| - level = new LevelDetector(processor->output, 600, 200); |
| 39 | +extern "C" { |
46 | 40 |
|
47 |
| - uBit.io.runmic.setDigitalValue(1); |
48 |
| - uBit.io.runmic.setHighDrive(true); |
| 41 | +static bool microphone_init_done = false; |
| 42 | + |
| 43 | +void microbit_hal_microphone_init(void) { |
| 44 | + if (!microphone_init_done) { |
| 45 | + microphone_init_done = true; |
| 46 | + uBit.messageBus.listen(DEVICE_ID_SYSTEM_LEVEL_DETECTOR, DEVICE_EVT_ANY, level_detector_event_handler); |
49 | 47 | }
|
50 | 48 | }
|
51 | 49 |
|
52 | 50 | void microbit_hal_microphone_set_threshold(int kind, int value) {
|
53 | 51 | value = value * SOUND_LEVEL_MAXIMUM / 255;
|
54 | 52 | if (kind == 0) {
|
55 |
| - level->setLowThreshold(value); |
| 53 | + uBit.audio.level->setLowThreshold(value); |
56 | 54 | } else {
|
57 |
| - level->setHighThreshold(value); |
| 55 | + uBit.audio.level->setHighThreshold(value); |
58 | 56 | }
|
59 | 57 | }
|
60 | 58 |
|
61 | 59 | int microbit_hal_microphone_get_level(void) {
|
62 |
| - if (level == NULL) { |
63 |
| - return -1; |
64 |
| - } else { |
65 |
| - int l = level->getValue(); |
66 |
| - l = min(255, l * 255 / SOUND_LEVEL_MAXIMUM); |
67 |
| - return l; |
68 |
| - } |
| 60 | + int l = uBit.audio.level->getValue(); |
| 61 | + l = min(255, l * 255 / SOUND_LEVEL_MAXIMUM); |
| 62 | + return l; |
69 | 63 | }
|
70 | 64 |
|
71 | 65 | }
|
0 commit comments