|
- /*******************************************************
- * 程序功能:USART的数据发送和接收
- * 接线说明:核心板PD0和PD1短接,PA0~PA7接到静态数码管显示电路
- * 实验现象:数码管从0加到9如此循环
- * 日 期 : 2014/07/31
- * 作 者 : 翟志刚
- *******************************************************/
- #include <iom16v.h>
- #include <macros.h>
- #define uchar unsigned char
- #define uint unsigned int
- #define BAUD 9600 //波特率采用9600bps
- #define CRYSTAL 1000000 //系统时钟1MHz
- //计算和定义波特率设置参数
- #define BAUD_SETTING (unsigned int)((unsigned long)CRYSTAL/(16*(unsigned long)BAUD)-1)
- #define BAUD_H (unsigned char)(BAUD_SETTING>>8)
- #define BAUD_L (unsigned char)(BAUD_SETTING)
- // USART控制和状态寄存器的标志位定义
- #define RXC 7 // UCSRA位定义
- #define TXC 6
- #define UDRE 5
- #define FE 4
- #define DOR 3
- #define PE 2
- #define U2X 1
- #define MPCM 0
- #define RXCIE 7 // UCSRB位定义
- #define TXCIE 6
- #define UDRIE 5
- #define RXEN 4
- #define TXEN 3
- #define UCSZ2 2
- #define RXB8 1
- #define TXB8 0
- #define URSEL 7 // UCSRC位定义
- #define UMSEL 6
- #define UPM1 5
- #define UPM0 4
- #define USBS 3
- #define UCSZ1 2
- #define UCSZ0 1
- #define UCPOL 0
- #define FRAMING_ERROR (1<<FE)
- #define PARITY_ERROR (1<<PE)
- #define DATA_OVERRUN (1<<DOR)
- #define DATA_REGISTER_EMPTY (1<<UDRE)
- uchar led_7[10]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F};
- uchar i = 0;
- uchar counter = 0;
- // USART接收结束中断服务程序
- #pragma interrupt_handler USART_RXC:12
- void USART_RXC(void) // USART接收中断服务
- {
- uchar status,data;
- status = UCSRA;
- data = UDR;
- if ((status & (FRAMING_ERROR | PARITY_ERROR | DATA_OVERRUN))==0)
- PORTA = led_7[data];
- }
- void USART_Transmit(unsigned char data)
- {
- while (!(UCSRA & DATA_REGISTER_EMPTY)); // 等待发送寄存器空
- UDR = data; // 发送数据
- }
- /*定时器0溢出中断服务程序*/
- #pragma interrupt_handler timer0_ovf:10
- void timer0_ovf(void)
- {
- counter++;
- if(counter == 4)
- {
- USART_Transmit(i);
- PORTB=~PORTB;
- if (++i >= 10) i = 0;
- counter = 0;
- }
- }
- void main( void )
- {
- DDRA = 0xff; // LED段码输出
- PORTA = 0x00;
- DDRB = 0xff;
- PORTB = 0xFF; // LED灯输出
- PORTD = 0x03; // TXD(PD1)输出
- DDRD = 0x02; // RXD(PD0)输入,上拉有效
- UCSRA = 0x00; // USART初始化
- UCSRB = (1<<RXCIE)|(1<<RXEN)|(1<<TXEN); // 允许RXC中断,接收允许,发送允许
- UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0); // 8 Data, 1 Stop, No Parity
- UBRRH = BAUD_H; // 设置波特率
- UBRRL = BAUD_L;
- TIMSK |= (1<<TOIE0); //使能T0溢出中断
- TCCR0 = 0x05; //配置定时器工作普通模式
- TCNT0 = 0xff; //给定时器赋初值
- SREG=0x80; // 开全局中断
- while(1)
- {
- };
- }
复制代码
|
|