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

📄 usartreceive9bit.c

📁 AVR单片机系列的ATmega162的USART编程
💻 C
字号:
#include <avr/io.h>

void DelayMs(long int s);
void USART_Init(unsigned int baud);
void USART_Transmit0(unsigned char data);
unsigned char USART_Receive0(void);
unsigned int USART_Receive1(void);

int main(void)
{

	DDRC=0xff;
	
	unsigned int rec;
	unsigned char res;
	
	USART_Init(25);
	
	PORTC=0xff;
	while(1)
	{

			
			rec=USART_Receive1();
			
		//	if(rec==-1) continue;
			
			if(rec>>8)
			{
				res=rec;
				switch(res)
				{
					case 'A':
						PORTC&=~1;
						DelayMs(50);
						break;
					case 'B':
						PORTC&=~(1<<1);
						DelayMs(50);
						break;
					case 'C':
						PORTC&=~(1<<2);
						DelayMs(50);
						break;
					case 'D':
						PORTC&=~(1<<3);
						DelayMs(50);
						break;
					default:
						;
				}

				PORTC=0xff;
			}
	}
	
}

void USART_Init(unsigned int baud)
{
	UBRR0H = (unsigned char)(baud>>8);
	UBRR0L = (unsigned char)baud;
	
	UCSR0B|=(1<<RXEN0)|(1<<TXEN0);
	UCSR0C|=(1<<URSEL0)|(3<<UCSZ00);
	
	UBRR1H = (unsigned char)(baud>>8);
	UBRR1L = (unsigned char)baud;
	
	UCSR1B|=(1<<RXEN1)|(1<<UCSZ12);
	UCSR1C|=(1<<URSEL1)|(3<<UCSZ10);

}

void USART_Transmit0(unsigned char data)
{
	while((UCSR0A&(1<<UDRE0))==0)
		;
	UDR0=data;
}
unsigned char USART_Receive0(void)
{
	while((UCSR0A&(1<<RXC0))==0)
		;
	return UDR0;
}


unsigned int USART_Receive1(void)
{
	unsigned char status,resh,resl;
	while((UCSR1A&(1<<RXC1))==0)
		;
	status=UCSR1A;
	resh=UCSR1B;
	resl=UDR1;
	
//	if(status&(1<<FE1)|(1<<DOR1)|(1<<PE1))
//		return -1;
	resh=(resh>>1)&0x01;
	return((resh<<8)|resl);
}

void DelayMs(long int s)
{
	int t;
	while(s--)
	{
		for(t=1000;t>0;t--)
			;
	}

}

⌨️ 快捷键说明

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