欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

单片机必备知识--串口通讯

程序员文章站 2022-06-23 20:33:20
蓝桥杯单片机必备知识-----(12)串口通讯...

蓝桥杯单片机必备知识-----(12)串口通讯

串口初始化函数

//主程序中调用

void UartInit(void)		//9600bps@11.0592MHz
{
	SCON = 0x50;		//8位数据,可变波特率
	AUXR |= 0x01;		//串口1选择定时器2为波特率发生器
	AUXR &= 0xFB;		//定时器2时钟为Fosc/12,即12T
	T2L = 0xE8;		//设定定时初值
	T2H = 0xFF;		//设定定时初值
	AUXR |= 0x10;		//启动定时器2
}

发送字符串

void sendstring(unsigned char *str)//发送字符串
{
	while(*str !='\0')//等待\0
		{
			//sendbyte(*str++);//发送下一个字符
			SBUF=*str++; //将数据放进SBUF缓冲器
			while(TI==0); //等待发送数据完成
			 TI=0; //清除发送完成标志
		}
}

串口中断

void s() interrupt 4
{
	if(RI)
	{
		str1[scount++]=SBUF;   RI=1时接收数据,将数据放入SBUF
		RI = 0;
	}
}

整个代码粘贴

#include <stc15f2k60s2.h>
#include <stdio.h>

#define uchar unsigned char
#define uint unsigned int

uchar tab[] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xff};
uchar dspbuf[] = {10,10,10,10,10,10,10,10};
uchar temperature = 12;
unsigned char str1[20];
unsigned char scount = 0;
unsigned char str[20];

void load();
void sendstring(unsigned char *str);
void sendbyte(unsigned char dat);
void display();
void uart_proc();
void cls()
{
	P2 = (P2 & 0x1f) | 0x80;
	P0 = 0xff;
	P2 = 0x1f;
	
	P2 = (P2 & 0x1f) | 0xa0;
	P0 = 0x00;
	P2 = 0x1f;
}

void UartInit(void)		//9600bps@11.0592MHz
{
	SCON = 0x50;		//8位数据,可变波特率
	AUXR |= 0x01;		//串口1选择定时器2为波特率发生器
	AUXR &= 0xFB;		//定时器2时钟为Fosc/12,即12T
	T2L = 0xE8;		//设定定时初值
	T2H = 0xFF;		//设定定时初值
	AUXR |= 0x10;		//启动定时器2
}


void main()
{

	cls();
	AUXR = 0xc0;
	TMOD = 0x00;
	TL0 = 0xcd;
	TH0 = 0xd4;
	TR0 = 1;
	ET1 = 1;
	ES = 1;
	EA = 1;
	UartInit();
	while(1)
	{
		uart_proc();
	}
}

void s() interrupt 4
{
	if(RI)
	{
		str1[scount++]=SBUF;
		RI = 0;
	}
}
void uart_proc()
{
	if(scount > 0)
	{
		//sendstring(str1);	
		if(str1[scount-1] == 0xa)
		{
			sendstring(str1);		
			
			if((str1[0] =='s')  && (str1[1] == 0xd))
			{
				sprintf(str,"#temperature:%02u\r\n",(uint)(temperature));//发送Hello
				sendstring(str);
			}
			scount = 0;
			
		}
		else
			if(scount==6)
			{
	      sendstring(str1);		
				scount = 0;
			}
		
	}		
}




void sendstring(unsigned char *str)//发送字符串
{
	while(*str !='\0')//等待\0
		{
			//sendbyte(*str++);//发送下一个字符
			SBUF=*str++; //将数据放进SBUF缓冲器
			while(TI==0); //等待发送数据完成
			 TI=0; //清除发送完成标志
		}
}

本文地址:https://blog.csdn.net/qq_43710889/article/details/110082932

相关标签: 蓝桥杯单片机