串口通信实例与详解
/********************************************************/
/*Author: Chunxu Shen; All Rights Reserved!
/*Tsinghua University
/*2016-11-14
********************************************************/
#include <pic.h>
__CONFIG(0x3ffa);
#define BAUD ???UL
#define FOSC ???UL //根据实际情况,自己设定
#define DIVIDER ((int)(FOSC/(16UL * BAUD) -1))
unsigned int send1[2] = {0x4f,0x4b}; //'O'=ASCII 0x4f;'K'=ASCII 0x4b; “OK”
unsigned int send2[5] = {0x45,0x52,0x52,0x4f,0x52}; //'E'=ASCII 0x45;'R'=ASCII 0x52 “ERROR”
unsigned char rece; //全局变量
unsigned int cnt; //计数器
void main(void)
{
//初始化端口程序
TRISC7 = 1; //RX端口设为输入有效
TRISC6 = 0; //TX端口设为输出有效
//初始化串口设置
SPBRG = DIVIDER; //波特率设置
TXSTA = 0x04; //异步通讯-禁止发送数据-高速模式
RCSTA = 0xA0; //串口使能-接收单字符-禁止连续接受
//中断设计
RCIE = 1; //允许接收信号触发中断
GIE = 1; //打开中断总开关
PEIE = 1; //允许外围设备触发中断
//无限循环,等待PC机触发中断
while(1)
{
......
}
}
//接收上位机送发的信号
void interrupt usart(void)
{
if( RCIE )
//RCIE:开放串行中断请求 RCIF:接收中断允许(接收区满or单字符)
{
......
}
}
|