新聞中心

PIC196F877A串口通信程序

作者: 時(shí)間:2016-11-19 來源:網(wǎng)絡(luò) 收藏
今天上午完成PIC16F877A與上位機(jī)的串口通信程序!

注意:使用MPLAB IDE C語言編程時(shí),自定義頭文件要使用""包含不能使用<>

本文引用地址:http://butianyuan.cn/article/201611/318568.htm

串口與單片機(jī)的連線原理圖

串口通信頭文件

#ifndef T232_H
#define T232_H

#include "main.h"
//定義一幀的開始和結(jié)束
#define FRAME_BEGIN 0x28//開始幀標(biāo)志
#define FRAME_END 0x29//結(jié)束幀標(biāo)志

void init_232() ;
void send_str(const char *str) ;
char get_char() ;
void get_string(char *temp) ;
void put_char(char temp) ;
#endif

串行通信子程序


//基于TPDEM1,通過串口調(diào)試助手等串口觀察軟件觀察程序,
//將TPDEM1通過ICD2配送的串口延長(zhǎng)線與PC的串口連接,設(shè)置PC的串口為默認(rèn)設(shè)置,如波特率9600,數(shù)據(jù)位8,無校驗(yàn)位,使用FIFO
#include "t232.h"
/*
*Function:init seriel port
*/
void init_232()
{
INTCON=0;
TRISC7=1; //RX置輸入
TRISC6=0; //TX清成輸出
RCSTA=0x90;//連續(xù)接受多位數(shù)據(jù)
TXSTA=0x24;
SPBRG=25; //9600=4000000/(16*(X+1))->X=25,high speed mode
// INTCON=0xC0;//開GIE,外圍中斷PEIE
//RCIE=1; //開接收中斷
}
/*
*Fuction :send const string to seriel port
/

void send_str(const char *p)
{
while((*p)!=/0)
{
put_char(*p++) ;
}
}
/
Function:get charactor from serial port
*/
char get_char()
{
char temp ;
while(!RCIF) ; /* set when register is not empty */
temp = RCREG ;
return RCREG; /* RXD9 and FERR are gone now */
}

/*
*Function:send charactot to serial port
/
void put_char(char temp)
{
TXREG=temp ;
while(TRMT==0) ;
}

/*
*Function:get num bytes charactot
/
void get_string(char *t)
{
uchar i ;
char temp ;

//有可能接受一幀數(shù)據(jù)后因?yàn)槿ヌ幚頂?shù)據(jù),導(dǎo)致接受下一幀數(shù)據(jù)失敗
SPEN=1 ;//必須注意在連續(xù)接受完一幀數(shù)據(jù)時(shí),一定要把這兩位使能,
CREN=1 ;//我就是因?yàn)闆]有使能查了一上午的錯(cuò),在找出錯(cuò)誤所在;
while(1)
{
temp=get_char() ;
if(temp==FRAME_BEGIN)
{
i=0 ;
continue ;
}
if(temp==FRAME_END)
{
t[i]=/0 ;
break ;
}
t[i++]=temp ;
}
}



關(guān)鍵詞: PIC196F877A串口通

評(píng)論


技術(shù)專區(qū)

關(guān)閉