/****PIC单片机通过SPI串口可以读取TC77传感器的温度数值****/
/****通过串口与上位机连接在串口调试工具中可显示温度的数字值**/
/*****************主程序************************/
#include "p18f4620.h"
#define TC77_CS LATAbits.LATA2 //片选信号,低电平有效
//初始化
void initial()
{
INTCON = 0x00;
ADCON1 = 0x07;
PIE1 = 0;
PIE2 = 0;
}
//串口初始化
void EUSART_Init()
{
TXSTA = 0xA4;
RCSTA = 0x90;
BAUDCON =0x00;
TRISC = TRISC|0x80;
TRISC = TRISC&0xBF;
SPBRG = 25;
}
//发送数据到串口
void send_ch(int d)
{
PIR1bits.TXIF = 0;
TXREG = d;
while(TXSTAbits.TRMT == 0);
}
//SPI配置TC77
void TC77_init(void)
{
TRISCbits.TRISC3 = 0;
TRISCbits.TRISC4 = 1;
TRISAbits.TRISA2 = 0;
SSPSTAT = 0xC0;
SSPCON1 = 0x20;
PIR1bits.SSPIF = 0;
}
//读TC77温度传感器
unsigned int Read_TC77(void)
{
unsigned char temh,teml;
unsigned int temp;
TC77_CS = 0; //片选TC77
PIR1bits.SSPIF = 0;
SSPBUF = 0; // 读高8位
while(!PIR1bits.SSPIF);
if(SSPSTATbits.BF)
temh=SSPBUF;
PIR1bits.SSPIF = 0;
SSPBUF = 0; //读低八位
while(!PIR1bits.SSPIF);
if(SSPSTATbits.BF)
teml=SSPBUF;
TC77_CS = 1;
temp = temh;
temp = (temp << 6)+(teml >> 2); //换算为十六位数据
return temp;
}
//延时函数
void wait(unsigned char t)
{
unsigned char i;
unsigned int j;
for(i=0;i for(j=0;j<10000;j++);
}
//主函数
void main()
{
unsigned int T;
initial();
EUSART_Init();
TC77_init();
while(1)
{
T = Read_TC77();
send_ch(0xFF);
send_ch(T);
send_ch(T >> 8);
Nop();
Nop();
wait(10);
}
}