用proteus模拟,单片机型号:ATMega16
电路图:
?U1(接收端)代码:
//共阳极数码管,接收端代码,ATMega16
#include<iom16v.h>
const unsigned char num[] = { 0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90 };
unsigned int led[3];
unsigned char x = 0;
//io初始化
void io_init(void)
{
DDRC = 0XFF;
PORTC = 0X00;
DDRD = 0XF0;
PORTD = 0XF0;
}
//时钟初始化 T/C0
void t_init(void)
{
TCCR0 = 0B00001100;//ctc,256分频
OCR0 = 50;
}
//USART初始化
void usart_init(unsigned int baud)
{
UBRRH = (unsigned char)(baud>>8);
UBRRL = (unsigned char)baud;
UCSRB = 1<<RXEN;
UCSRC = (1<<URSEL)|(3<<UCSZ0);
}
//数据接收函数
unsigned int usart_receive(void)
{
unsigned char dl,dh;
unsigned int d;
while(!(UCSRA & (1<<RXC))) ;
dl = UDR;
while(!(UCSRA & (1<<RXC))) ;
dh = UDR;
d = (unsigned int)dl + ((unsigned int)dh<<8);
return d;
}
//中断刷新
#pragma interrupt_handler _led:20
void _led(void)
{
PORTD |= 0xF0;
x =(++x)%4;
PORTC = num[led[x]];
switch(x)
{
case 0: PORTD &= ~(1<<4); break;//个位
case 1: PORTD &= ~(1<<5); break;//十位
case 2: PORTD &= ~(1<<6); break;//百位
case 3: PORTD &= ~(1<<7); break;//千位
default: ; break;
}
}
//译码函数
void ledbuf(unsigned int input)
{
unsigned char i;
for(i = 0; i <= 3; i++)
{
led[i] = input % 10;
input = input /10;
}
}
void main(void)
{
io_init();
t_init();
usart_init(103);
TIMSK = 1<<1;
SREG = 1<<7; // T0比较匹配
while(1)
{
ledbuf(usart_receive());
}
}
U2(发送端代码):
//发送数据代码
#include<iom16v.h>
#define DATA 9531
//传输数据DATA
//usart初始化
void usart_init(unsigned int baud)
{
UBRRH = (unsigned char)(baud>>8);
UBRRL = (unsigned char)baud;// 设置波特率
UCSRB = 1<<TXEN;//发送器使能
UCSRC = (1<<URSEL)|(3<<UCSZ0);// 帧格式:8个数据位,1个停止位
}
//数据发送函数
void usart_transmit(unsigned int data)
{
while(!(UCSRA & (1<<UDRE))) ;
UDR = (unsigned char)data;
while(!(UCSRA & (1<<UDRE))) ;
UDR = (unsigned char)( data>>8);
}
void main(void)
{
usart_init(103);
while(1)
{
usart_transmit(DATA);
}
}
|