Atmega128串口UART 0/1测试代码
#includeavr/io.h>
#define fosc 7372800UL //晶振7.3728MHZ
#define baud 9600//波特率
#define com0
void uart0_init(void)
{
UCSR0B = 0x00; //disable while setting baud rate
UCSR0A = 0x00;
UCSR0C =(1UCSZ01)|(1UCSZ00);//8bit+1bit stop
UBRR0L=(fosc/16/(baud+1))%256;
UBRR0H=(fosc/16/(baud+1))/256;
UCSR0B =(1RXEN0)|(1TXEN0);//RXCEN TXCEN
}
void uart1_init(void)
{
UCSR1B = 0x00; //disable while setting baud rate
UCSR1A = 0x00;
UCSR1C = (1UCSZ11)|(1UCSZ10);//8bit+1bit stop
UBRR1L=(fosc/16/(baud+1))%256;
UBRR1H=(fosc/16/(baud+1))/256;
UCSR1B =(1RXEN1)|(1TXEN1);//RXCEN TXCEN
}
void putchar0(unsigned char c)
{
while (!(UCSR0A(1UDRE0)));
UDR0=c;
}
void putchar1(unsigned char c)
{
while (!(UCSR1A(1UDRE1)));
UDR1=c;
}
unsigned char getchar0(void)
{
while(!(UCSR0A (1RXC0)));
return UDR0;
}
unsigned char getchar1(void)
{
while(!(UCSR1A (1RXC1)));
return UDR1;
}
void puts0(char *s)
{
while (*s)
{
putchar0(*s);
s++;
}
putchar0(0x0a);
putchar0(0x0d);
}
void puts1(char *s)
{
while (*s)
{
putchar1(*s);
s++;
}
putchar1(0x0a);
putchar1(0x0d);
}
int main(void)
{
unsigned char i;
#ifdef com0
uart0_init();
puts0("HELLO!");
#else
uart1_init();
puts1("HELLO!");
#endif
while(1)
{
#ifdef com0
if (getchar0()=='t')//按键盘t键开始测试
{
puts0("test ok!");
for (i=0;i10;i++)
{
putchar0(0x30+i);
}
putchar0(0x0a);
putchar0(0x0d);
}
#else
if (getchar1()=='t')//按键盘t键开始测试
{
puts1("test ok!");
for (i=0;i10;i++)
{
putchar1(0x30+i);
}
putchar1(0x0a);
putchar1(0x0d);
}
#endif
}
}
- 基于ATmega128单片机的矿用磁力启动器控制系统设计(06-04)
- 一款宠物狗无线感知交互系统让人和动物的社交网络成真(06-03)
- ATmega128 流水灯的两种实现方法(基于AVR GCC)(11-23)
- Atmega128串口详解(11-23)
- 基于ATMEGA128单片机压力的测量(11-21)
- ATmega128型号标识说明(11-11)