FreeRTOS Queue example sketch Passes measurements from one FreeRTOS task to another through a queue. Needs Tools > Operating System > FreeRTOS (SMP).
A sampling task reads A0 exactly every 100 ms (vTaskDelayUntil()) and puts each reading on a queue. loop() is a task too: it waits for readings and prints them. The sampling task has the higher priority, so its timing holds even while loop() is busy printing. See FreeRTOS.
- Wiring
- A voltage to measure on A0, e.g. a potentiometer wiper (0-3.3 V).
- Output
- Serial Monitor at 115200 baud:
1203 ms: A0 = 1650 mV
1303 ms: A0 = 1651 mV
#include <FreeRTOS.h>
#include <queue.h>
#include <task.h>
struct Reading {
unsigned long time_ms;
uint32_t millivolts;
};
QueueHandle_t readings;
void sampleTask(void*) {
TickType_t wake = xTaskGetTickCount();
for (;;) {
if (xQueueSend(readings, &r, 0) != pdPASS) {
Serial.println(
"Queue full: reading dropped");
}
vTaskDelayUntil(&wake, pdMS_TO_TICKS(100));
}
}
readings = xQueueCreate(20, sizeof(Reading));
xTaskCreate(sampleTask, "sample", 1024, nullptr, 2, nullptr);
}
Reading r;
if (xQueueReceive(readings, &r, portMAX_DELAY) == pdPASS) {
}
}
SerialUSBClass Serial
USB serial port, the one the Serial Monitor uses.
uint32_t analogReadMillivolts(pin_size_t pin)
Reads an analog pin as a voltage, whatever its ADC and full scale.
void loop(void)
Written by the sketch: runs over and over after setup(), on core 0.
void setup(void)
Written by the sketch: runs once after reset, on core 0.
unsigned long millis(void)
Milliseconds since the board started.