//-----------------------------------------------------------------
// Date: 2022-12-28
// Author: RSP @KMUTNB
//-----------------------------------------------------------------
#include <Arduino_FreeRTOS.h>
#include <task.h>
#include <event_groups.h>
// Declare a global variable to be used for task synchronization
EventGroupHandle_t eventgroup;
// Task function prototypes
void task1(void *pvParameters);
void task2(void *pvParameters);
TaskHandle_t task1Handle;
TaskHandle_t task2Handle;
// Note: configMINIMAL_STACK_SIZE is set to 192 (default).
#define TASK_STACK_SIZE (configMINIMAL_STACK_SIZE+16)
const int BUTTON_PIN = 2; // use either D2 or D3 pin
// ISR for the button press
void btn_isr() {
detachInterrupt( digitalPinToInterrupt(BUTTON_PIN) );
// Set the event flag to notify task2
xEventGroupSetBits(eventgroup, 0x01);
}
void enable_btn_isr() {
// Set up the external interrupt on the button pin
attachInterrupt(
digitalPinToInterrupt(BUTTON_PIN),
btn_isr, FALLING
);
}
// Task1 function: waits for a button press and notifies task2
void task1(void *pvParameters) {
(void) pvParameters; // parameters not used
// Enable the external interrupt for the push button
enable_btn_isr();
while (true) {
// Wait indefinitely for the button press event flag
xEventGroupWaitBits(eventgroup, 0x01, pdTRUE, pdFALSE, portMAX_DELAY);
// Button press event has occurred, clear the event flag
xEventGroupClearBits(eventgroup, 0x01);
// Notify task2
xTaskNotifyGive(task2Handle);
// Wait for stable input to avoid button bouncing
uint8_t cnt = 5;
while (true) {
if (digitalRead(BUTTON_PIN)==HIGH) {
if (cnt > 0) {
cnt--;
} else {
break;
}
} else {
cnt = 5;
}
vTaskDelay(1);
}
// Re-enable the external interrupt for the push button
enable_btn_isr();
}
}
// Task2 function: waits for notification from task1
void task2(void *pvParameters) {
(void) pvParameters; // parameters not used
uint8_t count = 0; // button press count
while (true) {
// Wait for notification from task1
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
Serial.print("Button press count: " );
Serial.println( ++count );
}
}
void setup() {
// Initialize Serial
Serial.begin(115200);
// Configure button pin as an input pin with pull-up resistor
pinMode(BUTTON_PIN, INPUT_PULLUP);
// Create an event group
eventgroup = xEventGroupCreate();
// Create task1 and task2 (with task priority set to 1)
xTaskCreate(task1, "Task1", TASK_STACK_SIZE, NULL, 1, &task1Handle);
xTaskCreate(task2, "Task2", TASK_STACK_SIZE, NULL, 1, &task2Handle);
}
void loop() {
// empty
}
//-----------------------------------------------------------------