2019-12-12 10:47 AM
#include "stm32f4xx.h" // Device header
void USART2_Init(void);
void USART2_Write(int ch);
void delayMS(int delay);
int main(void){
USART2_Init();
while(1){
USART2_Write('H');
USART2_Write('i');
delayMS(1000);
}
}
void USART2_Init(void){
RCC->APB1ENR |= 0x00020000;
RCC->AHB1ENR |= 0x00000001;
GPIOA->AFR[1] = 0x00000070;
GPIOA->MODER |= 0x00000020;
USART2->BRR = 0x342;
USART2->CR1 |= 0x00000008;
USART2->CR1 |= 0x00002000;
}
void USART2_Write(int ch){
while(!(USART2->SR & 0x0080)){
USART2->DR = (ch & 0xFF);
}
}
void delayMS(int delay){
int i;
for(; delay>0; delay--){
for(i = 0; i < 1000; i++);
}
}
I am trying to Initialize and send data through PA3 (USART2_TX). When i connect the pin to a Serial to USB module to see the data sent on the terminal (CoolTerm) I get an error and doesnt' work. I set the baud rate based on that I have an 8MHz crystal on the board and still nothing is working. What is wrong in the code?
Solved! Go to Solution.
2019-12-12 01:16 PM
You might want to add comments about the pins, clocks and expectations.
Baud rate looks to be ~9600 baud from 8 MHz APB1
AFR[1]= 0x00000070; // Is NOT PA2
AFR[0] = (AFR[0] & 0xFFFFF0FF) | 0x00000700; // PA2:AF7
2019-12-12 12:12 PM
2019-12-12 12:33 PM
I edited the code but there is a still a problem. I get the following error in CoolTerm "103 BreakCondition". I search and I found out that it is usually due to Hardware detected a break condition. Usually due to a signal rate mismatch. Is it a problem with the baud rate ?
2019-12-12 01:16 PM
You might want to add comments about the pins, clocks and expectations.
Baud rate looks to be ~9600 baud from 8 MHz APB1
AFR[1]= 0x00000070; // Is NOT PA2
AFR[0] = (AFR[0] & 0xFFFFF0FF) | 0x00000700; // PA2:AF7
2019-12-12 01:30 PM
Your code worked. But could you explain to me how is it possible. As I mentioned earlier that the USART2 is on AF7 and it is on the AFRH and in the code from my understanding that the AFRH is AFR[1]. Also in the datasheets it is written that AF7:0111 in AFRHy
2019-12-12 03:09 PM
AFR[0] nee AFRL deals with GPIO pins 0 thru 7
AFR[1] nee AFRH deals with GPIO pins 8 thru 15
PA2 would be in the former. Each pin has 4-bits assigned to it, so pin 2 would be bit positions 8 thru 11 of AFRL