Binary Semaphore to synchronize an Interrupt with a task in FreeRTOS - c

Hello everyone im doing my first steps with RTOS. Im trying to receive an amount of data using UART in an interrupt mode. I have a Display Task where the commands are being written to a global buffer, and i just created a UART Handler Task where i want to read the bytes. The problems im facing are.
The semaphore i use inside the UART Task is unknown, even though i declared it global in the main function, so the xSemaphoreTake() function has errors there. Maybe a helpful Note: the UART Task is in a seperated file.
Is my implemntation of the HAL_UART_RxCpltCallback and the UART Task clean?
here is the code i wrote:
SemaphoreHandle_t uartInterruptSemaphore = NULL;
int main(void)
{
/* USER CODE BEGIN 1 */
void mainTask(void* param) {
uartInterruptSemaphore = xSemaphoreCreateBinary();
if(uartInterruptSemaphore != NULL) {
// Display Thread with a 2 priority
xTaskCreate(&displayTask, "Display Thread", 1000, &huart4, 2, NULL);
// deferred Interrupt to be synchronized with the Display Task, must have a higher priority than the display task
xTaskCreate(&UartHandlerTask, "UART Handler Task", 1000, &huart4, 3, NULL);
}
for(;;){
}
}
the callback function i wrote:
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *uart_cb) {
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
if(uart_cb->Instance == USART4) {
xSemaphoreGiveFromISR(uartInterruptSemaphore, &xHigherPriorityTaskWoken);
}
portEND_SWITCHING_ISR(xHigherPriorityTaskWoken);
}
and the handler task:
void UartHandlerTask(void* param) {
huart_cache = param;
const uint8_t tmp = rx_byte; //rx byte is global volatile variable
for(;;){
if(xSemaphoreTake(uartInterruptSemaphore, portMAX_DELAY) == pdPASS) {
HAL_UART_Receive_IT((UART_HandleTypeDef *)huart_cache, (uint8_t *)&rx_byte, 1);
// write data to the buffer
RX_interrupt(tmp);
}
}
}

I would recommend getting a better handle on C before trying to use an RTOS. This will also show you a better way of unblocking a task form an interrupt than using a binary semaphore: https://www.freertos.org/2020/09/decrease-ram-footprint-and-accelerate-execution-with-freertos-notifications.html

Related

Event-based task management using FreeRTOS

I'm trying to pick up C, using an esp32. While looking at exactly how FreeRTOS works, I found the following page regarding how to use the tasks, and best practices etc.
https://www.freertos.org/implementing-a-FreeRTOS-task.html
According to this page, to prevent starvation, tasks should be event based. Regarding what I am trying to achieve, I will try to provide a very simplified example.
Background
I have a LCD screen, which should display data from a sensor. The data shown on the LCD will be done using a task, which according to the documentation, should never exit and should be event driven to prevent starvation.
I have a way of controlling the data shown on the LCD screen, which would be a rotary encoder. This encoder can be clicked, which should refresh the sensor's data.
Question
How would I implement the event based tasks, which are described on the FreeRTOS page, in this specific context? I had a look at the documentation and the "simple" example projects on their github, but as a beginner within C and embedded, they were extremely overwhelming.
Simple demo code
void update_sensor_task(void *pvParameters)
{
// Ensure the task keeps on running
for( ; ; )
{
if(event_update_sensor) // How would I be able to notify the task that this should be run?
{
// update the data
}
}
// Tasks should not be returning, but if they happen to do so, ensure a clean exit
vTaskDelete(NULL);
}
void screen_temperature_task(void *pvParameters)
{
for(; ;)
{
if(event_sensor_updated)
{
// Update the lcd screen with the new data
}
}
vTaskDelete(NULL);
}
void on_rotary_clicked(void *pvParameters)
{
// Notify the sensor task that it should be updating?
}
EDIT:
By using what has been marked as the correct answer, I have managed to get it to work by implementing it the following way:
/* Queue used to send and receive the data */
QueueHandle_t xStructQueue = NULL;
/* Struct which shall be used to hold and pass around the data for the LCD screen*/
struct LcdData
{
int current_temp;
int current_humidity;
} xLcdData;
void initialize_queues(void)
{
xLcdData.current_humidity = 0;
xLcdData.current_temp = 0;
xStructQueue = xQueueCreate(
/* The maximum number of items the queue can hold*/
5,
/* The size of each struct, which the queue should be able to hold */
sizeof( xLcdData )
);
if(xStructQueue == NULL)
{
ESP_LOGE(TAG, "Queue has not been initialized successfully");
}
}
void screen_temperature_task_simplified(void *pvParameters)
{
int counter = 0;
for(; ;)
{
struct LcdData xReceivedStructure;
BaseType_t result;
result = xQueueReceive(xStructQueue, &xReceivedStructure, ( TickType_t ) 10);
if(result == pdPASS)
{
counter = counter + 1;
char snum_current_counter[12];
sprintf(snum_current_counter, "%d", counter);
i2c_lcd1602_clear (lcd_info);
i2c_lcd1602_write_string (lcd_info, snum_current_counter);
}
}
vTaskDelete(NULL);
}
void update_sensor_struct(void)
{
xLcdData.current_temp = DHT11_read().temperature;
xLcdData.current_humidity = DHT11_read().humidity;
// Log the results in the console
printf("Temperature is %d \n", xLcdData.current_temp);
printf("Humidity is %d\n", xLcdData.current_humidity);
ESP_LOGI(TAG, "Data has been updated");
}
void on_rotary_clicked_simplified()
{
ESP_LOGI(TAG, "Rotary encoder has been clicked!");
// Update the struct which holds the data
update_sensor_struct();
/* Send the entire struct to the queue */
xQueueSend(
/* The handle of the queue */
xStructQueue,
/* The adress of the struct which should be sent */
(void *) &xLcdData,
/* Block time of 0 says don't block if the queue is already full.
Check the value returned by xQueueSend() to know if the message
was sent to the queue successfully. */
( TickType_t ) 0
);
}
I use FRTOS and event driven development.
The typical flow here would be:
for(;;)
{
BaseType_t result;
result = xQueueReceive(LCD_Event_Queue, &someLCDEvent, QUEUE_TIMEOUT);
if (result == pdPASS)
{
/* We have new event data in someLCDEvent; Use that data to update the LCD */
}
else
{
/* No new event, do some brief idle-time processing if necessary */
}
}
In brief, wait up to QUEUE_TIMEOUT time for a new event to arrive.
If a new event arrives within that timeframe successfully, then process the data in that event and update your screen.
If a new event does not arrive, you have an opportunity to do some other maintenance work.
Designing and defining the structure-type of someLCDEvent, and putting data into the queue is a big topic, and will depend a lot on your specific project.

proper way to create multiple forked threads

I'm creating a timer function for a bit of embedded code that will allow me to bypass certain GPIO checks while a certain process is running, i.e., when the timer is running in a non-blocking manner.
This seems to run just fine the first 11 times the operations occur, but every time, on the 11th iteration the system will crash. The likely culprit is something in how the timer thread is being handled. My guess is there's some bit of memory cleanup that I'm not handling properly and that's leading to memory leaks of some kind. But I'm really not sure.
I can see through debug tracing that the thread is exiting after each iteration.
Here is the timer code:
#include <time.h>
#include <semaphore.h>
#include <pthread.h>
#include <msp432e4_timer.h>
extern void TaskSleep(uint32_t delay);
static bool timerActive;
static sem_t timerSem;
pthread_t timerThread;
pthread_attr_t attrs;
struct sched_param priParam;
static void *msp432e4_timer(void *argUnused) {
sem_wait(&timerSem);
timerActive = true;
sem_post(&timerSem);
TaskSleep(40);
sem_wait(&timerSem);
timerActive = false;
sem_post(&timerSem);
return (NULL);
}
void initTimer() {
int retc;
pthread_attr_init(&attrs);
priParam.sched_priority = 1;
retc = pthread_attr_setschedparam(&attrs, &priParam);
retc |= pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
retc |= pthread_attr_setstacksize(&attrs, 1024);
if (retc != 0) {
// failed to set attributes
while (1) {}
}
timerActive = false;
if((sem_init(&timerSem, 0, 0)) != 0) {
while(1);
}
sem_post(&timerSem);
}
/*
* return true on starting a new timer
* false implies timer already active
*/
void timerStart() {
int retc;
retc = pthread_create(&timerThread, &attrs, msp432e4_timer, NULL);
if (retc != 0) {
// pthread_create() failed
while (1) {}
}
}
/* return true if timer active */
bool timerCheck() {
bool retval;
sem_wait(&timerSem);
retval = timerActive;
sem_post(&timerSem);
return(retval);
}
The TaskSleep function is a call to a freeRTOS TaskDelay function. It's used in many points throughout the system and has never been an issue.
Hopefully someone can point me in the right direction.
But you didn't really post enough of your code to determine where the problems might be, but I thought this might be worth mentioning:
A general problem is that the sample code you have is open loop wrt thread creation; that is there is nothing to throttle it, and if your implementation has a particularly slow thread exit handling, you could have many zombie threads lying around that haven't died yet.
In typical embedded / real time systems, you want to move resource allocation out of the main loop, since it is often non deterministic. So, more often you would create a timer thread, and park it until it is needed:
void *TimerThread(void *arg) {
while (sem_wait(&request) == 0) {
msp432e4_timer(void *arg);
}
return 0
}
void TimerStart(void) {
sem_post(&request);
}

STM32 Uart Interrupt Burst transmit problem

I'm trying to implement uart in interrupt mode, but something go wrong obviously. Here is my problem: I want to send some strings as soon as possible (example: want to send 10 times string "test123") but for some reason that isn't possible (I make some mistake but can't understand where is that mistake). I use STM32CubeIDE, mcu is stm32f407vgt6. After first successful transmit code fall into Error_Handler() which is not acceptable. When I use delays between each transmit all string will be successful transmitted but why that can be done in this way.Here is code
uint8_t TxData[] = "test123\n";
bool flagTxCmpltUsart = true;
for(i = 0; i < 10; i++){`
if(HAL_UART_Transmit_IT(&huart3, TxData, strlen(TxData)) != HAL_OK)
{
Error_Handler();
}
Wait_Unit_Uart_Tx_Is_Complete();
Reset_Uart_Tx_Complete_Flag();}
void Reset_Uart_Tx_Complete_Flag(void)
{
flagTxCmpltUsart = false;
}
void Wait_Unit_Uart_Tx_Is_Complete(void)
{
while(!flagTxCmpltUsart){}
}
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance == USART3)
{
flagTxCmpltUsart = true;
}
}
Since void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) is called in the interrupt context, you should set your complete flag as
volatile bool flagTxCmpltUsart = true;
To make sure the compiler knows that is could change outside of the normal program flow.
You have to check your UART status, you'll get error if the transmission line is busy. Try to insert the following code between each call;
while (HAL_UART_GetState(&UartHandle) != HAL_UART_STATE_READY){
//Do Something..
}

What is the purpose of xTaskAbortDelay function in free rtos?

I have two task in which i am receving data from bluetooth and if i receive a particular hex value , i want a task(which is Toggling LED State) to run on the basis of the received data.
If there was no data received , then both task should run as per they are scheduled.
I have been trying to use xTaskAbortDelay function , the task does run from the input from bluetooth data, however , after that the LED task is running continously.
Does xTaskAbortDelay creating some problem here?
Should I use something else to achieve the same functionality?
TaskHandle_t lora_send_data_handle;
TaskHandle_t ble_send_data_handle;
TaskHandle_t test_data_handle;
static void button_task_check(void * pvParameter)
{
TickType_t xLastWakeTime;
const TickType_t xFrequency = 1024;
xLastWakeTime = xTaskGetTickCount();
while(1)
{
nrf_delay_ms(100);
SEGGER_RTT_printf(0,"%s","INSIDE SWITCHING\r\n");
xTaskAbortDelay(test_data_handle);
vTaskDelayUntil( &xLastWakeTime, (TickType_t) 1024);
}
}
/*TASK TO RUN LEDS CHECK */
static void led_task_check(void * pvParameter)
{
TickType_t xLastWakeTime;
const TickType_t xFrequency = 122880;
xLastWakeTime = xTaskGetTickCount();
while(1)
{
SEGGER_RTT_printf(0,"%s","TEST TASK\r\n");
nrf_gpio_pin_write(RED,1);
nrf_gpio_pin_write(GREEN,1);
nrf_gpio_pin_write(BLUE,1);
nrf_gpio_pin_write(RED,0);
nrf_gpio_pin_write(GREEN,1);
nrf_gpio_pin_write(BLUE,1);
nrf_delay_ms(1000);
nrf_gpio_pin_write(RED,1);
nrf_gpio_pin_write(GREEN,0);
nrf_gpio_pin_write(BLUE,1);
nrf_delay_ms(1000);
nrf_gpio_pin_write(RED,1);
nrf_gpio_pin_write(GREEN,1);
nrf_gpio_pin_write(BLUE,0);
nrf_delay_ms(1000);
nrf_gpio_pin_write(RED,0);
nrf_gpio_pin_write(GREEN,0);
nrf_gpio_pin_write(BLUE,0);
nrf_delay_ms(1000);
vTaskDelayUntil( &xLastWakeTime, (TickType_t) 122880);
}
}
int main(void)
{
uint8_t rx_qspi[255];
SEGGER_RTT_printf(0,"%s","reset\r\n");
nrf_delay_ms(100);
xQueue1 = xQueueCreate(1, 30);
ret_code_t err_code;
err_code = nrf_drv_clock_init();
SEGGER_RTT_WriteString(0, err_code);
UNUSED_VARIABLE(xTaskCreate( button_task_check, "t", \
configMINIMAL_STACK_SIZE + 200, NULL,3, &lora_send_data_handle));
UNUSED_VARIABLE(xTaskCreate(led_task_check, "et", \
configMINIMAL_STACK_SIZE + 200, NULL, 2, &test_data_handle));
vTaskStartScheduler();
while(1);
}
Reputation to low to comment. From what you say, everything is working as you said. Need more information:
What does the LED task looks like?
Do you use preemptive or cooperative scheduler (#define configUSE_PREEMPTION 1 in freertosconfig.h file).
What are the priorities of the three tasks?
Something else to consider is: do you put the task back in BLOCKED state after it has served it's purose? You should check that first. How do you block the task in the first place?
Maybe try using calling vTaskResume( <LED task handle> ) from the bluetooth tasks and calling vTaskSuspend() from the LED task once it has finished it's job. I don't personally think this is the best approach, but it should work.

RTOS MicroC tasking

I've been working on some RTOS MicroC project and whenever I've implemented some function it works just fine outside the task, but whenever I put in the task it just wouldn't do anything. I know I might not get answer to this, but any tips where to start looking would be a big help, thanks in advance.
a_sem = OSSemCreate(1);
static void AppTask1(void *p_arg)
{
(void) p_arg;
INT8U perr;
while (1)
{
OSSemPend(a_sem, 0, &perr);
planeAngles();// Functon that works outside the task
OSSemPost(a_sem);
OSTimeDly(OS_TICKS_PER_SEC/20);
}
}
static void AppTask2(void *p_arg)
{
(void) p_arg;
INT8U perr;
while (1)
{
OSSemPend(a_sem, 0, &perr);
servoTurns(); // Functon that works outside the task
OSSemPost(a_sem);
OSTimeDly(OS_TICKS_PER_SEC/20);
}
}
Both tasks wait on a semaphore, but it is not clear where that semaphore is initially given. It seems likely that neither task ever returns from the OSSemPend call.
Somewhere in your code, before AppTask1 and AppTask2 are created, you should have a line of code like this:
OSSemCreate(a_sem, 1, &perr);
You are creating a semaphore, a_sem with an initial value of 1 so that the first task that calls OSSemPend will successfully acquire the semaphore.
Also, you should not block forever on OSSemPend. Wait for awhile and then check the error status:
OSSemPend(a_sem, 10, &perr);
if(perr == OS_ERR_NONE)
{
/* You have the semaphore */
}
else
{
/* Error! Maybe a timeout */
}

Resources