Atmega128串口UART 0/1測(cè)試代碼
#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鍵開(kāi)始測(cè)試
{
puts0("test ok!");
for (i=0;i10;i++)
{
putchar0(0x30+i);
}
putchar0(0x0a);
putchar0(0x0d);
}
#else
if (getchar1()=='t')//按鍵盤t鍵開(kāi)始測(cè)試
{
puts1("test ok!");
for (i=0;i10;i++)
{
putchar1(0x30+i);
}
putchar1(0x0a);
putchar1(0x0d);
}
#endif
}
}
評(píng)論