简体   繁体   English

启动时,stm32 UART发送空字节

[英]stm32 UART sending null bytes when starting

I'm trying to exchange data between 2 stm32f407 boards through uart. 我正在尝试通过uart在2个stm32f407板之间交换数据。 The peripheral that I'm using is the USART2 (there are more of them on the board). 我使用的外设是USART2(板上有更多这些外设)。 I've configured it with a baud rate of 9600, 8 bit frame, no parity bits and only 1 stop bit. 我已将其配置为9600的波特率,8位帧,无奇偶校验位和仅1个停止位。 The strange thing that happens is that the receiver gets a lot of null bytes (to be more precise sometimes there are 9 consecutive null bytes, while in other cases 8 null bytes ended by a 0xFF byte) before the data that I'm actually sending. 发生的一件奇怪的事是,接收者在我实际发送的数据之前获取了很多空字节(更准确地说,有时有9个连续的空字节,而在其他情况下,则有8个空字节以0xFF字节结尾) 。 This seems to happen only when I turn on the sender or when I press its reset button, if I send the same data multiple times in a row everything is fine. 这似乎仅在我打开发送器或按下其重置按钮时才发生,如果我连续多次发送相同的数据,一切都很好。 This is the code that I use to setup the uart as described: 这是我用来设置uart的代码,如下所述:

int uart_init ()
{
    unsigned int ra;

    ra=GET32(RCC_AHB1ENR);
    ra|=1<<0; //enable port A
    PUT32(RCC_AHB1ENR,ra);

    ra=GET32(RCC_APB1ENR);
    ra|=1<<17; //enable USART2
    PUT32(RCC_APB1ENR,ra);

    //PA2 USART2_TX
    //PA3 USART2_RX

    ra=GET32(GPIOA_MODER);
    ra|= (2<<4);
    ra|= (2<<6);
    PUT32(GPIOA_MODER,ra);
    ra=GET32(GPIOA_OTYPER);
    ra&=(1<<2);
    ra&=(1<<3);
    PUT32(GPIOA_OTYPER,ra);
    ra=GET32(GPIOA_AFRL);
    ra|=(7<<8);
    ra|=(7<<12);
    PUT32(GPIOA_AFRL,ra);

    // divisor 136 fractional divisor 11
    PUT32(USART2_BRR,(136<<4)|(11<<0));
    PUT32(USART2_CR1,(1<<13)|(1<<3)|(1<<2));
    return(0);
}

While this is my routine to send a byte through uart: 这是我通过uart发送字节的例程:

void uart_putc ( unsigned int x )
{
    while (( GET32(USART2_SR) & (1<<7)) == 0) continue;
    PUT32(USART2_DR,x);
}

My question is: is this a normal and reasonable behavior? 我的问题是:这是正常而合理的行为吗? In case it is, what is a good strategy to receive the stream of incoming bytes discarding those that are undesired? 在这种情况下,接收丢弃不想要的字节的传入字节流的好策略是什么? In case it is not, what am I doing wrong? 如果不是,我在做什么错?

It's because during the interval between reset and the pins being configured for AFIO they're in a high-impedance state so attempts to read will return undefined data. 这是因为在重置和为AFIO配置的引脚之间的时间间隔内,它们处于高阻抗状态,因此尝试读取将返回未定义的数据。 Your receiver is becoming ready before your transmitter. 接收器在发射器之前已经准备就绪。

To guard against this you need to indicate readiness through an out of band method or if your resets are electrically linked then a dumb method such as sleeping for a second on the receiver and 2 seconds on the transmitter upon startup and after the pins have been configured for AFIO should do it. 为了防止这种情况,您需要通过带外方法或通过电气方式连接复位来表明准备就绪,然后再使用一种愚蠢的方法,例如在启动时以及在配置引脚之后,在接收器上休眠一秒钟,在发送器上休眠2秒。 AFIO应该这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM