⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 m8-串口收发.c

📁 这是mega8的串口收发程序
💻 C
字号:
//ICC-AVR application builder : 2007-5-25 16:09:59
// Target : M8
// Crystal: 8.0000Mhz

#include <iom8v.h>
#include <macros.h>
int data,data0,data1;
void port_init(void)
{
 PORTB = 0x00;
 DDRB  = 0xff;
 PORTC = 0xFF; //m103 output only
 DDRC  = 0x00;
 PORTD = 0x00;
 DDRD  = 0xf0;
}
/*
//UART0 initialize
// desired baud rate: 2400
// actual: baud rate:2404 (0.2%)
// char size: 8 bit
// parity: Disabled
void uart0_init(void)
{
 UCSRB = 0x00; //disable while setting baud rate
 UCSRA = 0x00;
 UCSRC = BIT(URSEL) | 0x06;
 UBRRL = 0xCF; //set baud rate lo
 UBRRH = 0x00; //set baud rate hi
 UCSRB = 0x98;
}*/

//UART0 initialisation
// desired baud rate: 9600
// actual: baud rate:9615 (0.2%)
// char size: 8 bit
// parity: Disabled
void uart0_init(void)
{
 UCSRB = 0x00; //disable while setting baud rate
 UCSRA = 0x00;
 UCSRC = 0x86; //1000 0110
 UBRRL = 0x33; //set baud rate lo
 UBRRH = 0x00; //set baud rate hi
 UCSRB = 0x98;
}


#pragma interrupt_handler uart0_rx_isr:12
void uart0_rx_isr(void)
{
 data1=UDR;//uart has received a character in UDR
 //if(data1==data0)
  data=data1;
 //else
 // data=0;
 //data0=data1;

}

//call this routine to initialize all peripherals
void init_devices(void)
{
 //stop errant interrupts until set up
 CLI(); //disable all interrupts
 port_init();
 uart0_init();
 MCUCR = 0x00;
 GICR  = 0x00;
 SEI(); //re-enable interrupts
 //all peripherals are now initialized
}
void delay(int t)			//延时
{int x;
for(;t>=0;t--)	 			//双重循环
for(x=0;x<1020;x++);			//12000*100约一秒
}
display(int number)
{
 int i,n[4]={0},   	 		//要显示的四个数字
 d[4]={0X7F,0XBF,0XDF,0XEF},//四个选通端轮流为低
 num[10]={0X3F,0X06,0X5B,0X4F,0X66,0X6D,0X7D,0X27,0X7F,0X6F};//十个数字
 DDRD  = 0xF0;
 n[0]=(number%10000)/1000;
 n[1]=(number%1000)/100;
 n[2]=(number%100)/10;
 n[3]=number%10;
  for(i=0;i<4;i++)
   {
   PORTD=d[i];	  	  	  	//指定显示位置	  	  
   //或PORTD=~(0X80>>i)
   PORTB=num[n[i]];delay(5);//显示延时
   PORTB=0x00;		 		 //显示清空
   } 		
}

key(void)
{
	int k=0;
	if((PINC&0x01)==0)k=1;
	if((PINC&0x02)==0)k=2;
	if((PINC&0x04)==0)k=3;	  
	if((PINC&0X08)==0)k=4;	  
	if((PINC&0X10)==0)k=5;
	if((PINC&0x20)==0)k=6;
	return(k);
}
void sendchar(char w)
{
int i;
UDR=w;
while(!(UCSRA&0X40));//可提高速度
	UCSRA|=0X40;
}

void main()
{
 int i=0,k=0;
 init_devices();
 while(1)
 	{
	 k=data;
	 for(i=0;i<10;i++)
	 display(data1);
	 k=key();
	 if(k!=0)
	 	{
		 while(k==key());
		 sendchar(k+96);
		 //delay(10);
		 //sendchar(k+91);		 
		}
 	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -