Skip to content

Instantly share code, notes, and snippets.

@shakram02
Created February 21, 2021 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shakram02/25a486d2864f9ede5cb049899d14c5f9 to your computer and use it in GitHub Desktop.
Save shakram02/25a486d2864f9ede5cb049899d14c5f9 to your computer and use it in GitHub Desktop.
Mailbox example for FreeRTOS using FreeRTOS demo code as a base
/**
*
* Adapted from: https://microcontrollerslab.com/create-mailbox-with-queues-using-freertos-arduino/
*
*/
#include <stdio.h>
#include <pthread.h>
/* Kernel includes. */
#include "FreeRTOS.h"
#include <queue.h>
// Speed control
#define RECEIVER_TICK_MS 100
#define SENDER_TICK_MS 300
#define SENDER_WAIT_MS 0
#define RECEIVER_MESSAGE_WAIT_MS 10
#define QUEUE_SIZE 3
QueueHandle_t mailbox;
void update_mailbox(void *_)
{
while (1)
{
// Get some sample data, number of ticks so far.
uint32_t data = xTaskGetTickCount();
printf("Send: %d\r\n", data);
if (!xQueueSend(mailbox, &data, SENDER_WAIT_MS))
{
printf("Failed to send data, Queue full.\r\n");
}
vTaskDelay(pdMS_TO_TICKS(SENDER_TICK_MS));
}
}
void read_mailbox(void *_)
{
while (1)
{
uint32_t data = 0;
printf("Starting to read Mailbox...\r\n");
fflush(stdout);
// Read an item from the mailbox and wait for RECEIVER_MESSAGE_WAIT_MS ticks max.
if (xQueueReceive(mailbox, &data, pdMS_TO_TICKS(RECEIVER_MESSAGE_WAIT_MS)))
{
// Received an item from mailbox.
printf("Received: %d\r\n", data);
}
else
{
printf("Item not yet available\r\n");
}
vTaskDelay(pdMS_TO_TICKS(RECEIVER_TICK_MS));
}
}
void main_mailbox()
{
// Mailbox that fits for QUEUE_SIZE ints
mailbox = xQueueCreate(QUEUE_SIZE, sizeof(uint32_t));
xTaskCreate(update_mailbox, "Sender", configMINIMAL_STACK_SIZE, NULL, 1, NULL);
xTaskCreate(read_mailbox, "Receiver", configMINIMAL_STACK_SIZE, NULL, 1, NULL);
vTaskStartScheduler();
for (;;)
;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment