/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * Copyright (c) 2025 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "cmsis_os.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ //#include "ili9341.h" //#include "ili9341_touch.h" #include "ILI9341_STM32_Driver.h" #include "ILI9341_GFX.h" //#include "ili9341_touch.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ I2C_HandleTypeDef hi2c1; SPI_HandleTypeDef hspi1; SPI_HandleTypeDef hspi2; DMA_HandleTypeDef hdma_spi1_rx; DMA_HandleTypeDef hdma_spi1_tx; TIM_HandleTypeDef htim1; TIM_HandleTypeDef htim4; TIM_HandleTypeDef htim5; UART_HandleTypeDef huart6; /* Definitions for touchhistory */ osThreadId_t touchhistoryHandle; const osThreadAttr_t touchhistory_attributes = { .name = "touchhistory", .stack_size = 128 * 4, .priority = (osPriority_t) osPriorityNormal, }; /* Definitions for draw */ osThreadId_t drawHandle; const osThreadAttr_t draw_attributes = { .name = "draw", .stack_size = 1024 * 4, .priority = (osPriority_t) osPriorityLow, }; /* Definitions for reactiongame */ osThreadId_t reactiongameHandle; const osThreadAttr_t reactiongame_attributes = { .name = "reactiongame", .stack_size = 128 * 4, .priority = (osPriority_t) osPriorityLow, }; /* Definitions for gamepicker */ osThreadId_t gamepickerHandle; const osThreadAttr_t gamepicker_attributes = { .name = "gamepicker", .stack_size = 128 * 4, .priority = (osPriority_t) osPriorityLow, }; /* Definitions for presses */ osMessageQueueId_t pressesHandle; const osMessageQueueAttr_t presses_attributes = { .name = "presses" }; /* Definitions for display */ osMutexId_t displayHandle; const osMutexAttr_t display_attributes = { .name = "display" }; /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_DMA_Init(void); static void MX_SPI1_Init(void); static void MX_SPI2_Init(void); static void MX_TIM1_Init(void); static void MX_TIM4_Init(void); static void MX_TIM5_Init(void); static void MX_USART6_UART_Init(void); static void MX_I2C1_Init(void); void StartTouchHist(void *argument); void snakegame(void *argument); void startreactiongame(void *argument); void gamepicker_entry(void *argument); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ #define touchbuffersize 50 struct { int x[touchbuffersize]; int y[touchbuffersize]; } touchcoord; void titlescreen() { ILI9341_FillScreen(WHITE); char str[50]; sprintf(str, "snake"); ILI9341_DrawText(str, FONT3, 320 / 2 - 100, 240 / 2, BLACK, WHITE); sprintf(str, "1v1"); ILI9341_DrawText(str, FONT3, 10, 30, BLACK, WHITE); //ILI9341_WriteString(320 / 2 + 100, 240 / 2, str, Font_11x18, //ILI9341_MAGENTA, ILI9341_WHITE); } #define FLASH_USER_ADDR ((uint32_t)0x0803F000) // Last 4 KB void Flash_Write_HighScore(uint32_t highscore) { HAL_FLASH_Unlock(); // Erase the sector first FLASH_EraseInitTypeDef EraseInitStruct; uint32_t PageError = 0; EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3; EraseInitStruct.Sector = FLASH_SECTOR_5; EraseInitStruct.NbSectors = 1; if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) != HAL_OK) { // Handle error return; } // Program the word if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, FLASH_USER_ADDR, highscore) != HAL_OK) { // Handle error } HAL_FLASH_Lock(); } uint32_t Flash_Read_HighScore(void) { return *(uint32_t*) FLASH_USER_ADDR; } struct Snake { // Snake head coordinates (x-axis, y-axis) int x, y; // Food coordinates int fruitCordX, fruitCordY; // Player's score int playerScore; // Tail coordinates int TailX[100], TailY[100]; // Tail length int TailLen; // Movement direction enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN } Dir; int gamesizewidth; //number of " pixels " in the horizontal int gamesizeheight; int TailPendingDeletionX; int TailPendingDeletionY; int TailGrowPending; // Delay tail growth by one frame // Game over flag int isGameOver; } snake; // Function to initialize game variables void GameInit() { snake.gamesizeheight = 6; snake.gamesizewidth = 8; snake.isGameOver = 0; snake.Dir = RIGHT; snake.x = 1; //snake.gamesizewidth / 2; snake.y = 1; //snake.gamesizeheight / 2; snake.fruitCordX = 2; //rand() % snake.gamesizewidth; snake.fruitCordY = 1; //rand() % snake.gamesizeheight; snake.playerScore = 0; snake.TailLen = 0; snake.TailGrowPending = 0; if (osMutexAcquire(displayHandle, osWaitForever) == osOK) { ILI9341_FillScreen(WHITE); osMutexRelease(displayHandle); } } // Function for updating the game state void UpdateGame() { char dir; // check the queue non blocking osStatus_t status = osMessageQueueGet(pressesHandle, &dir, NULL, 0); // 0 = no wait if (status == osOK) { switch (dir) { case 'L': snake.Dir = LEFT; break; case 'R': snake.Dir = RIGHT; break; case 'U': snake.Dir = UP; break; case 'D': snake.Dir = DOWN; break; } } if (!snake.TailGrowPending) { if (snake.TailLen > 0) { snake.TailPendingDeletionX = snake.TailX[snake.TailLen - 1]; snake.TailPendingDeletionY = snake.TailY[snake.TailLen - 1]; } else { snake.TailPendingDeletionX = snake.x; snake.TailPendingDeletionY = snake.y; } } snake.TailGrowPending = 0; // tail movement if (snake.TailLen > 0) { for (int i = snake.TailLen - 1; i > 0; i--) { snake.TailX[i] = snake.TailX[i - 1]; snake.TailY[i] = snake.TailY[i - 1]; } snake.TailX[0] = snake.x; snake.TailY[0] = snake.y; } switch (snake.Dir) { case LEFT: snake.x--; break; case RIGHT: snake.x++; break; case UP: snake.y--; break; case DOWN: snake.y++; break; } // Checks for snake's collision with the wall if (snake.x >= snake.gamesizewidth || snake.x < 0 || snake.y >= snake.gamesizeheight || snake.y < 0) snake.isGameOver = 1; // Checks for collision with the tail (o) for (int i = 0; i < snake.TailLen; i++) { if (snake.TailX[i] == snake.x && snake.TailY[i] == snake.y) snake.isGameOver = 1; } // Checks for snake's collision with the food (#) if (snake.x == snake.fruitCordX && snake.y == snake.fruitCordY) { snake.playerScore += 10; snake.fruitCordX = 0; //rand() % snake.gamesizewidth; snake.fruitCordY = 0; //rand() % snake.gamesizeheight; snake.TailLen++; snake.TailX[snake.TailLen - 1] = snake.x; snake.TailY[snake.TailLen - 1] = snake.y; snake.TailGrowPending = 1; //snake.TailPendingDeletionX = -1; } if (snake.isGameOver) { if (osMutexAcquire(displayHandle, osWaitForever) == osOK) { if (Flash_Read_HighScore() > snake.playerScore) { char str[50]; sprintf(str, "Highscore Remains: %lu", Flash_Read_HighScore()); ILI9341_DrawText(str, FONT3, 320 / 2 - 70, 240 / 2, BLACK, WHITE); // ILI9341_WriteString(320 / 2 - 70, 240 / 2, str, Font_11x18, //ILI9341_MAGENTA, ILI9341_WHITE); } else { char str[50]; sprintf(str, "New Highscore: %lu", snake.playerScore); //ILI9341_WriteString(320 / 2 - 70, 240 / 2, str, Font_11x18, //ILI9341_MAGENTA, ILI9341_WHITE); ILI9341_DrawText(str, FONT3, 320 / 2 - 70, 240 / 2, BLACK, WHITE); Flash_Write_HighScore(snake.playerScore); } osMutexRelease(displayHandle); } } } // Function to handle user UserInput int prevpressed; void UserInput() { // Checks if a key is pressed or not //case 'a': // snake.Dir = LEFT; uint16_t x, y; //if (ILI9341_TouchGetCoordinates(&x, &y)) { // Only act if touch detected for (int i = 0; i < touchbuffersize - 1; i++) { touchcoord.x[i] = touchcoord.x[i + 1]; touchcoord.y[i] = touchcoord.y[i + 1]; //} touchcoord.x[touchbuffersize - 1] = x; touchcoord.y[touchbuffersize - 1] = y; char dir; if (x < 107) { dir = 'L'; // Left } else if (x > 213) { dir = 'R'; // Right } else if (y > 120) { dir = 'U'; // Up } else { dir = 'D'; // Down } dir = 'R'; // Send the direction to the queue //if (!prevpressed && ILI9341_TouchPressed()) { osStatus_t status = osMessageQueuePut(pressesHandle, &dir, 0, 0); if (status != osOK) { // Optional: Handle error } //} prevpressed = 1; //} else { prevpressed = 0; //give illegal coords //if it is already we can skip it if (touchcoord.x[0] != ILI9341_SCREEN_WIDTH) { //is the last buffer coord illegal? for (int i = 0; i < touchbuffersize - 1; i++) { touchcoord.x[i] = touchcoord.x[i + 1]; touchcoord.y[i] = touchcoord.y[i + 1]; } touchcoord.x[touchbuffersize - 1] = ILI9341_SCREEN_WIDTH; touchcoord.y[touchbuffersize - 1] = ILI9341_SCREEN_WIDTH; } } } // Function for creating the game board & rendering void GameRender() { // Creating top walls // Creating side walls //ILI9341_FillRectangle(j, i, ILI9341_WIDTH/snake.gamesizewidth, ILI9341_HEIGHT/snake.gamesizeheight, ILI9341_YELLOW); //ILI9341_FillScreen(MAGENTA); for (int x = 0; x < snake.gamesizewidth; x++) { for (int y = 0; y <= snake.gamesizeheight; y++) { if (x == snake.x && y == snake.y) { if (osMutexAcquire(displayHandle, osWaitForever) == osOK) { ILI9341_DrawFilledRectangleCoord( (x * ILI9341_SCREEN_WIDTH) / snake.gamesizewidth, (y * ILI9341_SCREEN_HEIGHT) / snake.gamesizeheight, (x * ILI9341_SCREEN_WIDTH) / snake.gamesizewidth + ILI9341_SCREEN_WIDTH / snake.gamesizewidth, (y * ILI9341_SCREEN_HEIGHT) / snake.gamesizeheight + ILI9341_SCREEN_HEIGHT / snake.gamesizeheight, BLACK); // ILI9341_FillRectangle( // (x * ILI9341_WIDTH) / snake.gamesizewidth, // (y * ILI9341_HEIGHT) / snake.gamesizeheight, // ILI9341_WIDTH / snake.gamesizewidth, // ILI9341_HEIGHT / snake.gamesizeheight, // ILI9341_BLACK); osMutexRelease(displayHandle); } } //cout << "O"; // Creating the sanke's food with '#' else if (x == snake.fruitCordX && y == snake.fruitCordY) { if (osMutexAcquire(displayHandle, osWaitForever) == osOK) { ILI9341_DrawFilledRectangleCoord( (x * ILI9341_SCREEN_WIDTH) / snake.gamesizewidth, (y * ILI9341_SCREEN_HEIGHT) / snake.gamesizeheight, (x * ILI9341_SCREEN_WIDTH) / snake.gamesizewidth + ILI9341_SCREEN_WIDTH / snake.gamesizewidth, (y * ILI9341_SCREEN_HEIGHT) / snake.gamesizeheight + ILI9341_SCREEN_HEIGHT / snake.gamesizeheight, RED); // ILI9341_FillRectangle( // (x * ILI9341_WIDTH) / snake.gamesizewidth, // (y * ILI9341_HEIGHT) / snake.gamesizeheight, // ILI9341_WIDTH / snake.gamesizewidth, // ILI9341_HEIGHT / snake.gamesizeheight, ILI9341_RED); osMutexRelease(displayHandle); } } //cout << "#"; else if (snake.TailLen >= 0) { for (int i = 0; i < snake.TailLen; i++) { if (snake.TailX[0] == x && snake.TailY[0] == y) { if (osMutexAcquire(displayHandle, osWaitForever) == osOK) { ILI9341_DrawFilledRectangleCoord( (x * ILI9341_SCREEN_WIDTH) / snake.gamesizewidth, (y * ILI9341_SCREEN_HEIGHT) / snake.gamesizeheight, (x * ILI9341_SCREEN_WIDTH) / snake.gamesizewidth + ILI9341_SCREEN_WIDTH / snake.gamesizewidth, (y * ILI9341_SCREEN_HEIGHT) / snake.gamesizeheight + ILI9341_SCREEN_HEIGHT / snake.gamesizeheight, GREEN); // ILI9341_FillRectangle( // (x * ILI9341_WIDTH) / snake.gamesizewidth, // (y * ILI9341_HEIGHT) / snake.gamesizeheight, // ILI9341_WIDTH / snake.gamesizewidth, // ILI9341_HEIGHT / snake.gamesizeheight, // ILI9341_GREEN); osMutexRelease(displayHandle); } } } } if (snake.TailPendingDeletionX == x && snake.TailPendingDeletionY == y) { if (osMutexAcquire(displayHandle, osWaitForever) == osOK) { ILI9341_DrawFilledRectangleCoord( (x * ILI9341_SCREEN_WIDTH) / snake.gamesizewidth, (y * ILI9341_SCREEN_HEIGHT) / snake.gamesizeheight, (x * ILI9341_SCREEN_WIDTH) / snake.gamesizewidth + ILI9341_SCREEN_WIDTH / snake.gamesizewidth, (y * ILI9341_SCREEN_HEIGHT) / snake.gamesizeheight + ILI9341_SCREEN_HEIGHT / snake.gamesizeheight, WHITE); // ILI9341_FillRectangle( // (x * ILI9341_WIDTH) / snake.gamesizewidth, // (y * ILI9341_HEIGHT) / snake.gamesizeheight, // ILI9341_WIDTH / snake.gamesizewidth, // ILI9341_HEIGHT / snake.gamesizeheight, // ILI9341_WHITE); osMutexRelease(displayHandle); } } } } } /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_DMA_Init(); MX_SPI1_Init(); MX_SPI2_Init(); MX_TIM1_Init(); MX_TIM4_Init(); MX_TIM5_Init(); MX_USART6_UART_Init(); MX_I2C1_Init(); /* USER CODE BEGIN 2 */ ILI9341_Init(); ILI9341_SetRotation(SCREEN_HORIZONTAL_1); ILI9341_FillScreen(MAGENTA); /* USER CODE END 2 */ /* Init scheduler */ osKernelInitialize(); /* Create the mutex(es) */ /* creation of display */ displayHandle = osMutexNew(&display_attributes); /* USER CODE BEGIN RTOS_MUTEX */ /* add mutexes, ... */ /* USER CODE END RTOS_MUTEX */ /* USER CODE BEGIN RTOS_SEMAPHORES */ /* add semaphores, ... */ /* USER CODE END RTOS_SEMAPHORES */ /* USER CODE BEGIN RTOS_TIMERS */ /* start timers, add new ones, ... */ /* USER CODE END RTOS_TIMERS */ /* Create the queue(s) */ /* creation of presses */ //pressesHandle = osMessageQueueNew (16, sizeof(char), &presses_attributes); /* USER CODE BEGIN RTOS_QUEUES */ /* add queues, ... */ /* USER CODE END RTOS_QUEUES */ /* Create the thread(s) */ /* creation of touchhistory */ //touchhistoryHandle = osThreadNew(StartTouchHist, NULL, &touchhistory_attributes); /* creation of draw */ drawHandle = osThreadNew(snakegame, NULL, &draw_attributes); /* creation of reactiongame */ //reactiongameHandle = osThreadNew(startreactiongame, NULL, &reactiongame_attributes); /* creation of gamepicker */ //gamepickerHandle = osThreadNew(gamepicker_entry, NULL, &gamepicker_attributes); /* USER CODE BEGIN RTOS_THREADS */ /* add threads, ... */ char dir; // check the queue blocking //osStatus_t status = osMessageQueueGet(pressesHandle, &dir, NULL, //osWaitForever); // blocking //if (dir == 'L') // drawHandle = osThreadNew(snakegame, NULL, &draw_attributes); //if (dir == 'R') //reactiongameHandle = osThreadNew(startreactiongame, NULL, // &reactiongame_attributes); /* USER CODE END RTOS_THREADS */ /* USER CODE BEGIN RTOS_EVENTS */ /* add events, ... */ /* USER CODE END RTOS_EVENTS */ /* Start scheduler */ osKernelStart(); /* We should never get here as control is now taken by the scheduler */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ //int a[4] = { ILI9341_GREEN, ILI9341_WHITE, ILI9341_BLACK, ILI9341_BLUE }; int cnt; while (hspi1.State != HAL_SPI_STATE_READY) ; while (HAL_SPI_GetState(&hspi1) != HAL_SPI_STATE_READY) ; while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ cnt++; //ILI9341_DrawPixel(cnt % ILI9341_WIDTH, cnt % ILI9341_HEIGHT, a[cnt%4]); //ILI9341_FillScreen(MAGENTA); //ILI9341_DrawFilledRectangleCoord(10, 10, 20, 20, RED); //ILI9341_FillScreen(WHITE); HAL_Delay(1); char str[20]; sprintf(str, "%lu", cnt % 1000); int atim = HAL_GetTick(); //ILI9341_DrawFilledRectangleCoord(10, 10, 20, 20, GREEN); //ILI9341_FillScreen(MAGENTA); //ILI9341_FillScreen(atim%0xFFFF); //ILI9341_DrawText(str, FONT4, 50, 50, WHITE, BLACK); //ILI9341_DrawChar('C', FONT4, 40, 40, WHITE, BLACK); int c = HAL_GetTick() - atim; //HAL_Delay(100);s //ILI9341_WriteString(320 / 2 - 70, 240 / 2, str, Font_11x18, //ILI9341_MAGENTA, ILI9341_WHITE); //HAL_Delay(1000); //titlescreen(); } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Configure the main internal regulator output voltage */ __HAL_RCC_PWR_CLK_ENABLE(); __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2); /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK) { Error_Handler(); } } /** * @brief I2C1 Initialization Function * @param None * @retval None */ static void MX_I2C1_Init(void) { /* USER CODE BEGIN I2C1_Init 0 */ /* USER CODE END I2C1_Init 0 */ /* USER CODE BEGIN I2C1_Init 1 */ /* USER CODE END I2C1_Init 1 */ hi2c1.Instance = I2C1; hi2c1.Init.ClockSpeed = 100000; hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2; hi2c1.Init.OwnAddress1 = 0; hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; hi2c1.Init.OwnAddress2 = 0; hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; if (HAL_I2C_Init(&hi2c1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN I2C1_Init 2 */ /* USER CODE END I2C1_Init 2 */ } /** * @brief SPI1 Initialization Function * @param None * @retval None */ static void MX_SPI1_Init(void) { /* USER CODE BEGIN SPI1_Init 0 */ /* USER CODE END SPI1_Init 0 */ /* USER CODE BEGIN SPI1_Init 1 */ /* USER CODE END SPI1_Init 1 */ /* SPI1 parameter configuration*/ hspi1.Instance = SPI1; hspi1.Init.Mode = SPI_MODE_MASTER; hspi1.Init.Direction = SPI_DIRECTION_2LINES; hspi1.Init.DataSize = SPI_DATASIZE_8BIT; hspi1.Init.CLKPolarity = SPI_POLARITY_LOW; hspi1.Init.CLKPhase = SPI_PHASE_1EDGE; hspi1.Init.NSS = SPI_NSS_SOFT; hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2; hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB; hspi1.Init.TIMode = SPI_TIMODE_DISABLE; hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; hspi1.Init.CRCPolynomial = 10; if (HAL_SPI_Init(&hspi1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN SPI1_Init 2 */ /* USER CODE END SPI1_Init 2 */ } /** * @brief SPI2 Initialization Function * @param None * @retval None */ static void MX_SPI2_Init(void) { /* USER CODE BEGIN SPI2_Init 0 */ /* USER CODE END SPI2_Init 0 */ /* USER CODE BEGIN SPI2_Init 1 */ /* USER CODE END SPI2_Init 1 */ /* SPI2 parameter configuration*/ hspi2.Instance = SPI2; hspi2.Init.Mode = SPI_MODE_MASTER; hspi2.Init.Direction = SPI_DIRECTION_2LINES; hspi2.Init.DataSize = SPI_DATASIZE_8BIT; hspi2.Init.CLKPolarity = SPI_POLARITY_LOW; hspi2.Init.CLKPhase = SPI_PHASE_1EDGE; hspi2.Init.NSS = SPI_NSS_SOFT; hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32; hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB; hspi2.Init.TIMode = SPI_TIMODE_DISABLE; hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; hspi2.Init.CRCPolynomial = 10; if (HAL_SPI_Init(&hspi2) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN SPI2_Init 2 */ /* USER CODE END SPI2_Init 2 */ } /** * @brief TIM1 Initialization Function * @param None * @retval None */ static void MX_TIM1_Init(void) { /* USER CODE BEGIN TIM1_Init 0 */ /* USER CODE END TIM1_Init 0 */ TIM_Encoder_InitTypeDef sConfig = {0}; TIM_MasterConfigTypeDef sMasterConfig = {0}; /* USER CODE BEGIN TIM1_Init 1 */ /* USER CODE END TIM1_Init 1 */ htim1.Instance = TIM1; htim1.Init.Prescaler = 0; htim1.Init.CounterMode = TIM_COUNTERMODE_UP; htim1.Init.Period = 65535; htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; htim1.Init.RepetitionCounter = 0; htim1.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; sConfig.EncoderMode = TIM_ENCODERMODE_TI12; sConfig.IC1Polarity = TIM_ICPOLARITY_RISING; sConfig.IC1Selection = TIM_ICSELECTION_DIRECTTI; sConfig.IC1Prescaler = TIM_ICPSC_DIV1; sConfig.IC1Filter = 0; sConfig.IC2Polarity = TIM_ICPOLARITY_RISING; sConfig.IC2Selection = TIM_ICSELECTION_DIRECTTI; sConfig.IC2Prescaler = TIM_ICPSC_DIV1; sConfig.IC2Filter = 0; if (HAL_TIM_Encoder_Init(&htim1, &sConfig) != HAL_OK) { Error_Handler(); } sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET; sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; if (HAL_TIMEx_MasterConfigSynchronization(&htim1, &sMasterConfig) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN TIM1_Init 2 */ /* USER CODE END TIM1_Init 2 */ } /** * @brief TIM4 Initialization Function * @param None * @retval None */ static void MX_TIM4_Init(void) { /* USER CODE BEGIN TIM4_Init 0 */ /* USER CODE END TIM4_Init 0 */ TIM_Encoder_InitTypeDef sConfig = {0}; TIM_MasterConfigTypeDef sMasterConfig = {0}; /* USER CODE BEGIN TIM4_Init 1 */ /* USER CODE END TIM4_Init 1 */ htim4.Instance = TIM4; htim4.Init.Prescaler = 0; htim4.Init.CounterMode = TIM_COUNTERMODE_UP; htim4.Init.Period = 65535; htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; htim4.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; sConfig.EncoderMode = TIM_ENCODERMODE_TI12; sConfig.IC1Polarity = TIM_ICPOLARITY_RISING; sConfig.IC1Selection = TIM_ICSELECTION_DIRECTTI; sConfig.IC1Prescaler = TIM_ICPSC_DIV1; sConfig.IC1Filter = 0; sConfig.IC2Polarity = TIM_ICPOLARITY_RISING; sConfig.IC2Selection = TIM_ICSELECTION_DIRECTTI; sConfig.IC2Prescaler = TIM_ICPSC_DIV1; sConfig.IC2Filter = 0; if (HAL_TIM_Encoder_Init(&htim4, &sConfig) != HAL_OK) { Error_Handler(); } sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET; sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; if (HAL_TIMEx_MasterConfigSynchronization(&htim4, &sMasterConfig) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN TIM4_Init 2 */ /* USER CODE END TIM4_Init 2 */ } /** * @brief TIM5 Initialization Function * @param None * @retval None */ static void MX_TIM5_Init(void) { /* USER CODE BEGIN TIM5_Init 0 */ /* USER CODE END TIM5_Init 0 */ TIM_ClockConfigTypeDef sClockSourceConfig = {0}; TIM_MasterConfigTypeDef sMasterConfig = {0}; TIM_OC_InitTypeDef sConfigOC = {0}; /* USER CODE BEGIN TIM5_Init 1 */ /* USER CODE END TIM5_Init 1 */ htim5.Instance = TIM5; htim5.Init.Prescaler = 0; htim5.Init.CounterMode = TIM_COUNTERMODE_UP; htim5.Init.Period = 4294967295; htim5.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; htim5.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; if (HAL_TIM_Base_Init(&htim5) != HAL_OK) { Error_Handler(); } sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL; if (HAL_TIM_ConfigClockSource(&htim5, &sClockSourceConfig) != HAL_OK) { Error_Handler(); } if (HAL_TIM_PWM_Init(&htim5) != HAL_OK) { Error_Handler(); } sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET; sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; if (HAL_TIMEx_MasterConfigSynchronization(&htim5, &sMasterConfig) != HAL_OK) { Error_Handler(); } sConfigOC.OCMode = TIM_OCMODE_PWM1; sConfigOC.Pulse = 0; sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH; sConfigOC.OCFastMode = TIM_OCFAST_DISABLE; if (HAL_TIM_PWM_ConfigChannel(&htim5, &sConfigOC, TIM_CHANNEL_1) != HAL_OK) { Error_Handler(); } if (HAL_TIM_PWM_ConfigChannel(&htim5, &sConfigOC, TIM_CHANNEL_2) != HAL_OK) { Error_Handler(); } if (HAL_TIM_PWM_ConfigChannel(&htim5, &sConfigOC, TIM_CHANNEL_3) != HAL_OK) { Error_Handler(); } if (HAL_TIM_PWM_ConfigChannel(&htim5, &sConfigOC, TIM_CHANNEL_4) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN TIM5_Init 2 */ /* USER CODE END TIM5_Init 2 */ HAL_TIM_MspPostInit(&htim5); } /** * @brief USART6 Initialization Function * @param None * @retval None */ static void MX_USART6_UART_Init(void) { /* USER CODE BEGIN USART6_Init 0 */ /* USER CODE END USART6_Init 0 */ /* USER CODE BEGIN USART6_Init 1 */ /* USER CODE END USART6_Init 1 */ huart6.Instance = USART6; huart6.Init.BaudRate = 115200; huart6.Init.WordLength = UART_WORDLENGTH_8B; huart6.Init.StopBits = UART_STOPBITS_1; huart6.Init.Parity = UART_PARITY_NONE; huart6.Init.Mode = UART_MODE_TX_RX; huart6.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart6.Init.OverSampling = UART_OVERSAMPLING_16; if (HAL_UART_Init(&huart6) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART6_Init 2 */ /* USER CODE END USART6_Init 2 */ } /** * Enable DMA controller clock */ static void MX_DMA_Init(void) { /* DMA controller clock enable */ __HAL_RCC_DMA2_CLK_ENABLE(); /* DMA interrupt init */ /* DMA2_Stream0_IRQn interrupt configuration */ HAL_NVIC_SetPriority(DMA2_Stream0_IRQn, 5, 0); HAL_NVIC_EnableIRQ(DMA2_Stream0_IRQn); /* DMA2_Stream3_IRQn interrupt configuration */ HAL_NVIC_SetPriority(DMA2_Stream3_IRQn, 5, 0); HAL_NVIC_EnableIRQ(DMA2_Stream3_IRQn); } /** * @brief GPIO Initialization Function * @param None * @retval None */ static void MX_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; /* USER CODE BEGIN MX_GPIO_Init_1 */ /* USER CODE END MX_GPIO_Init_1 */ /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOC_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(LED_BLUE_GPIO_Port, LED_BLUE_Pin, GPIO_PIN_RESET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(GPIOA, DISPLAY_CS_Pin|DISPLAY_RES_Pin, GPIO_PIN_RESET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(GPIOB, TOUCH_CS_Pin|DISPLAY_DC_Pin, GPIO_PIN_RESET); /*Configure GPIO pin : LED_BLUE_Pin */ GPIO_InitStruct.Pin = LED_BLUE_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(LED_BLUE_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pins : DISPLAY_CS_Pin DISPLAY_RES_Pin */ GPIO_InitStruct.Pin = DISPLAY_CS_Pin|DISPLAY_RES_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /*Configure GPIO pins : TOUCH_CS_Pin DISPLAY_DC_Pin */ GPIO_InitStruct.Pin = TOUCH_CS_Pin|DISPLAY_DC_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /*Configure GPIO pin : TOUCH_IRQ_Pin */ GPIO_InitStruct.Pin = TOUCH_IRQ_Pin; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(TOUCH_IRQ_GPIO_Port, &GPIO_InitStruct); /* USER CODE BEGIN MX_GPIO_Init_2 */ /* USER CODE END MX_GPIO_Init_2 */ } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /* USER CODE BEGIN Header_StartTouchHist */ /** * @brief Function implementing the touchhistory thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_StartTouchHist */ void StartTouchHist(void *argument) { /* USER CODE BEGIN 5 */ /* Infinite loop */ for (;;) { UserInput(); if (osMutexAcquire(displayHandle, osWaitForever) == osOK) { // Mutex successfully locked // ILI9341_DrawPixel(touchcoord.x[touchbuffersize - 1], // touchcoord.y[touchbuffersize - 1], ILI9341_MAGENTA); // ILI9341_DrawPixel(touchcoord.x[0], touchcoord.y[0], ILI9341_WHITE); osMutexRelease(displayHandle); } osDelay(1); } /* USER CODE END 5 */ } /* USER CODE BEGIN Header_snakegame */ /** * @brief Function implementing the draw thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_snakegame */ void snakegame(void *argument) { /* USER CODE BEGIN snakegame */ /* Infinite loop */ ILI9341_FillScreen(BLACK); GameInit(); GameRender(); for (;;) { //uint16_t x,y; //ILI9341_TouchGetCoordinates(&x, &y); GameRender(); static char statsBuffer[512]; vTaskGetRunTimeStats(statsBuffer); vTaskDelay(1000); uint16_t timer=HAL_GetTick(); //ILI9341_FillScreen(timer%0xFFFF); UpdateGame(); } /* USER CODE END snakegame */ } /* USER CODE BEGIN Header_startreactiongame */ /** * @brief Function implementing the reactiongame thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_startreactiongame */ void startreactiongame(void *argument) { /* USER CODE BEGIN startreactiongame */ /* Infinite loop */ uint32_t lasttimestamp = osKernelGetTickCount(); for (;;) { int a = rand() % 4000; osDelay(1000 + a); char dir; char str[50]; // add the check for clicking too early. add the message clicked too early // if (osMessageQueueGet(pressesHandle, &dir, NULL, 0) != osOK) { // Check if someone pressed during the delay → early press // // if (osMutexAcquire(displayHandle, osWaitForever) == osOK) { // ILI9341_FillScreen(ILI9341_GREEN); // osMutexRelease(displayHandle); // } // lasttimestamp = osKernelGetTickCount(); // // check the queue blocking // osStatus_t status = osMessageQueueGet(pressesHandle, &dir, NULL, // osWaitForever); // // int timediff = osKernelGetTickCount() - lasttimestamp; // sprintf(str, "Time %d", timediff); // if (osMutexAcquire(displayHandle, osWaitForever) == osOK) { // if (dir == 'L') { // ILI9341_WriteString(320 / 2 - 100, 240 / 2, str, Font_11x18, // ILI9341_MAGENTA, ILI9341_WHITE); // } // if (dir == 'R') { // ILI9341_WriteString(320 / 2 + 100, 240 / 2, str, Font_11x18, // ILI9341_MAGENTA, ILI9341_WHITE); // } // osMutexRelease(displayHandle); // } // } else { // sprintf(str, "Pressed too early"); // if (osMutexAcquire(displayHandle, osWaitForever) == osOK) { // if (dir == 'L') { // ILI9341_WriteString(320 / 2 - 100, 240 / 2, str, Font_11x18, // ILI9341_MAGENTA, ILI9341_WHITE); // } // if (dir == 'R') { // ILI9341_WriteString(320 / 2 + 100, 240 / 2, str, Font_11x18, // ILI9341_MAGENTA, ILI9341_WHITE); // } // osMutexRelease(displayHandle); // } // // } // osDelay(1000); // if (osMutexAcquire(displayHandle, osWaitForever) == osOK) { // ILI9341_FillScreen(ILI9341_WHITE); // osMutexRelease(displayHandle); // } // //clear the queue // while (osMessageQueueGet(pressesHandle, &dir, NULL, 0) == osOK) { // // Discarding messages one by one // } } /* USER CODE END startreactiongame */ } /* USER CODE BEGIN Header_gamepicker_entry */ /** * @brief Function implementing the gamepicker thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_gamepicker_entry */ void gamepicker_entry(void *argument) { /* USER CODE BEGIN gamepicker_entry */ /* Infinite loop */ for (;;) { osDelay(1); titlescreen(); // Render title screen char dir; // Wait for input (blocking) osStatus_t status = osMessageQueueGet(pressesHandle, &dir, NULL, osWaitForever); if (status == osOK) { if (dir == 'L') { drawHandle = osThreadNew(snakegame, NULL, &draw_attributes); osThreadExit(); // Game Manager exits or waits for signal to restart } else if (dir == 'R') { reactiongameHandle = osThreadNew(startreactiongame, NULL, &reactiongame_attributes); osThreadExit(); } else { // not implemeted } } } /* USER CODE END gamepicker_entry */ } /** * @brief Period elapsed callback in non blocking mode * @note This function is called when TIM2 interrupt took place, inside * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment * a global variable "uwTick" used as application time base. * @param htim : TIM handle * @retval None */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { /* USER CODE BEGIN Callback 0 */ /* USER CODE END Callback 0 */ if (htim->Instance == TIM2) { HAL_IncTick(); } /* USER CODE BEGIN Callback 1 */ /* USER CODE END Callback 1 */ } /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ __disable_irq(); while (1) { } /* USER CODE END Error_Handler_Debug */ } #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 CODE BEGIN 6 */ /* 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) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */