AVR单片机串口接收与发送程序
/*串口初始化函数*/ //使用同一个串口进行发送与接收,mega162具有双串口功能
void Uart_Init(void)
{
UCSRA = 0x02;/*倍速*/
UCSRB = 0x18;/*允许接收和发送*/
UCSRC = 0x06;/*8位数据*/
UBRRH = 0x00;
UBRRL = 12;/*9600*/
}
/*数据发送,查询方式*/
void Uart_Transmit(unsigned char i)
{
while (!(UCSRA & (1<
}
/*数据接收,查询方式*/
unsigned char Uart_Receive( void ) //注意函数类型
{
while (!(UCSRA & (1<
}
/*主函数*/
void main(void)
{
unsigned char temp;
DDRA = 0x00;/*方向输入*/
PORTA = 0xFF;/*打开上拉*/
DDRB = 0xFF;/*方向输出*/
PORTB = 0xFF;/*电平设置*/
DDRC = 0x00;
PORTC = 0xFF;
DDRD = 0x02;
PORTD = 0xFF;
Uart_Init();
while (1)
{
temp = Uart_Receive();/*等待接收数据*/
PORTB = ~temp;/*显示低电平有效*/
Uart_Transmit(temp);/*发送收到的数据*/
}
}
评论