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; //延時時間110xfor(a=x;a>1;a--)for(b=110;b>1;b--); }
總結
以上是生活随笔為你收集整理的PIC单片机精通_串口通信模块C实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【飞秋】记一次“偷盗”别人的CSS和Js
- 下一篇: DatagridView 常用功能代码