I'm writing a simple program to use queues between two tasks, where one task sends data to the queue, and the other task received data from the queue. Here's the code:
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "driver/gpio.h"
// Create a constant that restricts ESP32 to use only one core when creating tasks
#if CONFIGURE_FREERTOS_UNICORE
static const BaseType_t app_cpu = 0;
#else
static const BaseType_t app_cpu = 1;
#endif
static const uint8_t queue_length = 5; // set max length of queue
static QueueHandle_t queue; // handle for the queue
void print_messages(void *parameters) {
int item;
while(1) {
printf("Spaces in queue :: %d\n", uxQueueSpacesAvailable(queue));
if(xQueueReceive(queue, &item, 0) == pdTRUE) {
printf("Item received :: %d\n", item);
}
else {
printf("Item not received\n");
}
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
void send_messages(void *parameters) {
static int num = 0;
while(1) {
printf("Sending num :: %d\n", num);
if(xQueueSend(queue, &num, 0) != pdTRUE) {
printf("Queue is full\n");
}
printf("Sent num\n");
num++;
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
void app_main(void) {
vTaskDelay(1000 / portTICK_PERIOD_MS);
queue = xQueueCreate(queue_length, sizeof(int));
xTaskCreatePinnedToCore(
send_messages, // function handler for the task
"Send messages", // name of task
2048, // stack size for the task
NULL, // pointer to argument we'd like to pass
1, // priority
NULL, // task handler
app_cpu // which core to run
);
xTaskCreatePinnedToCore(
print_messages, // function handler for the task
"Print messages", // name of task
1024, // stack size for the task
NULL, // pointer to argument we'd like to pass
1, // priority
NULL, // task handler
app_cpu // which core to run
);
}
Ideally, the tasks should get scheduled in a round-robin way since their priorities are the same. So, the "Send messages" task should write data to the queue, and the "Print messages" task should receive data from the queue and print it. It works for the first time when num = 0, but after that, from the logs, it seems that the "Send messages" task doesn't get to ever run. Here is how the console looks:
Sending num :: 0
Sent num
Spaces in queue :: 4
Item received :: 0
Spaces in queue :: 5
Item not received
Spaces in queue :: 5
Item not received
Spaces in queue :: 5
Item not received
Spaces in queue :: 5
Item not received
Spaces in queue :: 5
If "Send messages" runs again, then it should print "Sending num :: <value of num>". Am I missing something here? What's wrong with the code?