比较UART中收到的字符时的逻辑错误

时间:2014-08-06 09:04:54

标签: avr usart

我想比较通过ATMEGA8的RX引脚接收的字符。为什么比较不起作用?

int main()
{
   DDRB = 0XFF;
   UCSRB = (1<<RXEN);
   UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);
   UBRRL = 0X33;
   char r;
   while (1)
   {
      while(!(UCSRA&(1<<RXC)));
      r = UDR;
      if(r=='r') PORTB = 0XFF;
   }
   return 0;
 }

1 个答案:

答案 0 :(得分:0)

便于设置baud_rate的示例代码

#define F_CPU 8000000UL         // Chip CPU frequency here, prevents default 1MHz
#define USART_BAUDRATE 19200UL  // Baud_rate here, baudrates: 300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600
#define BAUD_PRESCALE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)

#include <avr/io.h>

int main(void) {
    DDRB = 0XFF;
    UBRRL = BAUD_PRESCALE;          // baud to  low byte of the UBRR register
    UBRRH = (BAUD_PRESCALE >> 8);   // baud to high byte of the UBRR register
    UCSRB = (1<<RXEN);
    UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);
    char r;
    while(1) {
        //TODO:: Please write your application code 
        while(!(UCSRA&(1<<RXC)));
        r = UDR;
        if(r=='r') PORTB = 0XFF;        
    }
   return 0;    
}