【发布时间】:2014-09-14 01:01:55
【问题描述】:
我正在为 MCU 编写代码,直到它将通过 UART (RS232) 传输数据。 [ATmega8A]
目前,我正在 Proteus 中测试我的代码:
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdlib.h>
#include <compat/twi.h>
#define FOSC 16000000 //Clock Speed
#define BAUD 9600 //Baud rate set to 9600
#define MYBRR FOSC/16/BAUD-1
void USART_Init (void)
{
UBRRH = (MYBRR >> 8); //Code for setting
UBRRL = MYBRR; //the baud rate
UCSRB = (1 << RXEN) | (1 << TXEN); //Enable receiver and transmitter
UCSRC = (1 << URSEL) | (1 << UCSZ0) | (1 << UCSZ1); //Frame format setting: 8 Data, 2 Stop bit
}
/* USART transmit function */
void USART_Transmit(unsigned char data)
{
while(!(UCSRA & (1 << UDRE))); //Wait until transmit buffer is empty
UDR = data;
}
/* USART receive function */
unsigned char USART_Receive(void)
{
while(!(UCSRA & (1 << RXC))); //Wait until data is received
return UDR; //Get the data from buffer and return it
}
以及main中的测试代码:
int main(void)
{
unsigned char c;
while(1)
{
a = USART_Receive();
c = 10;
USART_Transmit(c);
_delay(10000);
}
}
在 Proteus 中,虚拟终端显示 0。但是,我希望看到 10。 这只是一个示例,通常只有最后一个数字/字符会显示在虚拟终端上。 我无法解释这一点。 Proteus bug 还是逻辑错误?
感谢您的建议。
【问题讨论】:
-
我没有看到 UART 初始化。我应该注意到几个 AVR/ATMega 控制器中的 UCSRA、UDR 和其他常量值可能不同。
-
我初始化了UART,只是这里没有包括它。只需将其包含在上面的代码中即可。
-
尝试
c = 'A';而不是发送换行符 (10)。 -
那行得通。但我也想传输像FF这样的东西。在这里,同样只有 F 会被传输。
标签: c avr uart serial-communication data-loss