본문 바로가기

FreeRTOS/FreeRTOS 기본 학습

14 FreeRTOS Tutorial: Mutex

https://www.youtube.com/watch?v=rqpbQlzgws0

 

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "cmsis_os.h"
#include "usb_host.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "FreeRTOS.h"
#include <stdio.h>
#include <string.h>
#include "semphr.h"
/* USER CODE END Includes */



TaskHandle_t myTask1Handle = NULL;
TaskHandle_t myTask2Handle = NULL;

SemaphoreHandle_t xMutex;

char mySharedResource[10];

void myTask1(void *pvParameters)
{

	char Task1Msg[] = "potatoes";

	char text[10];


		while(1)
		{


			if ( xSemaphoreTake(xMutex, (TickType_t) 0xFFFFFFFF ) == 1)
			{
			int i;

			for(i=0; i<9; i++){

				mySharedResource[i] = Task1Msg[i];
				vTaskDelay(50);

			}

			mySharedResource[i] = 0;


			HAL_UART_Transmit(&huart2, (uint8_t *)"T1: ",strlen("T1: ") , 10);
			HAL_UART_Transmit(&huart2, (uint8_t *)mySharedResource ,strlen(mySharedResource) , 10);
			HAL_UART_Transmit(&huart2, (uint8_t *)"\r\n",strlen("\r\n") , 10);
			//printf("T1: %s\r\n", mySharedResource);

			xSemaphoreGive(xMutex);
		}
			vTaskDelay(100);
		}
}

void myTask2(void *pvParameters)
{

	char Task2Msg[] = "tomatoes";


		while(1)
		{


			if ( xSemaphoreTake(xMutex, (TickType_t) 0xFFFFFFFF ) == 1)
			{

			int i;

			for(i=0; i<9; i++){

				mySharedResource[i] = Task2Msg[i];
				vTaskDelay(50);

			}

			mySharedResource[i] = 0;

			HAL_UART_Transmit(&huart2, (uint8_t *)"T2: ",strlen("T2: ") , 10);
			HAL_UART_Transmit(&huart2, (uint8_t *)mySharedResource ,strlen(mySharedResource) , 10);
			HAL_UART_Transmit(&huart2, (uint8_t *)"\r\n",strlen("\r\n") , 10);
			//printf("T2: %s\r\n", mySharedResource);

			xSemaphoreGive(xMutex);

		}
			vTaskDelay(100);
		}

		//HAL_UART_Transmit(&huart2, (uint8_t *)"\r\n",strlen("\r\n") , 10);

}


int main(void)
{
  /* USER CODE BEGIN 1 */
  
	xMutex = xSemaphoreCreateMutex();

  /* USER CODE END 1 */
  


  xTaskCreate(myTask1,					//Task Pointer
  		  	  (const char* const)"task1",	//Task Name
  			  configMINIMAL_STACK_SIZE + 1000,	//Stack Depth
  			  (void *)0,						//Parameters to pass to task
  			  tskIDLE_PRIORITY,								//Task Priority
  			  &myTask1Handle);           //Pass Handle to created task

  xTaskCreate(myTask2,					//Task Pointer
		  	  (const char* const)"task_2",	//Task Name
			  configMINIMAL_STACK_SIZE + 1000,	//Stack Depth
			  (void *)0,						//Parameters to pass to task
			  tskIDLE_PRIORITY,								//Task Priority
			  &myTask2Handle);           //Pass Handle to created task


}