FreeRTOS. Программная очередь почты.
Тема статьи: программная очередь почты (mail queue). Немного C++ обвертки для FreeRTOS, грамотнее говоря, правильнее сказать cmsis – rtos, потому что, STM реализация FreeRTOS написана в концепции cmsis. Пример статьи – это простой обмен сообщениями с переключениям состояний светодиода. Поля очереди почты инкриминируется автоматически при отправке и верном приеме почты, посходит проверка на отправленное сообщение, а так же на прием почты.
Очередь почты напоминает очереди сообщений, но данные, которые передаются состоят из блоков памяти, которые должны быть выделены (до передачи в данные) и освобождены (после из данных). Очередь почты использует пул памяти для создания отформатированных блоков памяти и передачи указателя на эти блоки в очереди сообщений. Это позволяет данным, остаться в памяти выделенного блока, а только указатель перемещается между отдельными потоками. Это является преимуществом над сообщениями, которые могут передавать только 32-битное значение или указатель. Использование функций почтовой очереди, вы можете контролировать, отправлять, получать, или ждать почту.
Редактируем базовый пример для STM32746G-Discovery -> “..\STM32Cube_FW_F7_V1.3.0\Projects\STM32746G-Discovery\Applications\FreeRTOS\FreeRTOS_Mail”.
Для .cpp файлов нужно выставить –cpp11(misc controls).
//main.cpp #ifdef __cplusplus extern "C" { #endif #include "main.h" #include "cmsis_os.h" #ifdef __cplusplus } #endif #include "sys_freertos.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ #define blckqSTACK_SIZE configMINIMAL_STACK_SIZE uint32_t ProducerValue1 = 0, ProducerValue2 = 0; uint8_t ProducerValue3 = 0; uint32_t ConsumerValue1 = 0, ConsumerValue2 = 0; uint8_t ConsumerValue3 = 0; /* Private function prototypes -----------------------------------------------*/ /* Thread function that creates a mail and posts it on a mail queue. */ static void MailQueueProducer (const void *argument); /* Thread function that receives mail , remove it from a mail queue and checks that it is the expected mail. */ static void MailQueueConsumer (const void *argument); static void SystemClock_Config(void); static void CPU_CACHE_Enable(void); FreeRTOS sys; MailBox mail(1); osMailQId mailId; /* Private functions ---------------------------------------------------------*/ /** * @brief Main program * @param None * @retval None */ int main(void) { /* Enable the CPU Cache */ CPU_CACHE_Enable(); /* STM32F7xx HAL library initialization: - Configure the Flash ART accelerator on ITCM interface - Configure the Systick to generate an interrupt each 1 msec - Set NVIC Group Priority to 4 - Low Level Initialization */ HAL_Init(); /* Configure the system clock to 216 Mhz */ SystemClock_Config(); /* Initialize LED1 */ BSP_LED_Init(LED1); /* create mail queue */ mailId = sys.MailCreate(&mail.os_mailQ_def_name, NULL); /* Note the producer has a lower priority than the consumer when the tasks are spawned. */ Thread mail_r((char *)"mail_r", MailQueueConsumer, osPriorityBelowNormal, 0, blckqSTACK_SIZE); Thread mail_t((char *)"mail_t", MailQueueProducer, osPriorityBelowNormal, 0, blckqSTACK_SIZE); sys.ThreadCreate(&mail_r.os_thread_def_name, NULL); sys.ThreadCreate(&mail_t.os_thread_def_name, NULL); sys.StartScheduler(); /* We should never get here as control is now taken by the scheduler */ for(;;); } /** * @brief Mail Producer Thread. * @param argument: Not used * @retval None */ static void MailQueueProducer(const void *argument) { sys_Amail_TypeDef *pTMail; for(;;) { pTMail = (sys_Amail_TypeDef *)osMailAlloc(mailId, osWaitForever); /* Allocate memory */ /* Set the mail content */ //Установка полей сообщения pTMail->var1 = ProducerValue1; pTMail->var2 = ProducerValue2; pTMail->var3 = ProducerValue3; //При начальной инициализации сообщения, все поля нулевые. //Проверка на оправленное сообщение. if(osMailPut(mailId, pTMail) != osOK) /* Send Mail */ { /* LED1 is turned On to indicate error */ BSP_LED_On(LED1); } else { /* Increment the variables we are going to post next time round. The consumer will expect the numbers to follow in numerical order. */ // После того, как, сообщение было отправлено инкрементируем поля сообщения и переключаем состояние светодиода ProducerValue1 += 1; ProducerValue2 += 2; ProducerValue3 += 3; /* Toggle LED1 to indicate a correct number received */ BSP_LED_Toggle(LED1); // Пауза для потока sys.Delay(1500); } } } /** * @brief Mail Consumer Thread. * @param argument: Not used * @retval None */ static void MailQueueConsumer (const void *argument) { osEvent event; sys_Amail_TypeDef *pRMail; for(;;) { // Проверка на полученное сообщение /* Get the message from the queue */ event = osMailGet(mailId, osWaitForever); /* wait for mail */ //Если сообщение доставлено if(event.status == osEventMail) { pRMail = (sys_Amail_TypeDef *)event.value.p; //В случае, если поля отличаются, тогда заполняем поля полученными данными из сообщения. if((pRMail->var1 != ConsumerValue1) || (pRMail->var2 != ConsumerValue2) || (pRMail->var3 != ConsumerValue3)) { /* Catch-up. */ ConsumerValue1 = pRMail->var1; ConsumerValue2 = pRMail->var2; ConsumerValue3 = pRMail->var3; /* LED1 is turned On to indicate error */ BSP_LED_On(LED1); } else { /* Calculate values we expect to remove from the mail queue next time round. */ ConsumerValue1 += 1; ConsumerValue2 += 2; ConsumerValue3 += 3; //Увеличиваем индикацию сообщений } //Освобождаем память под сообщения osMailFree(mailId, pRMail); /* free memory allocated for mail */ } } } /** * @brief System Clock Configuration * The system Clock is configured as follow : * System Clock source = PLL (HSE) * SYSCLK(Hz) = 216000000 * HCLK(Hz) = 216000000 * AHB Prescaler = 1 * APB1 Prescaler = 4 * APB2 Prescaler = 2 * HSE Frequency(Hz) = 25000000 * PLL_M = 25 * PLL_N = 432 * PLL_P = 2 * PLL_Q = 9 * VDD(V) = 3.3 * Main regulator output voltage = Scale1 mode * Flash Latency(WS) = 7 * @param None * @retval None */ static void SystemClock_Config(void) { RCC_ClkInitTypeDef RCC_ClkInitStruct; RCC_OscInitTypeDef RCC_OscInitStruct; /* Enable HSE Oscillator and activate PLL with HSE as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSIState = RCC_HSI_OFF; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLM = 25; RCC_OscInitStruct.PLL.PLLN = 432; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 9; HAL_RCC_OscConfig(&RCC_OscInitStruct); /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_7); } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t* file, uint32_t line) { /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* Infinite loop */ while (1) {} } #endif /** * @brief CPU L1-Cache enable. * @param None * @retval None */ static void CPU_CACHE_Enable(void) { /* Enable I-Cache */ SCB_EnableICache(); /* Enable D-Cache */ SCB_EnableDCache(); } /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
//sys_freertos.cpp #include "sys_freertos.h" osStatus FreeRTOS::StartScheduler(void){ return osKernelStart(); } osMailQId FreeRTOS::MailCreate (const osMailQDef_t *queue_def, osThreadId thread_id){ return osMailCreate (queue_def, thread_id); } osStatus FreeRTOS::Delay (uint32_t millisec){ return osDelay (millisec); } osThreadId FreeRTOS::ThreadCreate (const osThreadDef_t *thread_def, void *argument){ return osThreadCreate(thread_def, argument); }
//sys_freertos.h #ifdef __cplusplus extern "C" { #endif #include "cmsis_os.h" #include <stdint.h> #ifdef __cplusplus } #endif typedef struct { /* Mail object structure */ uint32_t var1; /* var1 is a uint32_t */ uint32_t var2; /* var2 is a uint32_t */ uint8_t var3; /* var3 is a uint8_t */ } sys_Amail_TypeDef; class FreeRTOS { public: osStatus StartScheduler(void); osMailQId MailCreate (const osMailQDef_t *queue_def, osThreadId thread_id); osStatus Delay (uint32_t millisec); osThreadId ThreadCreate (const osThreadDef_t *thread_def, void *argument); }; class MailBox { public: os_mailQ_cb *os_mailQ_cb_name; const osMailQDef_t os_mailQ_def_name; MailBox(uint32_t queue_sz): os_mailQ_def_name ( { queue_sz, sizeof (sys_Amail_TypeDef), (&os_mailQ_cb_name) } ) {} }; class Thread { public: const osThreadDef_t os_thread_def_name; Thread(char *name, os_pthread pthread, osPriority tpriority, uint32_t instances, uint32_t stacksize): os_thread_def_name({name, pthread, tpriority, instances, stacksize}){} };
Старт ARM. RTOS часть 1-ая. STM32F4 и SAM3N.
Старт ARM. RTOS часть 2-ая.
Старт ARM. RTOS часть 3-ая. Очереди.
Старт ARM. RTOS часть 4-ая. Семафоры.
Старт ARM. RTOS часть 5-ая. Мьютексы.
Старт ARM. RTOS часть 6-ая. Сопрограмма.
Старт ARM. RTOS часть 7-ая. Программный таймер.