#include<stdio.h>
#include<pic.h>
#include "delay.c" __CONFIG(0x3f72);
#define DQ RC0
#define DQ_DIR TRISC0
#define FOSC 10000
#define BAUD_RATE 9.6 // 9600 Baudrate
#define BAUD_VAL (char)(FOSC/ (16 * BAUD_RATE )) - 1;
// Calculation For 9600 Baudrate @10Mhz
unsigned char i=0;
float Temerature=0;
void ds1820_init();
void Reset(void);
void write(unsigned char);
unsigned char Read(void);
void Serial_init();
void main()
{
unsigned char Temp[9];
DelayMs(100);
Serial_init();
ds1820_init();
DelayMs(100);
printf("\033[2J"); // Clear the Hyper terminal;
while(1)
{
Reset();
write(0xcc);
write(0x44);
DQ_DIR = 1;
DelayUs(10);
while(!DQ);
// this will be raised after finishing conversion
Reset();
write(0xcc);
write(0xbe);
for(i=0;i<9;i++)
Temp[i] = Read(); // Read 9 bytes
for(i=0;i<9;i++)
printf("%d ",Temp[i]);
printf("Temperature:%3.1f%cC",(float)Temp[0]/2,0xf8);
printf("\r");
DelayMs(250);
DelayMs(250);
DelayMs(250);
DelayMs(250);
}
}
void ds1820_init()
{
DQ = 1;
DQ_DIR = 1; // pull up
}
void Reset(void)
{
DQ_DIR = 0;
DQ = 0;
DelayMs(1);
DelayUs(250); // 500us
DQ_DIR = 1;
DelayUs(100); // 40us
while(DQ==1); // wait until presence pulse
DelayMs(1);
DelayUs(250); // 500us
}
void write(unsigned char cmd)
{
for(i=0;i<8;i++){
DQ_DIR = 0; // pull down
DQ = 0;
DelayUs(25); // 10us
DQ = (cmd & 0x01)?1:0; // Send bit
cmd = cmd >> 1;
DelayUs(120); // >45us
DQ_DIR = 1; // release
}
}
unsigned char Read(void)
{
unsigned char temp=0,RecDat=0;
for(i=0;i<8;i++)
{
DQ_DIR = 0;
DQ = 0; // pull down
DelayUs(25); // 10us
DQ_DIR = 1; // release
DelayUs(25); // 10us
temp = DQ; // read bit
temp = temp<<i;
RecDat |= temp;
DelayUs(70); // 30us
}
return RecDat;
}
void Serial_init()
{
TRISC=0xc0; // RC7,RC6 set to usart mode(INPUT)
TXSTA=0x24; // Transmit Enable
SPBRG=BAUD_VAL; // 9600 baud at 10Mhz
RCSTA=0x90; // USART Enable, Continuous receive enable
TXIF=1; // Start Transmit
}
void putch(unsigned char Data) // data TX required for printf
{
while(TXIF==0);
TXREG = Data;
}