简体   繁体   English

通过PC在Atmega32A上进行UART通信

[英]UART communication on Atmega32A with PC

I'm a begginer in programming AVR microcontroler and I get a lot of headacke sometimes from reading the datasheets. 我是AVR微控制器编程的入门者,有时阅读数据表会遇到很多麻烦。 I'm trying to make a communication between my AVR and PC just to send some caracters and receive it on my computer. 我正在尝试在AVR和PC之间进行通信,只是发送一些角色并在计算机上接收它。 There are two lines I don't understand from the whole program and that is: 我对整个程序不了解有两行 ,那就是:

 void USART_init(void)
{
    UBRRH = (uint8_t)(BAUD_PRESCALLER>>8); <---- this one!
    UBRRL = (uint8_t)(BAUD_PRESCALLER); <--- and this one
    UCSRB = (1<<RXEN)|(1<<TXEN);
    UCSRC = (1<<UCSZ0)|(1<<UCSZ1)|(1<<URSEL);
}

Datasheet 数据表

Why do I have to shift BAUD_PRESCALLER with 8? 为什么我必须将BAUD_PRESCALLER换8? If BAUD_PRESCALLER is a number and shifting that number with 8 doesn't mean the result will be zero?(Because we are shifting it too many times) 如果BAUD_PRESCALLER是一个数字并且将该数字移位8并不意味着结果将为零?(因为我们将其移位了太多次)

From the datasheet I understand that UBRRH contains the four most significant bits and the UBRRL contains the eight least signicant bits of the USART baut rate.(Note:UBBR is a 12-bit register) 从数据表中,我了解到UBRRH包含USART波特率的四个最高有效位,而UBRRL包含USART波特率的八个最低有效位。(注意:UBBR是一个12位寄存器)

So how actually we put all the required numbers in the UBBR register? 那么,实际上我们如何将所有必需的数字放入UBBR寄存器中?

You have to shift it right 8 bits because the result of BAUD_PRESCALLER is larger than 8 bits. 您必须将其右移8位,因为BAUD_PRESCALLER的结果大于8位。 Shifting it right 8 bits gives you the most significant byte of a 16-bit value. 将其右移8位可为您提供16位值的最高有效字节。

For example, if the value of BAUD_PRESCALAR is 0x123 - then 0x1 would be assigned to UBRRH and 0x23 would be assigned to UBRRL. 例如,如果BAUD_PRESCALAR的值为0x123-则将0x1分配给UBRRH,将0x23分配给UBRRL。

If the library was smart it could also perform sanity checking on the BAUD_PRESCALAR to make sure it fits in 16bits. 如果库很聪明,它也可以对BAUD_PRESCALAR进行完整性检查,以确保它适合16位。 If it can't, that means you cannot achieve the baud rate you want given the clock you are using. 如果不能,则意味着您无法使用给定的时钟达到所需的波特率。 If you're UBRRx is truly 12bits, the sanity check would look something like this: 如果您的UBRRx确实是12位,那么完整性检查将如下所示:

#if BAUD_PRESCALAR > 0xFFF
#error Invalid prescalar
#endif

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

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