1. 程式人生 > >PIC微控制器精通_串列埠通訊模組C實現

PIC微控制器精通_串列埠通訊模組C實現

1.串列埠通訊頭/定義檔案 usart.h

#ifndef _SERIAL_H_
#define _SERIAL_H_

#define BAUD 9600      
#define FOSC 9216000L
#define NINE 0     /* Use 9bit communication? FALSE=8bit */

#define DIVIDER ((int)(FOSC/(16UL * BAUD) -1))
#define HIGH_SPEED 1

#if NINE == 1
#define NINE_BITS 0x40
#else
#define NINE_BITS 0
#endif

#if HIGH_SPEED == 1
#define SPEED 0x4
#else
#define SPEED 0
#endif

#if defined(_16F87) || defined(_16F88)
	#define RX_PIN TRISB2
	#define TX_PIN TRISB5
#else
	#define RX_PIN TRISC7
	#define TX_PIN TRISC6
#endif

/* Serial initialization */
//'\'是對函式內屬性的定義 不可缺少
#define init_comms()\
	RX_PIN = 1;	\
	TX_PIN = 1;		  \
	SPBRG = DIVIDER;     	\
	RCSTA = (NINE_BITS|0x90);	\
	TXSTA = (SPEED|NINE_BITS|0x20)

void putch(unsigned char);
unsigned char getch(void);
unsigned char getche(void);

#endif

2.串列埠通訊源/實現檔案 usart.c

/******************************************/
/*Author:Shen Chucu  All Rights Reserved!**
/*Tsinghua University
/*2016-11-15
/********************************************/
#include <pic.h>
#include <stdio.h>
#include "usart.h"
__CONFIG(0x3ffa);


void delay(unsigned int x);
static int label=0; //不做事件響應
void main()
{
   INTCON=0x00;
   GIE=1;
   PEIE=1;
   RCIE=1;
   init_comms();
   CREN=1;
   SPEN=1;
   while(1)
   {//等待中斷 並進行事件響應設定
     if(label==1)
      {
        printf("OK"); 
		label = 0; //傳送一個回饋訊號即可
        delay(50);
      }
     if(label==2)
     {
        printf("ERROR");
    	label = 0; //傳送一個回饋訊號即可
        delay(50);
      }   
   }
}  

void interrupt IsReceive()
{  
   if(RCIE&&RCIF==1) //接受中斷使能位 + 接收中斷標誌位
    {
        unsigned char temp=RCREG;  //把上位機發送的資料儲存下來
        if(temp=='S')
          { 
            label=1;   //傳送資料標誌 1
          } 
       else if(temp=='E')
             {
               label=0; //傳送資料標誌 0 
             }
             else 
               label=2;  //傳送資料標誌 2  
    }
}

void delay(unsigned int x)
{
    unsigned int a,b;  //延時時間110x
    for(a=x;a>1;a--)
       for(b=110;b>1;b--)
          ;
}