AVR單片機串口接收與發(fā)送程序
/*串口初始化函數(shù)*/ //使用同一個串口進行發(fā)送與接收,mega162具有雙串口功能
void Uart_Init(void)
{
UCSRA = 0x02;/*倍速*/
UCSRB = 0x18;/*允許接收和發(fā)送*/
UCSRC = 0x06;/*8位數(shù)據(jù)*/
UBRRH = 0x00;
UBRRL = 12;/*9600*/
}
/*數(shù)據(jù)發(fā)送,查詢方式*/
void Uart_Transmit(unsigned char i)
{
while (!(UCSRA & (1<
}
/*數(shù)據(jù)接收,查詢方式*/
unsigned char Uart_Receive( void ) //注意函數(shù)類型
{
while (!(UCSRA & (1<
}
/*主函數(shù)*/
void main(void)
{
unsigned char temp;
DDRA = 0x00;/*方向輸入*/
PORTA = 0xFF;/*打開上拉*/
DDRB = 0xFF;/*方向輸出*/
PORTB = 0xFF;/*電平設(shè)置*/
DDRC = 0x00;
PORTC = 0xFF;
DDRD = 0x02;
PORTD = 0xFF;
Uart_Init();
while (1)
{
temp = Uart_Receive();/*等待接收數(shù)據(jù)*/
PORTB = ~temp;/*顯示低電平有效*/
Uart_Transmit(temp);/*發(fā)送收到的數(shù)據(jù)*/
}
}
評論