atmega48的异步串行通信
时间:10-02
整理:3721RD
点击:
- #include <iom48v.h>
- #include <macros.h>
- #define uchar unsigned char
- #define uint unsigned int
- #pragma interrupt_handler tx_int:21
- uchar duanxuan[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,
- 0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e,0x00};
- uchar weixuan[]={0X01,0X02,0X04,0X08};
- uchar a[]={1,2,3,4,5,6,7,8,9};
- void io_init()
- {
- DDRC|=0X0F;
- PORTC&=0XF0;
- DDRB=0XFF;
- PORTB=0XFF;
- }
- int uart_init()
- {
- UCSRnA=0X00;
- UCSRnB=0X00;
- UCSRnC=0X20;//异步,偶校验,1位停止位,上升沿发
- UBBRL=12;
- UBBRH=(12>>8);
- UCSRnB=0x48;//发送,5位数据位,发送结束中断使能
- SREG=0X80;//开启总中断
- DDRD|=BIT(2);//设置TX为输出
- }
- void delay(uint ms)
- {
- uint i,j;
- for(i=0;i<ms;i++)
- {
- for(j=0;j<140;j++);
- }
- }
- void tx_int()
- {
- uchar i=0;
- PORTC|=weixuan[a[i]];
- PORTB=duanxuan[i];
- delay(1);
- i++;
- if(i==8)
- i=0;
- }
- void main()
- {
- uchar i;
- io_init();
- uart_init();
- while(1)
- {
- for(i=0;i<9;i++)
- {
- while(!(UCSRnA&(1<<UDREn)));//等待数据寄存器为空
- UDRn=a[i];
- while(!(UCSRnA&(1<<TXCn)));//等待发送结束
- }
- }
研究了两个小时,终于搞掂了 讲n全部变为0就可以了 以为mega48那个是USART0,所以寄存器的那个n是0