Using Serial Communication in STM32

As the title says, today I am going to show you how to use UART for serial communication in STM32 devices. I am going to use STM32CubeMx to generate necessary code and than edit the code in Keil uvision 5.

UART is widely used for serial communication between two devices. It is easy to use protocol, because the clock sync is not involved. All you have to do is take care of BAUD RATE.  BAUD RATE must be same for both devices, amongst which communication is done. I am going to use 9600 as it is standard.

I have already explained the detailed working of  UART in my LPC2148 tutorial. If you want the full explanation of working of UART, please visit here. This basic working remains same throughout no matter which microcontroller you are using right now so I am going to skip that part and just show you guys how to set up UART in STM32.

Some Insight into the Code:-

uint8_t data[] = "HELLO WORLD!\n";

while (1)
    {
      HAL_UART_Transmit (&huart2, data, 14, 50);
      HAL_Delay (1000);
    }

HAL_UART_Transmit function takes following arguments-
     UART_HandleTypeDef *huart, --> This is uart handle as I am using UART2 so the handle is huart2
     uint8_t *pData,   --> the data to be sent
     uint16_t Size,    --> size of data
     uint32_t Timeout   --> timeout before error in milliseconds

Procedure:-
1.)  Open the cubemx and select your board. Select the UART you want to use for communication. I am using UART2.

2.) In the 'configuration' tab, make sure USART settings are as follows.

3.) That's it for cubemx. Now generate the project and open in the respective IDE. I am using keil uvision.

CODE:-
NOTE:I am just going to write the main part of the code here. For full code, see at the end of the post.

UART_HandleTypeDef huart2;   // define the handle for uart

void SystemClock_Config(void);
void Error_Handler(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);

uint8_t data[] = "HELLO WORLD!\n";    // data to be transmitted

int main(void)
{

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* Configure the system clock */
  SystemClock_Config();

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART2_UART_Init();

  while (1)
  {
 HAL_UART_Transmit (&huart2, data, 14, 50);    // transmit the data
  HAL_Delay (1000);    // wait for 1 sec
  }


}

The RESULT is shown below

That's it for transmitting via UART. I will cover receiving part in next post.
Please subscribe to this blog and share it.
For full code click  DOWNLOAD
Visit my youtube channel  Controllers tech to see full working of nucleo board.
Using Serial Communication in STM32 Using Serial Communication in STM32 Reviewed by Controllerstech on July 03, 2017 Rating: 5

1 comment:

Powered by Blogger.