SuperTinyKernel™ RTOS 1.08.x
Lightweight, high-performance, deterministic, bare-metal C++ RTOS for resource-constrained embedded systems. MIT Open Source License.
Loading...
Searching...
No Matches
audio_mic_c/main.c
Go to the documentation of this file.
1/*
2 * The MIT License (MIT)
3 *
4 * Copyright (c) 2020 Reinhard Panhuber
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 *
24 */
25
31
32/* plot_audio_samples.py requires following modules:
33 * $ sudo apt install libportaudio
34 * $ pip3 install sounddevice matplotlib
35 *
36 * Then run
37 * $ python3 plot_audio_samples.py
38 */
39
40#include <stdio.h>
41#include <stdlib.h>
42#include <string.h>
43
44#include "bsp/board_api.h"
45#include "tusb.h"
46
47// STK's own kernel type (STK_C_KERNEL_TYPE_CPU_0), CPU count and max-task count are project
48// settings, expected to be defined in stk_config.h - see the "Kernel factory functions" section
49// of stk_c.h. This example needs at least 3 task slots (blinky, usbd, audio).
50#include "stk_c.h"
51
52// STK has no built-in equivalent of FreeRTOS's configMINIMAL_STACK_SIZE (stack sizes are always
53// caller-supplied, in words of stk_word_t) - pick a baseline here and size up per task below.
54// Adjust for your target/toolchain.
55#define STK_MINIMAL_STACK_SIZE 128U
56
57// Increase stack size when debug log is enabled
58#define USBD_STACK_SIZE ((4U * STK_MINIMAL_STACK_SIZE / 2U) * (CFG_TUSB_DEBUG ? 2U : 1U))
59
60#define BLINKY_STACK_SIZE STK_MINIMAL_STACK_SIZE
61#define AUDIO_STACK_SIZE STK_MINIMAL_STACK_SIZE
62
63//--------------------------------------------------------------------+
64// MACRO CONSTANT TYPEDEF PROTYPES
65//--------------------------------------------------------------------+
66
67/* Blink pattern
68 * - 250 ms : device not mounted
69 * - 1000 ms : device mounted
70 * - 2500 ms : device is suspended
71 */
72enum {
76};
77
78// task stacks - STK's C API keeps the task control block in its own internal static slot pool
79// (sized via STK_C_KERNEL_MAX_TASKS), so unlike FreeRTOS's xTaskCreateStatic() only the stack
80// memory itself needs to be supplied here.
84
86
87// Audio controls
88// Current states
89bool mute[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX + 1]; // +1 for master channel 0
90uint16_t volume[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX + 1];// +1 for master channel 0
91uint32_t sampFreq;
92uint8_t clkValid;
93
94// Range states
96audio20_control_range_4_n_t(1) sampleFreqRng; // Sample frequency range state
97
98// Audio test data
100uint16_t startVal = 0;
101
102void led_blinking_task(void *param);
103void usb_device_task(void *param);
104void audio_isr_task(void *param);
105
106void board_init_after_tusb(void) {
107 // nothing to do
108}
109
110/*------------- MAIN -------------*/
111int main(int argc, char* argv[]) {
112 (void) argc;
113 (void) argv;
114
115 board_init();
116
117 // shall be done in family.c similar to (CFG_TUSB_OS == OPT_OS_FREERTOS) case
118 {
119 // disable SysTick on init, kernel will manage it
120 SysTick->CTRL &= ~1U;
121
122 // Priority must be less than SVCall to allow Privileged/non-Privileged tasks.
123 NVIC_SetPriority(OTG_FS_IRQn, STK_CORTEX_M_SVCALL_ISR_PRIORITY + 1U);
124 }
125
126 // Init values
128 clkValid = 1;
129
130 sampleFreqRng.wNumSubRanges = 1;
131 sampleFreqRng.subrange[0].bMin = CFG_TUD_AUDIO_FUNC_1_SAMPLE_RATE;
132 sampleFreqRng.subrange[0].bMax = CFG_TUD_AUDIO_FUNC_1_SAMPLE_RATE;
133 sampleFreqRng.subrange[0].bRes = 0;
134
135 // STK kernel/task setup. Unlike FreeRTOS, tasks are created individually via
136 // stk_task_create_privileged()/_user() and only take effect once added with
137 // stk_kernel_add_task() - all of which (for a static kernel) must happen before
138 // stk_kernel_start(). Priorities only matter if STK_C_KERNEL_TYPE_CPU_0 (stk_config.h)
139 // selects sched::SwitchStrategyFP32; with the default round-robin strategy they're a no-op.
142
143 // blinky task
145 stk_task_set_name(blinky_task, "blinky");
146 stk_task_set_priority(blinky_task, 1);
147 stk_kernel_add_task(k, blinky_task);
148
149 // Create a task for tinyusb device stack
151 stk_task_set_name(usb_device_task_hdl, "usbd");
152 stk_task_set_priority(usb_device_task_hdl, 30);
153 stk_kernel_add_task(k, usb_device_task_hdl);
154
155 // Audio receive (I2S) ISR simulation
156 // To simulate a ISR the priority is set to the highest
158 stk_task_set_name(audio_task, "audio");
159 stk_task_set_priority(audio_task, 31);
160 stk_kernel_add_task(k, audio_task);
161
162 // start the scheduler - never returns
164
165 return 0;
166}
167
168// USB Device Driver task
169// This top level thread process all usb events and invoke callbacks
170void usb_device_task(void *param) {
171 (void) param;
172
173 // init device stack on configured roothub port
174 // This should be called after scheduler/kernel is started.
175 // Otherwise it could cause kernel issue since USB IRQ handler does use RTOS queue API.
176 tusb_rhport_init_t dev_init = {
177 .role = TUSB_ROLE_DEVICE,
178 .speed = TUSB_SPEED_AUTO};
179 tusb_init(BOARD_TUD_RHPORT, &dev_init);
180
182
183 // RTOS forever loop
184 while (1) {
185 // tinyusb device task
186 tud_task();
187 }
188}
189
190//--------------------------------------------------------------------+
191// Device callbacks
192//--------------------------------------------------------------------+
193
194// Invoked when device is mounted
198
199// Invoked when device is unmounted
203
204// Invoked when usb bus is suspended
205// remote_wakeup_en : if host allow us to perform remote wakeup
206// Within 7ms, device must draw an average of current less than 2.5 mA from bus
207void tud_suspend_cb(bool remote_wakeup_en) {
208 (void) remote_wakeup_en;
210}
211
212// Invoked when usb bus is resumed
213void tud_resume_cb(void) {
215}
216
217//--------------------------------------------------------------------+
218// AUDIO Task
219//--------------------------------------------------------------------+
220
221// This task simulates an audio receive ISR, one frame is received every 1ms.
222// We assume that the audio data is read from an I2S buffer.
223// In a real application, this would be replaced with actual I2S receive callback.
224void audio_isr_task(void *param) {
225 (void) param;
226
227 while (1) {
228 stk_sleep_ms(1);
229 for (size_t cnt = 0; cnt < sizeof(test_buffer_audio) / 2; cnt++) {
231 }
232
233 tud_audio_write((uint8_t *) test_buffer_audio, sizeof(test_buffer_audio));
234 }
235}
236
237//--------------------------------------------------------------------+
238// Application Callback API Implementations
239//--------------------------------------------------------------------+
240
241// Invoked when audio class specific set request received for an EP
242bool tud_audio_set_req_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff) {
243 (void) rhport;
244 (void) pBuff;
245
246 // We do not support any set range requests here, only current value requests
247 TU_VERIFY(p_request->bRequest == AUDIO20_CS_REQ_CUR);
248
249 // Page 91 in UAC2 specification
250 uint8_t channelNum = TU_U16_LOW(p_request->wValue);
251 uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
252 uint8_t ep = TU_U16_LOW(p_request->wIndex);
253
254 (void) channelNum;
255 (void) ctrlSel;
256 (void) ep;
257
258 return false;// Yet not implemented
259}
260
261// Invoked when audio class specific set request received for an interface
262bool tud_audio_set_req_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff) {
263 (void) rhport;
264 (void) pBuff;
265
266 // We do not support any set range requests here, only current value requests
267 TU_VERIFY(p_request->bRequest == AUDIO20_CS_REQ_CUR);
268
269 // Page 91 in UAC2 specification
270 uint8_t channelNum = TU_U16_LOW(p_request->wValue);
271 uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
272 uint8_t itf = TU_U16_LOW(p_request->wIndex);
273
274 (void) channelNum;
275 (void) ctrlSel;
276 (void) itf;
277
278 return false;// Yet not implemented
279}
280
281// Invoked when audio class specific set request received for an entity
282bool tud_audio_set_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff) {
283 (void) rhport;
284
285 // Page 91 in UAC2 specification
286 uint8_t channelNum = TU_U16_LOW(p_request->wValue);
287 uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
288 uint8_t itf = TU_U16_LOW(p_request->wIndex);
289 uint8_t entityID = TU_U16_HIGH(p_request->wIndex);
290
291 (void) itf;
292
293 // We do not support any set range requests here, only current value requests
294 TU_VERIFY(p_request->bRequest == AUDIO20_CS_REQ_CUR);
295
296 // If request is for our feature unit
297 if (entityID == 2) {
298 switch (ctrlSel) {
299 case AUDIO20_FU_CTRL_MUTE:
300 // Request uses format layout 1
301 TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_1_t));
302
303 mute[channelNum] = ((audio20_control_cur_1_t *) pBuff)->bCur;
304
305 TU_LOG1(" Set Mute: %d of channel: %u\r\n", mute[channelNum], channelNum);
306 return true;
307
308 case AUDIO20_FU_CTRL_VOLUME:
309 // Request uses format layout 2
310 TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_2_t));
311
312 volume[channelNum] = (uint16_t) ((audio20_control_cur_2_t *) pBuff)->bCur;
313 TU_LOG1(" Set Volume: %d dB of channel: %u\r\n", volume[channelNum], channelNum);
314 return true;
315
316 // Unknown/Unsupported control
317 default:
318 TU_BREAKPOINT();
319 return false;
320 }
321 }
322 return false;// Yet not implemented
323}
324
325// Invoked when audio class specific get request received for an EP
326bool tud_audio_get_req_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request) {
327 (void) rhport;
328
329 // Page 91 in UAC2 specification
330 uint8_t channelNum = TU_U16_LOW(p_request->wValue);
331 uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
332 uint8_t ep = TU_U16_LOW(p_request->wIndex);
333
334 (void) channelNum;
335 (void) ctrlSel;
336 (void) ep;
337
338 return false;// Yet not implemented
339}
340
341// Invoked when audio class specific get request received for an interface
342bool tud_audio_get_req_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request) {
343 (void) rhport;
344
345 // Page 91 in UAC2 specification
346 uint8_t channelNum = TU_U16_LOW(p_request->wValue);
347 uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
348 uint8_t itf = TU_U16_LOW(p_request->wIndex);
349
350 (void) channelNum;
351 (void) ctrlSel;
352 (void) itf;
353
354 return false;// Yet not implemented
355}
356
357// Invoked when audio class specific get request received for an entity
358bool tud_audio_get_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request) {
359 (void) rhport;
360
361 // Page 91 in UAC2 specification
362 uint8_t channelNum = TU_U16_LOW(p_request->wValue);
363 uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue);
364 // uint8_t itf = TU_U16_LOW(p_request->wIndex); // Since we have only one audio function implemented, we do not need the itf value
365 uint8_t entityID = TU_U16_HIGH(p_request->wIndex);
366
367 // Input terminal (Microphone input)
368 if (entityID == 1) {
369 switch (ctrlSel) {
370 case AUDIO20_TE_CTRL_CONNECTOR: {
371 // The terminal connector control only has a get request with only the CUR attribute.
372 audio20_desc_channel_cluster_t ret;
373
374 // Those are dummy values for now
375 ret.bNrChannels = 1;
376 ret.bmChannelConfig = (audio20_channel_config_t) 0;
377 ret.iChannelNames = 0;
378
379 TU_LOG1(" Get terminal connector\r\n");
380
381 return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, (void *) &ret, sizeof(ret));
382 } break;
383
384 // Unknown/Unsupported control selector
385 default:
386 TU_BREAKPOINT();
387 return false;
388 }
389 }
390
391 // Feature unit
392 if (entityID == 2) {
393 switch (ctrlSel) {
394 case AUDIO20_FU_CTRL_MUTE:
395 // Audio control mute cur parameter block consists of only one byte - we thus can send it right away
396 // There does not exist a range parameter block for mute
397 TU_LOG1(" Get Mute of channel: %u\r\n", channelNum);
398 return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &mute[channelNum], 1);
399
400 case AUDIO20_FU_CTRL_VOLUME:
401 switch (p_request->bRequest) {
402 case AUDIO20_CS_REQ_CUR:
403 TU_LOG1(" Get Volume of channel: %u\r\n", channelNum);
404 return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &volume[channelNum], sizeof(volume[channelNum]));
405
406 case AUDIO20_CS_REQ_RANGE:
407 TU_LOG1(" Get Volume range of channel: %u\r\n", channelNum);
408
409 // Copy values - only for testing - better is version below
411 ret;
412
413 ret.wNumSubRanges = 1;
414 ret.subrange[0].bMin = -90;// -90 dB
415 ret.subrange[0].bMax = 90; // +90 dB
416 ret.subrange[0].bRes = 1; // 1 dB steps
417
418 return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, (void *) &ret, sizeof(ret));
419
420 // Unknown/Unsupported control
421 default:
422 TU_BREAKPOINT();
423 return false;
424 }
425 break;
426
427 // Unknown/Unsupported control
428 default:
429 TU_BREAKPOINT();
430 return false;
431 }
432 }
433
434 // Clock Source unit
435 if (entityID == 4) {
436 switch (ctrlSel) {
437 case AUDIO20_CS_CTRL_SAM_FREQ:
438 // channelNum is always zero in this case
439 switch (p_request->bRequest) {
440 case AUDIO20_CS_REQ_CUR:
441 TU_LOG1(" Get Sample Freq.\r\n");
442 return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &sampFreq, sizeof(sampFreq));
443
444 case AUDIO20_CS_REQ_RANGE:
445 TU_LOG1(" Get Sample Freq. range\r\n");
446 return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &sampleFreqRng, sizeof(sampleFreqRng));
447
448 // Unknown/Unsupported control
449 default:
450 TU_BREAKPOINT();
451 return false;
452 }
453 break;
454
455 case AUDIO20_CS_CTRL_CLK_VALID:
456 // Only cur attribute exists for this request
457 TU_LOG1(" Get Sample Freq. valid\r\n");
458 return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &clkValid, sizeof(clkValid));
459
460 // Unknown/Unsupported control
461 default:
462 TU_BREAKPOINT();
463 return false;
464 }
465 }
466
467 TU_LOG1(" Unsupported entity: %d\r\n", entityID);
468 return false;// Yet not implemented
469}
470
471bool tud_audio_set_itf_close_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request) {
472 (void) rhport;
473 (void) p_request;
474 startVal = 0;
475
476 return true;
477}
478
479//--------------------------------------------------------------------+
480// BLINKING TASK
481//--------------------------------------------------------------------+
482void led_blinking_task(void *param) {
483 (void) param;
484 static bool led_state = false;
485
486 while (1) {
487 // Blink every interval ms
489
490 board_led_write(led_state);
491 led_state = 1 - led_state;// toggle
492 }
493}
static bool led_state[LED_MAX]
int main()
#define STK_CORTEX_M_SVCALL_ISR_PRIORITY
Priority of the SVCall exception (the most urgent one used by the kernel).
C language binding/interface for SuperTinyKernel RTOS.
stk_task_t * stk_task_create_user(stk_task_entry_t entry, void *arg, stk_word_t *stack, uint32_t stack_size)
Create user-mode task.
Definition stk_c.cpp:662
void stk_task_set_name(stk_task_t *tsk, const char *tname)
Assign human-readable task name (for tracing/debugging).
Definition stk_c.cpp:690
struct stk_kernel_t stk_kernel_t
Opaque handle to a kernel instance.
Definition stk_c.h:188
void stk_kernel_start(stk_kernel_t *k)
Start the scheduler - never returns.
Definition stk_c.cpp:478
stk_add_result_t stk_kernel_add_task(stk_kernel_t *k, stk_task_t *tsk)
Add task to non-HRT kernel (static or dynamic).
Definition stk_c.cpp:506
void stk_sleep_ms(stk_timeout_t ms)
Put current task to sleep (non-HRT kernels only).
Definition stk_c.cpp:799
#define STK_PERIODICITY_DEFAULT
Default tick period (1 ms).
Definition stk_c.h:196
void stk_kernel_init(stk_kernel_t *k, uint32_t tick_period_us)
Initialize kernel with given tick period.
Definition stk_c.cpp:471
stk_task_t * stk_task_create_privileged(stk_task_entry_t entry, void *arg, stk_word_t *stack, uint32_t stack_size)
Create privileged-mode (kernel-mode) task.
Definition stk_c.cpp:650
void stk_task_set_priority(stk_task_t *tsk, uint8_t priority)
Set task priority (used only by Fixed Priority scheduler).
Definition stk_c.cpp:681
stk_kernel_t * stk_kernel_create(uint8_t core_nr)
Create kernel.
Definition stk_c.cpp:403
uintptr_t stk_word_t
CPU register type.
Definition stk_c.h:156
int32_t stk_timeout_t
Timeout value.
Definition stk_c.h:175
uint32_t sampFreq
#define USBD_STACK_SIZE
void tud_umount_cb(void)
void tud_mount_cb(void)
void tud_resume_cb(void)
bool tud_audio_get_req_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request)
uint16_t startVal
static uint32_t blink_interval_ms
audio20_control_range_4_n_t(1) sampleFreqRng
uint16_t volume[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX+1]
bool tud_audio_get_req_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request)
void board_init_after_tusb(void)
audio20_control_range_2_n_t(1) volumeRng[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX+1]
bool mute[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX+1]
void tud_suspend_cb(bool remote_wakeup_en)
#define BLINKY_STACK_SIZE
uint8_t clkValid
bool tud_audio_get_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request)
bool tud_audio_set_req_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff)
bool tud_audio_set_itf_close_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request)
@ BLINK_SUSPENDED
@ BLINK_NOT_MOUNTED
@ BLINK_MOUNTED
uint16_t test_buffer_audio[CFG_TUD_AUDIO_FUNC_1_SAMPLE_RATE/1000 *CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_TX *CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX/2]
bool tud_audio_set_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff)
#define AUDIO_STACK_SIZE
bool tud_audio_set_req_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff)
void usb_device_task(void *param)
static stk_word_t blinky_stack[128U]
static stk_word_t usb_device_stack[((4U *128U/2U) *(CFG_TUSB_DEBUG ? 2U :1U))]
static stk_word_t audio_stack[128U]
void audio_isr_task(void *param)
void led_blinking_task(void *param)
#define CFG_TUD_AUDIO_FUNC_1_SAMPLE_RATE
#define BOARD_TUD_RHPORT
#define CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX
#define CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_TX