#include<htc.h>
__CONFIG(0x2F84);
__CONFIG(0x1EFF);
#define _XTAL_FREQ 4000000 // I used 4mHz
#define STX 20 // change these to suit
#define ETX 21
void ADCInit()
{
ANSELA = 0xF;
ANSELB = 0;
ANSELE = 0;
ADCON1 = 0xA0;
}
unsigned int ADCread(unsigned char ch)
{
if (ch>13) // i have 4 thermistors voltage connected
return 0; // to input of pic16f1937
ADCON0 = 0;
ADCON0 = ch<<3; // select ADCchannel
ADCON0 = 1; // swich on adc module
NOP();
NOP();
GO=1; //START CONVERSION
while(GO); //waiting conversion to finish
ADCON0=0;
return (int)ADRESH *256 + ADRESL;
}
long GetADC(unsigned char ch) // oversample 24 times
{
char loop = 23;
long result = 0;
while(loop--)
result += ADCread(ch);
return result;
}
void HSerinit()
{
TRISC = 0xC0; // should really be set
SPBRG = 25; // 4mhz xtal 9600 BAUD
TXSTA = 0x24; // TXEN and BRGH
RCSTA = 0x90; // SPEN and CREN
}
unsigned int getTemp() // This will work out the temp
{ // Its in fixed point so 663 is 66.3 degrees
int idx;
long High,Low, Actual;
float temp1,temp2;
int tempArray[] = {18436,17305,16101,14845,13570,12288,11048,9874,
8774,7754,6826,5984,5235,4579,4005,3500};
// these are oversampled values
High = Low = tempArray[0];
Actual = GetADC(0);
for (idx=0;idx<16;idx++)
{
if( Actual < tempArray[idx])
{
Low = tempArray[idx+1];
High = tempArray[idx];
}
else
{
if(High == Low) return 0; // this bit works out a percentage
temp1 = High - Low; // and fills in the gaps
temp2 = High - Actual;
temp1 = temp2 / temp1;
temp2 = (50 * temp1) + ((idx-1) * 50);
return (unsigned int) temp2; // returns 0.0 to 75.0 (fixed )
} // remember the decimal point.
}
return 750;
}
void SendTemp(unsigned int temp)
{
unsigned char CRC=0, idx;
unsigned char sendArray[6];
// Change this to suit YOUR application
sendArray[0] = STX;
sendArray[1] = 2;
sendArray[2] = temp / 256;
sendArray[3] = temp % 256;
sendArray[5] = ETX;
for(idx = 1;idx<4;idx++)
CRC^= sendArray[idx];
sendArray[4] = CRC;
for(idx = 0;idx<6;idx++)
{
while(!TXIF);
TXREG = sendArray[idx]; // send to PC
}
}
void main()
{
unsigned int temperature;
OSCCON = 0x3B; // internal 4 meg
NOP();
NOP();
HSerinit(); // set up Tx ports
ADCInit(); // set up adc
while(1)
{
temperature = getTemp(); // get actual temp
SendTemp(temperature); // send
}
}