I have been struggling to work with DS18B20 Sensor to get it worked but not working.
I am getting 4095.94 Degree. I have copied code given in this forum.
No change in temperature. What could be wrong ? I have connected on PB5 Pin and Sensor i tried with both 5V and 3.3V with 4.7K Pull up resistor and 0.1uF Capacitor
Please guide what could be wrong ?
Code: Select all
int DSPIN = PB5;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop()
{
// put your main code here, to run repeatedly:
double temp = TempRead();
temp = temp * 0.0625; // conversion accuracy is 0.0625 / LSB
Serial.print("Temperature: ");
Serial.print(temp);
Serial.println(" °C");
Serial.println("");
delay(500);
}
boolean DS18B20_Init()
{
pinMode(DSPIN, OUTPUT);
digitalWrite(DSPIN, HIGH);
delayMicroseconds(5);
digitalWrite(DSPIN, LOW);
delayMicroseconds(750);//480-960
digitalWrite(DSPIN, HIGH);
pinMode(DSPIN, INPUT);
int t = 0;
while (digitalRead(DSPIN))
{
t++;
if (t > 60) return false;
delayMicroseconds(1);
}
t = 480 - t;
pinMode(DSPIN, OUTPUT);
delayMicroseconds(t);
digitalWrite(DSPIN, HIGH);
return true;
}
void DS18B20_Write(byte data)
{
pinMode(DSPIN, OUTPUT);
for (int i = 0; i < 8; i++)
{
digitalWrite(DSPIN, LOW);
delayMicroseconds(10);
if (data & 1) digitalWrite(DSPIN, HIGH);
else digitalWrite(DSPIN, LOW);
data >>= 1;
delayMicroseconds(50);
digitalWrite(DSPIN, HIGH);
}
}
byte DS18B20_Read()
{
pinMode(DSPIN, OUTPUT);
digitalWrite(DSPIN, HIGH);
delayMicroseconds(2);
byte data = 0;
for (int i = 0; i < 8; i++)
{
digitalWrite(DSPIN, LOW);
delayMicroseconds(1);
digitalWrite(DSPIN, HIGH);
pinMode(DSPIN, INPUT);
delayMicroseconds(5);
data >>= 1;
if (digitalRead(DSPIN)) data |= 0x80;
delayMicroseconds(55);
pinMode(DSPIN, OUTPUT);
digitalWrite(DSPIN, HIGH);
}
return data;
}
int TempRead()
{
if (!DS18B20_Init()) return 0;
DS18B20_Write (0xCC); // Send skip ROM command
DS18B20_Write (0x44); // Send reading start conversion command
if (!DS18B20_Init()) return 0;
DS18B20_Write (0xCC); // Send skip ROM command
DS18B20_Write (0xBE); // Read the register, a total of nine bytes, the first two bytes are the conversion value
int temp = DS18B20_Read (); // Low byte
temp |= DS18B20_Read () << 8; // High byte
return temp;
}