STC12C5A60S2串口2通信测试程序(实现串口自发自收)

快速导航
STC12已封装好的函数库

STC12C5A60S2串口2管脚定义
请添加图片描述

#include <STC12C5A60S2.H>
#include <intrins.h>

#define uchar unsigned char
#define uint unsigned int
	
/*Define UART parity mode*/
/*定义串口校验模式*/
#define NONE_PARITY     0   //None parity
#define ODD_PARITY      1   //Odd parity
#define EVEN_PARITY     2   //Even parity
#define MARK_PARITY     3   //Mark parity
#define SPACE_PARITY    4   //Space parity

#define PARITYBIT EVEN_PARITY   //Testing even parity


#define FOSC 11059200L      //系统频率
#define BAUD 115200         //UART 波特率

#define S2RI  0x01          //S2CON.0
#define S2TI  0x02          //S2CON.1
#define S2RB8 0x04          //S2CON.2
#define S2TB8 0x08          //S2CON.3

bit busy;



void UartInit2(void)
{	
	S2CON = 0x50;			//8位数据,可变波特率
	BRT = -(FOSC/32/BAUD);  //设置波特率发生器自动重载
	AUXR = 0x14;            //波特率发生器工作在1T模式下
	IE2 = 0x01;             //使能串口2中断
	EA = 1;                 //开总中断
}

//向串口发送一个字符
void putchar(char ch)
{
	while (busy);           //等待完成之前的数据被发送
	ACC = ch;              //计算校验位 P (PSW.0)
	if(P)
	{
#if (PARITYBIT == ODD_PARITY)
        S2CON &= ~S2TB8;    //设计奇偶校验位为 0
#elif (PARITYBIT == EVEN_PARITY)
        S2CON |= S2TB8;     //设置奇偶校验位为 1
#endif
	}
	else
	{
#if (PARITYBIT == ODD_PARITY)
        S2CON |= S2TB8;     //设置奇偶校验位为 1
#elif (PARITYBIT == EVEN_PARITY)
        S2CON &= ~S2TB8;    //设置奇偶校验位为 0
#endif
	}
	busy = 1;
    S2BUF = ACC;            //发送数据到串口2缓冲区
}

//向串口发送一段字符串
void prints(char *s)
{
	while(*s)
	{
		putchar(*s++);
	}
}

void main()
{
	UartInit2();
	prints("Hello World");
	while(1);
}


void Uart2() interrupt 8 using 1
{
	uchar dataTemp;//用于存放接收数据
	if(S2CON & S2RI)
	{
		S2CON &= ~S2RI;     	//清除中断标志位
		dataTemp = S2BUF;       //串口接收到的数据
		
		
		/*实现串口数据自发自收*/
		S2BUF = dataTemp;//将接收到的数据发送出去

	}
	if(S2CON & S2TI)
	{
		S2CON &= ~S2TI;     //清除发送中断标志位
		busy = 0;           //清除发送忙标志
	}
}

本程序参考资料STC官方代码

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值