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
low_power/example.cpp
Go to the documentation of this file.
1/*
2 * SuperTinyKernel(TM) RTOS: Lightweight High-Performance Deterministic C++ RTOS for Embedded Systems.
3 *
4 * Source: https://github.com/SuperTinyKernel-RTOS
5 *
6 * Copyright (c) 2022-2026 Neutron Code Limited <stk@neutroncode.com>. All Rights Reserved.
7 * License: MIT License, see LICENSE for a full text.
8 *
9 * --------------------------------------------------------------------------------------------
10 * Low-Power Demo - STM32F407G-DISC1
11 * --------------------------------------------------------------------------------------------
12 *
13 * Hardware used on the STM32F407G-DISC1 discovery board:
14 * * USER button - PA0 (active-HIGH, no external pull needed)
15 * * LEDs - PD12 (GREEN), PD13 (ORANGE), PD14 (RED), PD15 (BLUE)
16 * * Internal ADC - ADC1 channel 16 (on-chip temperature sensor, VBAT/2 mux)
17 *
18 * Behavior:
19 * 1. Three LED tasks run round-robin, each lighting one LED for 1 s at a time.
20 * 2. A periodic Timer (0.5 Hz / 2 s) samples the internal temperature sensor
21 * and publishes each reading into g_AdcPipe; no dedicated ADC task is needed.
22 * 3. When the CPU is idle (all tasks sleeping), IEventOverrider::OnSleep() fires
23 * and selects one of two power-saving modes based on sleep duration:
24 * – Short idle (sleep_ticks < 40): plain Cortex-M4 SLEEP via __WFI();
25 * SysTick wakes the CPU; PLL and ADC remain powered.
26 * – Deep idle (sleep_ticks >= 40): Cortex-M4 STOP mode via the RTC
27 * Wakeup Timer; ADC is suspended, HSE+PLL are restored on wake-up.
28 * 4. Pressing the USER button (PA0) triggers EXTI0_IRQHandler which:
29 * – Toggles the kernel between running and suspended states via
30 * IKernelService::Suspend() / Resume()
31 * – While suspended all LED tasks and the ADC timer are frozen
32 *
33 * Scheduler: KERNEL_STATIC | KERNEL_SYNC | KERNEL_TICKLESS (when STK_TICKLESS_IDLE),
34 * Round-Robin, 4 tasks
35 * (3 LED tasks + 1 Log task; TimerHost adds its own internal tasks).
36 */
37
43
44#include <stdio.h> // for printf()
45
46#include <stk.h>
47#include <sync/stk_sync.h>
48#include <time/stk_time.h>
49#include "example.h"
50
51using namespace bsp;
52
53// ============================================================================
54// ADC sample descriptor
55// ============================================================================
56
61{
63 uint16_t raw;
64};
65
66// ============================================================================
67// Shared state
68// ============================================================================
69
70// One flag bit per LED task; task 0 (RED) goes first.
71static const uint32_t FLAGS_ALL[] = {
72 (1U << LED_RED),
73 (1U << LED_GREEN),
74 (1U << LED_ORANGE)
75};
76
77// Start with the RED task's flag set so it runs first.
79
80// Timeline for a precise LED switching.
82
83// Pipe carrying AdcSample structs from the ADC timer callback to LogTask.
84// Capacity of 8 absorbs short bursts without dropping samples.
86
87// Kernel-suspended flag: set/cleared in the EXTI ISR.
88// Marked volatile so the ISR write is visible to polling code.
89static volatile bool g_KernelSuspended = false;
90
91// ============================================================================
92// Board-specific helpers
93// ============================================================================
94
95namespace Board
96{
97
98// ----------------------------------------------------------------------------
99// GPIO / LED
100// ----------------------------------------------------------------------------
101
102static void LedInit()
103{
104 Led::InitAll(false);
105}
106
107static __stk_forceinline void LedSet(bsp::Led::Id pin, bool on)
108{
109 Led::Set(pin, on);
110}
111
116
117// ----------------------------------------------------------------------------
118// USER button (PA0, active-HIGH) + EXTI0
119// ----------------------------------------------------------------------------
120
121static void ButtonInit()
122{
123 // Enable GPIOA clock
124 RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
125 __DSB();
126
127 // PA0: input, no pull (board has an external pull-down)
128 GPIOA->MODER &= ~(3U << 0); // input
129 GPIOA->PUPDR &= ~(3U << 0); // no pull
130
131 // Route PA0 to EXTI0
132 RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN;
133 __DSB();
134 SYSCFG->EXTICR[0] = (SYSCFG->EXTICR[0] & ~SYSCFG_EXTICR1_EXTI0) | SYSCFG_EXTICR1_EXTI0_PA;
135
136 // EXTI0: rising edge (button press), unmask
137 EXTI->RTSR |= (1U << 0);
138 EXTI->FTSR &= ~(1U << 0);
139 EXTI->IMR |= (1U << 0);
140
141 // Enable EXTI0 interrupt in NVIC, priority below SysTick so it can call
142 // kernel service functions safely (kernel is ISR-safe for Suspend/Resume).
143 NVIC_SetPriority(EXTI0_IRQn, 8);
144 NVIC_EnableIRQ(EXTI0_IRQn);
145}
146
147// ----------------------------------------------------------------------------
148// ADC1 - internal temperature sensor (channel 16)
149// ----------------------------------------------------------------------------
150
151static void AdcInit()
152{
153 // Enable ADC1 and its clock
154 RCC->APB2ENR |= RCC_APB2ENR_ADC1EN;
155 __DSB();
156
157 // ADC common: TSVREFE=1 to enable temp sensor & Vrefint
158 ADC->CCR |= ADC_CCR_TSVREFE;
159
160 // ADC1 config: 12-bit, right-aligned, single conversion
161 ADC1->CR1 = 0; // default: 12-bit resolution
162 ADC1->CR2 = 0; // single conversion, software trigger
163 ADC1->SMPR1 = (7U << 18); // 480 cycles sample time for ch16 (temp sensor needs ≥ 10 us)
164 ADC1->SQR3 = 16U; // sequence: channel 16 (temp sensor)
165 ADC1->SQR1 = 0; // 1 conversion in sequence
166
167 // Power on ADC (ADON) and wait for stabilization
168 ADC1->CR2 |= ADC_CR2_ADON;
169 for (volatile uint32_t i = 0; i < 10000; ++i) {}
170}
171
172// Suspend ADC to save power (called from OnSleep before WFI).
174{
175 ADC1->CR2 &= ~ADC_CR2_ADON;
176}
177
178// Resume ADC after a wake-up event.
180{
181 if ((ADC1->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON)
182 {
183 ADC1->CR2 |= ADC_CR2_ADON;
184 // Short stabilization delay (aprox 3 us at 168 MHz).
185 for (volatile uint32_t i = 0; i < 500; ++i) {}
186 }
187}
188
189// Start a single ADC conversion and return the raw result (blocking).
190static __stk_forceinline uint16_t AdcRead()
191{
192 AdcResume();
193
194 ADC1->SR &= ~ADC_SR_EOC;
195 ADC1->CR2 |= ADC_CR2_SWSTART;
196 while (!(ADC1->SR & ADC_SR_EOC)) {}
197 return static_cast<uint16_t>(ADC1->DR);
198}
199
200static __stk_forceinline float TEMP_ValueToDeg(uint32_t sens)
201{
202 static const float to_V = 3.3f / 4095; // max resolution: V per step
203 static const float slope = 2.5f / 1000; // slope in V
204 static const float v_cal = 1060.0f * (3.3f / 4095); // 26 deg == 1060
205 static const float t_cal = 26; // calibration T
206
207 float temp = (sens * to_V - v_cal) / slope + t_cal;
208
209 return temp;
210}
211
212// ----------------------------------------------------------------------------
213// CPU / PLL
214// ----------------------------------------------------------------------------
215//
216// Restore the PLL-based system clock after returning from STOP mode.
217//
218// On STOP exit the hardware has silently selected HSI (16 MHz) as the
219// system clock source and powered down both HSE and the main PLL.
220// All RCC divider/multiplier fields (PLLM, PLLN, PLLP, PLLQ, AHB/APB
221// prescalers) and FLASH->ACR wait-states are preserved by hardware -
222// we must not touch them. SysTick->LOAD and SysTick->VAL are equally
223// untouched and must stay that way so the in-progress tick interval
224// is not truncated.
225//
226// Sequence (mirrors the PLL bring-up inside SystemClock_Config but
227// without any HAL/SysTick side-effects):
228//
229// 1. Re-enable HSE and wait for it to stabilize.
230// 2. Re-enable the main PLL and wait for lock.
231// 3. Switch the system clock source back to PLL.
232//
233// Must be called with interrupts disabled (called from CpuEnterDeepSleepMode
234// which is already inside a __disable_irq / __enable_irq window).
235// ----------------------------------------------------------------------------
236
238{
239 // -- 1. Re-enable HSE ----------------------------------------------------
240 // DISC1 uses the 8 MHz on-board oscillator as the PLL input (not HSI).
241 // HSEON is in the upper half of RCC->CR so a 32-bit read-modify-write
242 // is safe here (no other bits in that half are volatile at this point).
243 RCC->CR |= RCC_CR_HSEON;
244
245 // Poll HSERDY. On the DISC1 the crystal typically stabilises in
246 // < 2 ms; spinning here is acceptable because interrupts are masked
247 // and we are not inside any scheduler context.
248 while (!(RCC->CR & RCC_CR_HSERDY)) {}
249
250 // -- 2. Re-enable the main PLL -------------------------------------------
251 // PLLON and PLLRDY live in the same RCC->CR register.
252 // PLLM/PLLN/PLLP/PLLQ fields in RCC->PLLCFGR were not disturbed by
253 // STOP, so we only need to set the enable bit and wait for lock.
254 RCC->CR |= RCC_CR_PLLON;
255 while (!(RCC->CR & RCC_CR_PLLRDY)) {}
256
257 // -- 3. Switch system clock source back to PLL ---------------------------
258 // Read-modify-write on RCC->CFGR: clear the SW field (bits [1:0])
259 // and write SW = 10 (PLL selected).
260 // The AHB/APB prescaler fields in the same register are left intact.
261 RCC->CFGR = (RCC->CFGR & ~RCC_CFGR_SW) | RCC_CFGR_SW_PLL;
262
263 // Poll SWS (bits [3:2]) until the hardware confirms the switch.
264 // This typically takes 1-2 AHB cycles after the PLL lock is confirmed.
265 while ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL) {}
266
267 // At this point HCLK is back at 168 MHz. SysTick->LOAD, SysTick->VAL
268 // and the NVIC priority table are completely unchanged.
269}
270
271// Put CPU into a DEEP SLEEP mode.
273{
274 SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
275
276 __DSB();
277 __WFI();
278
279 SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk;
280
281 // Restore CPU frequency: HSE + PLL back to 168 MHz.
283}
284
285// Put CPU into a SLEEP mode.
287{
288 SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk;
289 __DSB();
290 __WFI();
291}
292
293// ----------------------------------------------------------------------------
294// RTC Wakeup Timer
295// ----------------------------------------------------------------------------
296//
297// The STM32F407 RTC wakeup timer is clocked from LSI (~32 kHz) through
298// the RTC prescaler and survives in STOP mode - making it the correct
299// timed wake-up source for deep sleep on this device.
300//
301// Clock chain selected here:
302// LSI (~32 kHz) -> RTC/16 divider -> WUCKSEL = 000
303// Effective rate = 32000 / 16 = 2000 counts/s -> 0.5 ms per count
304//
305// Conversion: WUTR value = sleep_ticks * 2 (for 1 ms kernel ticks)
306//
307// A 1-tick guard (2 counts) is subtracted so the wakeup fires marginally
308// before the deadline, letting SysTick close the residual gap normally.
309//
310// The RTC wakeup line is internally connected to EXTI line 22. That line
311// must be unmasked and its rising-edge trigger enabled before the wakeup
312// interrupt can reach the NVIC.
313// ----------------------------------------------------------------------------
314
315const uint32_t RTC_WKUP_COUNTS_PER_TICK = 2U; // at RTC/16, LSI~32kHz
316const uint32_t RTC_WKUP_GUARD_COUNTS = 2U; // 1-tick guard
317const uint32_t RTC_WKUP_MAX_COUNT = 0xFFFFU; // 16-bit WUTR
318
319// Initialize the RTC wakeup timer once at startup.
320// Configures LSI as the RTC clock source and prepares EXTI line 22.
321// The RTC write-protection and init-mode sequences follow RM0090 27.3.
322static void RtcWakeupInit()
323{
324 // -- 1. Start LSI --------------------------------------------------------
325 RCC->CSR |= RCC_CSR_LSION;
326 while (!(RCC->CSR & RCC_CSR_LSIRDY)) {}
327
328 // -- 2. Select LSI as the RTC clock source (RTCSEL = 10) -----------------
329 // This field can only be written once after a backup-domain reset.
330 // If already set to LSI we skip it to avoid a needless domain reset.
331 RCC->APB1ENR |= RCC_APB1ENR_PWREN;
332 __DSB();
333 PWR->CR |= PWR_CR_DBP; // unlock backup domain
334
335 if ((RCC->BDCR & RCC_BDCR_RTCSEL) != RCC_BDCR_RTCSEL_1)
336 {
337 // Reset backup domain, then re-select LSI
338 RCC->BDCR |= RCC_BDCR_BDRST;
339 RCC->BDCR &= ~RCC_BDCR_BDRST;
340 RCC->BDCR |= RCC_BDCR_RTCSEL_1; // 10 = LSI
341 }
342
343 // -- 3. Enable RTC peripheral clock --------------------------------------
344 RCC->BDCR |= RCC_BDCR_RTCEN;
345 __DSB();
346
347 // -- 4. Disable RTC write protection (magic keys per RM0090 27.3.7) ------
348 RTC->WPR = 0xCA;
349 RTC->WPR = 0x53;
350
351 // -- 5. Enter init mode to set prescalers (required by RM0090) -----------
352 RTC->ISR |= RTC_ISR_INIT;
353 while (!(RTC->ISR & RTC_ISR_INITF)) {}
354
355 // Async prescaler = 127, Sync prescaler = 249
356 // f_ck_apre = 32000/(127+1) = 250 Hz (calendar - not used here)
357 // Wakeup timer ignores these and uses its own WUCKSEL divider.
358 RTC->PRER = (127U << RTC_PRER_PREDIV_A_Pos) | (249U << RTC_PRER_PREDIV_S_Pos);
359
360 // Exit init mode
361 RTC->ISR &= ~RTC_ISR_INIT;
362
363 // -- 6. Re-enable write protection ---------------------------------------
364 RTC->WPR = 0xFF;
365
366 // -- 7. Route RTC wakeup to NVIC via EXTI line 22 ------------------------
367 // Rising edge trigger; interrupt (not event) mode.
368 EXTI->IMR |= (1U << 22);
369 EXTI->RTSR |= (1U << 22);
370 EXTI->FTSR &= ~(1U << 22);
371
372 NVIC_SetPriority(RTC_WKUP_IRQn, 12); // low priority - wake-up only
373 NVIC_EnableIRQ(RTC_WKUP_IRQn);
374}
375
376// Arm the RTC wakeup timer to fire after `sleep_ticks` kernel ticks.
377// Must be called with interrupts disabled (called from OnSleep critical window).
379{
380 // Compute WUTR value, clamp to 16-bit range, apply guard.
381 uint32_t counts = static_cast<uint32_t>(sleep_ticks) * RTC_WKUP_COUNTS_PER_TICK;
382 if (counts > RTC_WKUP_MAX_COUNT)
383 counts = RTC_WKUP_MAX_COUNT;
384 if (counts > RTC_WKUP_GUARD_COUNTS)
385 counts -= RTC_WKUP_GUARD_COUNTS;
386 else
387 counts = 1U; // minimum meaningful reload
388
389 // Unlock RTC registers (magic keys per RM0090 27.3.7).
390 RTC->WPR = 0xCA;
391 RTC->WPR = 0x53;
392
393 // Disable wakeup timer and wait until we are allowed to write WUTR
394 // (hardware clears WUTWF when the timer is running).
395 RTC->CR &= ~RTC_CR_WUTE;
396 while (!(RTC->ISR & RTC_ISR_WUTWF)) {}
397
398 // Clear any stale wakeup flag
399 RTC->ISR &= ~RTC_ISR_WUTF;
400 EXTI->PR = (1U << 22); // clear EXTI pending
401
402 // Select RTC/16 clock for the wakeup counter (WUCKSEL = 000).
403 RTC->CR = (RTC->CR & ~RTC_CR_WUCKSEL) | 0x0U;
404
405 // Load the auto-reload value (counts – 1 per RM0090: timer fires after
406 // WUTR+1 ck_wut cycles, so subtract 1 to get the exact period).
407 RTC->WUTR = (counts > 0U) ? (counts - 1U) : 0U;
408
409 // Enable wakeup timer + interrupt.
410 RTC->CR |= RTC_CR_WUTIE | RTC_CR_WUTE;
411
412 // Re-enable write protection.
413 RTC->WPR = 0xFF;
414}
415
416// Disarm the RTC wakeup timer after the CPU wakes.
417// Safe to call even if the timer already fired.
419{
420 // Unlock RTC registers (magic keys per RM0090 27.3.7).
421 RTC->WPR = 0xCA;
422 RTC->WPR = 0x53;
423
424 RTC->CR &= ~(RTC_CR_WUTE | RTC_CR_WUTIE);
425 RTC->ISR &= ~RTC_ISR_WUTF;
426
427 // Re-enable write protection.
428 RTC->WPR = 0xFF;
429
430 // Clear EXTI pending line.
431 EXTI->PR = (1U << 22);
432}
433
434} // namespace Board
435
436// ============================================================================
437// RTC Wakeup ISR
438// ============================================================================
439//
440// Fires on EXTI line 22 when the RTC wakeup counter expires.
441// Its only job is to clear the RTC and EXTI flags so the interrupt does not
442// re-trigger. The kernel's SysTick ISR advances the tick counter after PLL is
443// restored by RestorePllClock.
444// ============================================================================
445
446extern "C" void RTC_WKUP_IRQHandler()
447{
448 // Clear the RTC wakeup flag (inside write-protected domain)
449 RTC->WPR = 0xCA;
450 RTC->WPR = 0x53;
451 RTC->ISR &= ~RTC_ISR_WUTF;
452 RTC->WPR = 0xFF;
453
454 // Clear EXTI line 22 pending bit
455 EXTI->PR = (1U << 22);
456}
457
458// ============================================================================
459// IEventOverrider - low-power sleep hook
460// ============================================================================
461//
462// The kernel calls OnSleep() whenever all tasks are sleeping and the CPU
463// would otherwise spin-wait until the next tick. Returning true tells the
464// kernel that we handled the idle period ourselves.
465// ============================================================================
466
468{
469public:
498 bool OnSleep(stk::Timeout sleep_ticks) override
499 {
500 // Note: For extended processing here we must increase the stack of
501 // the sleep task using STK_SLEEP_TRAP_STACK_SIZE in stk_config.h.
502 // Based on processing inside OnSleep you would need more or less
503 // stack. 256 looks optimal for this implementation.
504 // You can always inspect Kernel::m_sleep_trap->memory stack array
505 // and check how it is filled (not touched memory is filled with
506 // STK_STACK_MEMORY_FILLER.
508
509 enum {
512 };
513
514 if ((sleep_ticks >= TICKS_DEEP_SLEEP) || g_KernelSuspended)
515 {
517
518 // 1. Arm RTC wakeup timer and suspend kernel
519 // Skip when kernel is suspended indefinitely - the USER button
520 // EXTI0 is the sole intended wake-up source in that state.
522 {
523 // Arm RTC wakeup timer
524 Board::RtcWakeupArm(sleep_ticks);
525
526 // Suspend kernel by turning off its ticking timer.
527 // We ignore returned ticks as they will be equal to sleep_ticks here.
528 STK_UNUSED(kernel->Suspend());
529 }
530
531 // 2. Power down ADC to cut its quiescent current during STOP.
533
534 // 3. Enter STOP mode. Returns after any enabled interrupt fires.
535 // RestorePllClock() inside brings HSE + PLL back to 168 MHz.
536 // Interrupts must be enabled before WFI so any IRQ can wake us.
538
539 // 4. Disarm RTC wakeup (clears flags; safe if already fired).
541
542 // 5. Restore ADC so the ADC timer finds it powered on next conversion.
544
545 // 6. Resume scheduling.
547 {
548 // Resume with number of slept ticks to avoid time skew.
549 kernel->Resume(sleep_ticks);
550
551 // We return false in order to avoid re-entry to OnSleep() again
552 // the driver will wait in a Idle sleep until the context switch.
553 return false;
554 }
555 }
556 else
557 if (sleep_ticks > TICKS_IDLE_SLEEP)
558 {
559 // 1. Power down ADC to cut its quiescent current during STOP.
561
562 // 2. Short idle - plain SLEEP mode.
563 // SysTick (or EXTI0) wakes the CPU at the next tick boundary.
564 // PLL never stops; ADC stays powered; no clock restore needed.
566
567 // 3. Restore ADC so the ADC timer finds it powered on next conversion.
569 }
570 else
571 {
572 // Short idle - plain SLEEP mode.
573 // SysTick (or EXTI0) wakes the CPU at the next tick boundary.
574 // PLL never stops; ADC stays powered; no clock restore needed.
576 }
577
578 // Return true so that driver would re-enter OnSleep() again and we
579 // could continue sleeping which could be broken by some ISR in the
580 // system.
581 return true;
582 }
583};
584
585// ============================================================================
586// Task stack size
587// ============================================================================
588
589#ifdef _PICO_H
590enum { TASK_STACK_SIZE = 1024 };
591#else
592enum { TASK_STACK_SIZE = 256 };
593#endif
594
595// ============================================================================
596// LED task
597// ============================================================================
598
599template <stk::EAccessMode _AccessMode>
600class LedTask final : public stk::Task<TASK_STACK_SIZE, _AccessMode>
601{
602 uint8_t m_task_id;
603 const char *m_name;
604 uint32_t m_my_flag;
605 uint32_t m_next_flag;
606
607public:
608 LedTask(uint8_t task_id, const char *name)
609 : m_task_id(task_id),
610 m_name(name),
611 m_my_flag(FLAGS_ALL[task_id]),
612 m_next_flag(FLAGS_ALL[(task_id + 1) % 3])
613 {}
614
615 const char *GetTraceName() const override { return m_name; }
616
617private:
618 void Run() override
619 {
620 // get a start of the timeline (race is acceptable here)
622
623 while (true)
624 {
625 // block until this task's flag is set; auto-cleared on return
628 continue;
629
630 // Atomically switch the active LED.
631 {
633 SwitchOnLED(static_cast<LedId>(m_task_id));
634 }
635
636 // sleep 1s drift-free and then delegate work to the next task
637 // we could use simple stk::Sleep() but due to other work around Sleep call we
638 // will get a time drift, STK allows to sleep until exact timestamp making it
639 // possible precise sleeping with 1 tick precision, you could also use
640 // time::TimerHost for timer-related tasks (see related 'timer' example)
642
643 // hand off to the next task
645 }
646 }
647
648 static void SwitchOnLED(uint8_t id)
649 {
652 Board::LedSet(bsp::Led::ORANGE, id == 2); // DISC1 has no BLUE user LED at the same position
653 Board::LedSet(bsp::Led::BLUE, false); // keep BLUE as "system suspended" indicator (see ISR)
654 }
655};
656
657// ============================================================================
658// ADC timer - fires every 2 s, samples the internal temperature sensor,
659// and publishes each reading into g_AdcPipe.
660//
661// Replaces the former AdcTask: no dedicated kernel task is consumed.
662// The callback executes in the TimerHost handler task context; it must
663// complete quickly and must not block.
664// ============================================================================
665
666class AdcTimer final : public stk::time::Timer
667{
668public:
669 void OnExpired(stk::time::TimerHost * /*host*/) override
670 {
671 // Perform a single blocking ADC conversion.
672 // Board::AdcRead() is a tight spin on EOC — acceptable here because
673 // the conversion takes < 5 µs (480 sample cycles @ 21 MHz ADC clock).
674 AdcSample sample;
675 sample.raw = Board::AdcRead();
676 sample.timestamp = stk::GetTicks();
677
678 // Push the sample into the pipe (non-blocking).
679 // TryWrite() is used so the handler task is never blocked by a slow
680 // consumer; if the pipe is full (LogTask is stalled) the oldest
681 // unread samples will accumulate until the pipe drains.
682 // Switch to Write() (blocking) if you must not drop samples, but be
683 // aware that blocking inside OnExpired() stalls ALL pending timers.
684 if (!g_AdcPipe.TryWrite(sample))
685 {
686 // Pipe full — log task is not keeping up.
687 // The sample is dropped; add an overflow counter here if needed.
688 }
689 }
690};
691
692// ============================================================================
693// Log task - blocks on g_AdcPipe and logs every received sample.
694// ============================================================================
695//
696// Design notes:
697// - Read() blocks indefinitely (WAIT_INFINITE) so the task consumes zero
698// CPU time when no ADC data is available - no busy-polling.
699// - printf() is called outside any lock; the task owns its own stack-local
700// copy of the sample, so no shared-state issues arise.
701// - A 10 s timeout on Read() is used instead of WAIT_INFINITE so the task
702// can periodically print a "heartbeat" even if the ADC timer is suspended
703// (e.g. when the kernel is paused by the USER button).
704// ============================================================================
705
706template <stk::EAccessMode _AccessMode>
707class LogTask final : public stk::Task<TASK_STACK_SIZE, _AccessMode>
708{
709public:
710 const char *GetTraceName() const override { return "log"; }
711
712private:
713 void Run() override
714 {
715 while (true)
716 {
717 AdcSample sample;
718 sample.timestamp = stk::GetTicks();
719
720 // Block until a sample arrives or 2 s elapse.
721 if (!g_AdcPipe.Read(sample, stk::GetTicksFromMs(10000)))
722 {
723 // Timeout: ADC timer may be frozen (misbehavior).
724 // Print a warning so the console stays active.
725 printf("[log] t=%d s warning: no ADC sample for 10 s\n",
726 static_cast<int>(sample.timestamp / 1000));
727 }
728 else
729 {
730 // Convert raw ADC counts to degrees Celsius.
731 const float deg_c = Board::TEMP_ValueToDeg(sample.raw);
732
733 // Scale by 100 to preserve 2 decimal places.
734 int temp_scaled = (int)(deg_c * 100.0f);
735 int temp_int = temp_scaled / 100;
736 int temp_frac = temp_scaled % 100;
737 if (temp_frac < 0)
738 {
739 temp_frac = -temp_frac; // ensure fractional part is positive
740 }
741
742 // Log: tick timestamp, raw counts, and temperature.
743 printf("[log] t=%d s raw=%-4d temp=%d.%02d C\n",
744 (int)(sample.timestamp / 1000),
745 (int)sample.raw,
746 temp_int,
747 temp_frac);
748 }
749 }
750 }
751};
752
753// ============================================================================
754// EXTI0 ISR - USER button on PA0
755// ============================================================================
756//
757// Toggles the kernel between running and suspended states.
758// While suspended all task wake-ups and context switches are frozen,
759// which effectively pauses the entire application.
760//
761// The BLUE LED acts as a "suspended" indicator:
762// ON -> kernel is suspended
763// OFF -> kernel is running normally
764// ============================================================================
765
766extern "C" void EXTI0_IRQHandler()
767{
769
771 {
772 // Suspend() is ISR-safe. It returns the number of ticks until the
773 // nearest scheduled wake-up (useful for tickless operation), but we
774 // do not need that value here since we resume on the next button press.
775 kernel->Suspend();
776
777 g_KernelSuspended = true;
778
779 // Light the BLUE LED to signal the suspended state, all other - off.
781 }
782 else
783 {
784 // Resume() with 0 ticks because we could sleep indefinitely long, so it
785 // is similar to restore from hibernation.
786 kernel->Resume(0);
787
788 g_KernelSuspended = false;
789
790 // Extinguish the suspended-state indicator.
792 }
793
794 // Debounce button press
795 for (volatile int i = 0; i < 1000000; ++i);
796
797 // Clear the EXTI pending bit first to acknowledge the interrupt.
798 EXTI->PR = (1U << 0);
799}
800
801// ============================================================================
802// RunExample - entry point
803// ============================================================================
804
806{
807 using namespace stk;
808
809 // - Board initialization -------------------------------------------------
810 Board::LedInit(); // LEDs
811 Board::AdcInit(); // CPU temperature reader
812 Board::ButtonInit(); // Standby button
813 Board::RtcWakeupInit(); // RTC for deep-sleep wake-up
814
815 // - Kernel setup ---------------------------------------------------------
816 // KERNEL_STATIC - tasks never exit (required for the while(true) pattern).
817 // KERNEL_TICKLESS - kernel suppresses SysTick firings when all tasks sleep,
818 // amplifying the power benefit of OnSleep()+WFI.
819 //
820 // Task count reduced from 5 to 4: the former AdcTask is replaced by an
821 // AdcTimer managed by TimerHost (which adds its own internal tasks).
822 const uint8_t KernelMode = KERNEL_STATIC | KERNEL_SYNC | (STK_TICKLESS_IDLE ? KERNEL_TICKLESS : 0);
823
824 // 4 user tasks: 3 LED + 1 Log.
825 // TimerHost::TASK_COUNT additional internal tasks are registered separately.
827
828 // Tasks run in privileged mode - GPIO and ADC registers require it on
829 // Cortex-M4 when the MPU restricts peripheral access to privileged code.
830 static LedTask<ACCESS_PRIVILEGED> task_red (0, "LED-red");
831 static LedTask<ACCESS_PRIVILEGED> task_grn (1, "LED-grn");
832 static LedTask<ACCESS_PRIVILEGED> task_org (2, "LED-org");
833 static LogTask<ACCESS_PRIVILEGED> task_log;
834
835 kernel.Initialize();
836
837 // - TimerHost setup ------------------------------------------------------
838 // Initialize the host and register it with the kernel. Must be called
839 // after kernel.Initialize() and before kernel.Start().
840 // ACCESS_PRIVILEGED is required so the handler task can call AdcRead()
841 // which accesses peripheral registers.
842 static stk::time::TimerHost timer_host;
843 timer_host.Initialize(&kernel, ACCESS_PRIVILEGED);
844
845 // ADC sampling timer: periodic, fires every 1 s (~1 Hz).
846 static AdcTimer adc_timer;
847 const uint32_t adc_period = stk::GetTicksFromMs(2000);
848 timer_host.Start(adc_timer, adc_period, adc_period);
849
850 // - Low-power event overrider --------------------------------------------
851 // Must be registered before kernel.Start() so the platform driver sees it
852 // from the very first idle period.
853 static LowPowerOverrider lp_overrider;
854 kernel.GetPlatform()->SetEventOverrider(&lp_overrider);
855
856 // - Start scheduling -----------------------------------------------------
857 kernel.AddTask(&task_red);
858 kernel.AddTask(&task_grn);
859 kernel.AddTask(&task_org);
860 kernel.AddTask(&task_log);
861
862 // Start() never returns in KERNEL_STATIC mode.
863 kernel.Start();
864
865 STK_ASSERT(false);
866}
LedId
Definition led.h:16
@ LED_ORANGE
Definition led.h:18
@ LED_GREEN
Definition led.h:17
@ LED_RED
Definition led.h:19
Top-level STK include. Provides the Kernel class template and all built-in task-switching strategies.
#define STK_UNUSED(X)
Explicitly marks a variable as unused to suppress compiler warnings.
Definition stk_defs.h:715
#define __stk_forceinline
Forces compiler to always inline the decorated function, regardless of optimisation level.
Definition stk_defs.h:270
#define STK_SLEEP_TRAP_STACK_SIZE
Stack size for the sleep trap in elements of Word (default: STK_STACK_SIZE_MIN).
Definition stk_defs.h:659
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
Definition stk_defs.h:532
#define STK_STATIC_ASSERT(X)
Compile-time assertion. Produces a compilation error if X is false.
Definition stk_defs.h:560
Collection of synchronization primitives (stk::sync namespace).
Collection of time-related primitives (stk::time namespace).
Namespace of STK package.
@ ACCESS_PRIVILEGED
Privileged access mode (access to hardware is fully unrestricted).
Definition stk_common.h:38
int64_t Ticks
Ticks value.
Definition stk_common.h:221
int32_t Timeout
Timeout time (ticks).
Definition stk_common.h:216
static bool SleepUntil(Ticks timestamp)
Put calling process into a sleep state until the specified timestamp.
Definition stk_helper.h:523
static Ticks GetTicksFromMs(Time ms, uint32_t resolution)
Convert milliseconds to ticks.
Definition stk_helper.h:406
static Ticks GetTicks()
Get number of ticks elapsed since kernel start.
Definition stk_helper.h:448
@ KERNEL_TICKLESS
Tickless mode. To use this mode STK_TICKLESS_IDLE must be defined to 1 in stk_config....
Definition stk_common.h:51
@ KERNEL_SYNC
Synchronization support (see Event).
Definition stk_common.h:50
@ KERNEL_STATIC
All tasks are static and can not exit.
Definition stk_common.h:47
EventFlagsT< uint32_t > EventFlags
Default event flags group with a 32-bit flags word (31 usable flags, bit 31 reserved).
const uint32_t RTC_WKUP_COUNTS_PER_TICK
static __stk_forceinline void LedSwitchOnExclusive(bsp::Led::Id pin)
static __stk_forceinline void AdcResume()
static void AdcInit()
static void ButtonInit()
static __stk_forceinline void RestorePllClock()
static __stk_forceinline void CpuEnterSleepMode()
static __stk_forceinline void RtcWakeupArm(stk::Timeout sleep_ticks)
static __stk_forceinline float TEMP_ValueToDeg(uint32_t sens)
const uint32_t RTC_WKUP_GUARD_COUNTS
static __stk_forceinline uint16_t AdcRead()
const uint32_t RTC_WKUP_MAX_COUNT
static void RtcWakeupInit()
static __stk_forceinline void CpuEnterDeepSleepMode()
static __stk_forceinline void RtcWakeupDisarm()
static void LedInit()
static __stk_forceinline void AdcSuspend()
static __stk_forceinline void LedSet(bsp::Led::Id pin, bool on)
Definition cpu.h:17
Concrete implementation of IKernel.
Definition stk.h:102
void Start() override
Start the scheduler. This call does not return until all tasks have exited (KERNEL_DYNAMIC mode) or i...
Definition stk.h:1999
EAddResult AddTask(ITask *user_task) override
Register task for a soft real-time (SRT) scheduling.
Definition stk.h:1465
IPlatform * GetPlatform() override
Get platform driver instance owned by this kernel.
Definition stk.h:2034
void Initialize(uint32_t resolution_us=PERIODICITY_DEFAULT) override
Initialize kernel.
Definition stk.h:1425
RAII instance that enters the critical section on construction and exits it on destruction.
Definition stk_arch.h:495
virtual void SetEventOverrider(IEventOverrider *overrider, bool non_secure=false)=0
Set platform event overrider.
Interface for a platform event overrider.
Interface for the kernel services exposed to the user processes during run-time when Kernel started s...
static IKernelService * GetInstance()
Get CPU-local instance of the kernel service.
virtual void Resume(Timeout elapsed_ticks)=0
Resume scheduling after a prior Suspend() call.
virtual Timeout Suspend()=0
Suspend scheduling.
Partial implementation of the user task.
Definition stk_helper.h:98
static constexpr uint32_t OPT_WAIT_ANY
static bool IsError(uint32_t result)
Thread-safe, type-safe FIFO communication pipe with internal storage.
Abstract base class for a timer managed by TimerHost.
Software timer multiplexer that manages multiple Timer instances on top of a small fixed set of kerne...
EResult Start(Timer &tmr, uint32_t delay, uint32_t period=0)
Start timer.
EAddResult Initialize(IKernel *kernel, EAccessMode mode, const Config &cfg=Config())
Initialize timer host instance.
uint32_t m_my_flag
const char * m_name
LedState m_task_id
LedTask(uint8_t task_id, const char *name)
const char * GetTraceName() const override
Get task trace name set by application.
uint32_t m_next_flag
void Run() override
Entry point of the user task.
static void SwitchOnLED(uint8_t id)
static constexpr Id GREEN
Definition led.h:34
static constexpr Id RED
Definition led.h:36
static constexpr Id ORANGE
Definition led.h:35
LedId Id
Definition led.h:32
static constexpr Id BLUE
Definition led.h:37
static void InitAll(bool init_state)
Definition led.h:40
static void SwitchOnExclusive(Id led)
Definition led.h:48
static void Set(Id led, bool state)
One ADC reading delivered through the pipe.
uint16_t raw
raw 12-bit ADC value
stk::Ticks timestamp
kernel tick at the time of conversion
bool OnSleep(stk::Timeout sleep_ticks) override
Called by the kernel when it enters the idle/sleep state.
void OnExpired(stk::time::TimerHost *) override
Callback invoked when this timer expires.
void Run() override
Entry point of the user task.
const char * GetTraceName() const override
Get task trace name set by application.
static stk::Ticks g_Timeline
static const uint32_t FLAGS_ALL[]
static stk::sync::EventFlags g_TaskFlags(FLAGS_ALL[LED_RED])
static stk::sync::PipeT< AdcSample, 8 > g_AdcPipe
static volatile bool g_KernelSuspended
void RTC_WKUP_IRQHandler()
void RunExample()
void EXTI0_IRQHandler()
static stk::sync::EventFlags g_TaskFlags(FLAGS_ALL[LED_RED])
#define TICKS_IDLE_SLEEP
#define TASK_STACK_SIZE
#define TICKS_DEEP_SLEEP
static void SwitchOnLED()