-
Notifications
You must be signed in to change notification settings - Fork 0
/
Siren_Monitor.ino
391 lines (287 loc) · 11.7 KB
/
Siren_Monitor.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
/*
Name: Siren_Monitor.ino
Created: 3/19/2024 2:37:12 PM
Author: Chris
*/
/* Edge Impulse ingestion SDK
* Copyright (c) 2022 EdgeImpulse Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// If your target is limited in memory remove this macro to save 10K RAM
#define EIDSP_QUANTIZE_FILTERBANK 0
/**
* Define the number of slices per model window. E.g. a model window of 1000 ms
* with slices per model window set to 4. Results in a slice size of 250 ms.
* For more info: https://docs.edgeimpulse.com/docs/continuous-audio-sampling
*/
#define EI_CLASSIFIER_SLICES_PER_MODEL_WINDOW 4
/*
** NOTE: If you run into TFLite arena allocation issue.
**
** This may be due to may dynamic memory fragmentation.
** Try defining "-DEI_CLASSIFIER_ALLOCATION_STATIC" in boards.local.txt (create
** if it doesn't exist) and copy this file to
** `<ARDUINO_CORE_INSTALL_PATH>/arduino/hardware/<mbed_core>/<core_version>/`.
**
** See
** (https://support.arduino.cc/hc/en-us/articles/360012076960-Where-are-the-installed-cores-located-)
** to find where Arduino installs cores on your machine.
**
** If the problem persists then there's not enough memory for this model and application.
*/
/* Includes ---------------------------------------------------------------- */
#include <PDM.h>
#include <Clarke_Cooper_Ltd-project-1_inferencing.h>
/** Audio buffers, pointers and selectors */
typedef struct {
signed short* buffers[2];
unsigned char buf_select;
unsigned char buf_ready;
unsigned int buf_count;
unsigned int n_samples;
} inference_t;
static inference_t inference;
static bool record_ready = false;
static signed short* sampleBuffer;
static bool debug_nn = false; // Set this to true to see e.g. features generated from the raw signal
static int print_results = -(EI_CLASSIFIER_SLICES_PER_MODEL_WINDOW);
#define ALARM_KEY "Siren"
#define CONFIDENCE_FACTOR 0.90
bool is_alarm = false;
#define espInterrupt 14 // Digital pin connected to interrupt pin on ESP32
unsigned long lastTriggerTime = 0;
const unsigned long triggerInterval = 30000; // Trigger interval in milliseconds (60 seconds)
/*---------------------------------------------------------------- * /
/**
* @brief Arduino setup function
*/
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
// comment out the below line to cancel the wait for USB connection (needed for native USB)
// while (!Serial);
Serial.println("Edge Impulse Inferencing Demo");
// Start Serial 1 for ESP32 Communications
Serial1.begin(115200); // initialize UART with baud rate of 9600
// Pin mode
pinMode(espInterrupt, OUTPUT);
digitalWrite(espInterrupt, HIGH);
// Continue setup
digitalWrite(LEDB, LOW);
delay(1000);
Serial1.println("Nano BLE Sense Successfully Reset...");
Serial1.println(" ");
delay(500);
digitalWrite(LEDB, HIGH);
// Summary of inferencing settings (from model_metadata.h)
ei_printf("Inferencing settings:\n");
ei_printf("\tInterval: %.2f ms.\n", (float)EI_CLASSIFIER_INTERVAL_MS);
ei_printf("\tFrame size: %d\n", EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE);
ei_printf("\tSample length: %d ms.\n", EI_CLASSIFIER_RAW_SAMPLE_COUNT / 16);
ei_printf("\tNo. of classes: %d\n", sizeof(ei_classifier_inferencing_categories) / sizeof(ei_classifier_inferencing_categories[0]));
run_classifier_init();
if (microphone_inference_start(EI_CLASSIFIER_SLICE_SIZE) == false) {
ei_printf("ERR: Could not allocate audio buffer (size %d), this could be due to the window length of your model\r\n", EI_CLASSIFIER_RAW_SAMPLE_COUNT);
return;
}
Serial.println();
Serial.print("Confidence Factor Set As: ");
Serial.println(CONFIDENCE_FACTOR);
Serial.println();
} // Close setup
/*---------------------------------------------------------------- * /
/**
* @brief Arduino main function. Runs the inferencing loop.
*/
void loop() {
bool m = microphone_inference_record();
if (!m) {
ei_printf("ERR: Failed to record audio...\n");
return;
}
signal_t signal;
signal.total_length = EI_CLASSIFIER_SLICE_SIZE;
signal.get_data = µphone_audio_signal_get_data;
ei_impulse_result_t result = { 0 };
EI_IMPULSE_ERROR r = run_classifier_continuous(&signal, &result, debug_nn);
if (r != EI_IMPULSE_OK) {
ei_printf("ERR: Failed to run classifier (%d)\n", r);
return;
}
if (++print_results >= (EI_CLASSIFIER_SLICES_PER_MODEL_WINDOW)) {
// print the predictions
// ei_printf("Predictions ");
// ei_printf("(DSP: %d ms., Classification: %d ms., Anomaly: %d ms.)",
// result.timing.dsp, result.timing.classification, result.timing.anomaly);
// ei_printf(": \n");
for (size_t ix = 0; ix < EI_CLASSIFIER_LABEL_COUNT; ix++) {
ei_printf(" %s: %.5f", result.classification[ix].label, result.classification[ix].value);
//ei_printf(" ");
if (strcmp(result.classification[ix].label, ALARM_KEY) == 0 && result.classification[ix].value > CONFIDENCE_FACTOR) {
heard_alarm();
// Convert value to percentage (assuming value is in range 0.0 to 1.0)
int percentage = int(result.classification[ix].value * 100);
// Convert percentage to a string
String percentageString = String(percentage) + "%";
// Construct the data string in the format: "Title,Percentage%"
String dataToSend = String(result.classification[ix].label) + "," + 'U' + "," + String(percentageString);
// Construct the data string in the format: "Title,Accuracy"
//String dataToSend = String(result.classification[ix].label) + "," + String(result.classification[ix].value);
Serial1.println(dataToSend);
}
else if (strcmp(result.classification[ix].label, ALARM_KEY) == 0 && result.classification[ix].value < CONFIDENCE_FACTOR) {
digitalWrite(LEDR, HIGH);
digitalWrite(LEDB, HIGH);
}
//if (strcmp(result.classification[ix].label, ALARM_KEY) == 0 && result.classification[ix].value > CONFIDENCE_FACTOR)
//{
// heard_alarm();
// Serial1.print(" ");
// Serial1.print(result.classification[ix].label);
// Serial1.print(": ");
// Serial1.println(result.classification[ix].value);
//
//}
//else if (strcmp(result.classification[ix].label, ALARM_KEY) == 0 && result.classification[ix].value < CONFIDENCE_FACTOR)
// digitalWrite(LEDR, HIGH);
// digitalWrite(LEDB, HIGH);
}
ei_printf(": \n");
#if EI_CLASSIFIER_HAS_ANOMALY == 1
ei_printf(" anomaly score: %.3f\n", result.anomaly);
#endif
print_results = 0;
}
unsigned long currentTime = millis();
if (currentTime - lastTriggerTime >= triggerInterval) {
// Send a trigger signal to the ESP32 by toggling the interrupt pin
Serial.println("ESP Interrupt triggered...");
digitalWrite(espInterrupt, LOW);
delayMicroseconds(100); // Ensure a pulse width of at least 100 microseconds
digitalWrite(espInterrupt, HIGH);
lastTriggerTime = currentTime;
}
}
/*---------------------------------------------------------------- */
static void heard_alarm() {
Serial.print(" - ");
Serial.print("Siren Detected");
digitalWrite(LEDR, LOW);
//Serial1.println('1');
//digitalWrite(LEDB, LOW);
}
/*---------------------------------------------------------------- */
/**
* @brief PDM buffer full callback
* Get data and call audio thread callback
*/
static void pdm_data_ready_inference_callback(void) {
int bytesAvailable = PDM.available();
// read into the sample buffer
int bytesRead = PDM.read((char*)&sampleBuffer[0], bytesAvailable);
if (record_ready == true) {
for (int i = 0; i < bytesRead >> 1; i++) {
inference.buffers[inference.buf_select][inference.buf_count++] = sampleBuffer[i];
if (inference.buf_count >= inference.n_samples) {
inference.buf_select ^= 1;
inference.buf_count = 0;
inference.buf_ready = 1;
}
}
}
}
/*---------------------------------------------------------------- * /
/**
* @brief Init inferencing struct and setup/start PDM
*
* @param[in] n_samples The n samples
*
* @return { description_of_the_return_value }
*/
static bool microphone_inference_start(uint32_t n_samples) {
inference.buffers[0] = (signed short*)malloc(n_samples * sizeof(signed short));
if (inference.buffers[0] == NULL) {
return false;
}
inference.buffers[1] = (signed short*)malloc(n_samples * sizeof(signed short));
if (inference.buffers[1] == NULL) {
free(inference.buffers[0]);
return false;
}
sampleBuffer = (signed short*)malloc((n_samples >> 1) * sizeof(signed short));
if (sampleBuffer == NULL) {
free(inference.buffers[0]);
free(inference.buffers[1]);
return false;
}
inference.buf_select = 0;
inference.buf_count = 0;
inference.n_samples = n_samples;
inference.buf_ready = 0;
// configure the data receive callback
PDM.onReceive(&pdm_data_ready_inference_callback);
PDM.setBufferSize((n_samples >> 1) * sizeof(int16_t));
// initialize PDM with:
// - one channel (mono mode)
// - a 16 kHz sample rate
if (!PDM.begin(1, EI_CLASSIFIER_FREQUENCY)) {
ei_printf("Failed to start PDM!");
}
// set the gain, defaults to 20
PDM.setGain(127);
record_ready = true;
return true;
}
/*---------------------------------------------------------------- * /
/**
* @brief Wait on new data
*
* @return True when finished
*/
static bool microphone_inference_record(void) {
bool ret = true;
if (inference.buf_ready == 1) {
ei_printf(
"Error sample buffer overrun. Decrease the number of slices per model window "
"(EI_CLASSIFIER_SLICES_PER_MODEL_WINDOW)\n");
ret = false;
}
while (inference.buf_ready == 0) {
delay(1);
}
inference.buf_ready = 0;
return ret;
}
/*---------------------------------------------------------------- * /
/**
* Get raw audio signal data
*/
static int microphone_audio_signal_get_data(size_t offset, size_t length, float* out_ptr) {
numpy::int16_to_float(&inference.buffers[inference.buf_select ^ 1][offset], out_ptr, length);
return 0;
}
/*---------------------------------------------------------------- * /
/**
* @brief Stop PDM and release buffers
*/
static void microphone_inference_end(void) {
PDM.end();
free(inference.buffers[0]);
free(inference.buffers[1]);
free(sampleBuffer);
}
#if !defined(EI_CLASSIFIER_SENSOR) || EI_CLASSIFIER_SENSOR != EI_CLASSIFIER_SENSOR_MICROPHONE
#error "Invalid model for current sensor."
#endif
/*---------------------------------------------------------------- */