If we need to receive integer values from serial port, we can use “stdlib.h” as includes and then atoi, atof etc. functions to convert string values to integer or floating values.
Example:
Includes;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
/* Includes ------------------------------------------------------------------*/ #include "main.h" #include "stm32f4xx_hal.h" #include <stdbool.h> #include <stdlib.h> // for atoi, atof functions /* USER CODE BEGIN Includes */ char rx_buffer[50], tx_buffer[50]; bool led_state=false; uint32_t value1 = 0; // integer value double value2 = 0; // floating value /* USER CODE END Includes */ |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
/* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { HAL_UART_Receive(&huart6, (uint8_t*)rx_buffer, 50, 500); value1 = atoi(rx_buffer); //convert string value into an integer value //value2 = atof(rx_buffer); //convert string value into a floating value // for example; value1 = 123 , value2 = 12.3 if(value1 == 123){ HAL_GPIO_WritePin(GPIOD, GPIO_PIN_12|GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15, GPIO_PIN_SET); if(led_state != true) HAL_UART_Transmit(&huart6, (uint8_t *)tx_buffer, sprintf(tx_buffer, "Led is on\n"), 500); led_state = true; // clear rx buffer for(int i=0;i<50;i++) rx_buffer[i] = 0; } // for example; value1 = 456 , value2 = 4.56 else if(value1 == 456){ HAL_GPIO_WritePin(GPIOD, GPIO_PIN_12|GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15, GPIO_PIN_RESET); if(led_state != false) HAL_UART_Transmit(&huart6, (uint8_t *)tx_buffer, sprintf(tx_buffer, "Led is off\n"), 500); led_state = false; // clear rx buffer for(int i=0;i<50;i++) rx_buffer[i] = 0; } /* USER CODE END WHILE */ } |