cancel
Showing results for 
Search instead for 
Did you mean: 

I am using an STM32L476RG , I worte a code for UART communication. But am not able to get the output.

Charlie4918
Associate

#include "stm32l4xx.h"

#include <stdint.h>

#define SYS_FREQ 16000000

#define APB1_CLK SYS_FREQ

#define UART_BaudRate 115200

#define GPIOAEN (1U<<0)

#define UART2EN (1U<<17)

#define CR1_TE (1U<<3)

#define CR1_UE (1U<<0)

#define ISR_TXE (1U<<7)

static void uart_setBaudRate (USART_TypeDef *USARTx, uint32_t PeriphClk, uint32_t BaudRate);

static uint16_t compute_uart_bd(uint32_t PeriphClk, uint32_t BaudRate);

void uart2_tx_init(void);

void uart2_write(int ch);

int main(void){

uart2_tx_init();

while(1){

uart2_write('Y');

}

}

void uart2_tx_init(void)

{

/************Configure GPIO pin**************************/

/*Enable clock access to gpioA*/

RCC->AHB2ENR |=GPIOAEN;

/*Set PA2 mode to alternate function type*/

GPIOA->MODER &=~(1U<<4);

GPIOA->MODER |=(1U<<5);

/*Set PA2 alternate mode to uartTX AFO7*/

GPIOA->AFR[0] |=(1U<<8);

GPIOA->AFR[0] |=(1U<<9);

GPIOA->AFR[0] |=(1U<<10);

GPIOA->AFR[0] &=~(1U<<11);

/************Configure UART mode**************************/

/*Enable Clock acess ti uart2*/

RCC->APB1ENR1 |=UART2EN;

/*Configure Baudrate*/

uart_setBaudRate(USART2,APB1_CLK,UART_BaudRate);

/*Configure the transfer direction*/

USART2->CR1 = CR1_TE;

/*Enable usart module*/

USART2->CR1 |= CR1_UE;

}

void uart2_write(int ch){

/*Make sure transmit data register is empty*/

while(!(USART2->ISR & ISR_TXE)){}

/*Write to transmit data register*/

USART2->TDR = (ch & 0xFF);

}

static void uart_setBaudRate (USART_TypeDef *USARTx, uint32_t PeriphClk, uint32_t BaudRate){

USARTx->BRR = compute_uart_bd(PeriphClk,BaudRate);

}

static uint16_t compute_uart_bd(uint32_t PeriphClk, uint32_t BaudRate)

{

return ((PeriphClk +(BaudRate/2U))/BaudRate);

}

2 REPLIES 2
Paul1
Lead

a) Use STM32CubeMX to generate initialization code for your STM32 pinout, and check if you missed anything.

b) Look at the tutorials for sample UART code.

c) Attached project in C++ using STM32CubeMX has some useful startup code: STM32L476RG-Nucleo_TestsPR06.zip

*I suggest C++ for the enhanced compile time checking, even if everything is just C Code.

d) Did you make your own PCB or are you using a standard board like a Nucleo? What is the STM32 pinout and schematic?

*When posting code use the </> in toolbar so code keeps formatting and is easier to read.

Paul

SVemp.2
Associate II

@Charlie4918​ : Can you please tell me why the equation return ((PeriphClk +(BaudRate/2U))/BaudRate); was used?