[SOLVED] Temp sensor DS18B20 on STM32 sometimes read 85
Posted: Thu Jan 07, 2021 3:59 am
I'm using a temperature sensor DS18B20 with STM32F103 Bluepill, but sometimes this sensor gives me 85°C which is the power-on reset value of the temperature register. I'm so confused because sometimes it can give me the correct value but mostly is 85°C. I have put a 4.7K resistor as the pull-up resistor. I have read some posts regarding this problem but it doesn't gimme solutions. For the data pin, I'm using PB5 on my STM32F103 and I'm using Arduino_STM32 core official. I have tested it before, using Arduino Uno and Wemos D1 mini. When I was using those boards I didn't face any problems. Any suggestions?
This is my code:
This is my code:
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;
}