DS18S20 Temperature Sensor

I know there are lots of sample programs for the DS18S20 device, but most of them produce values that can only be displayed and not actually a full temperature (including the 0.5 remainder) that can be compared etc... The Positron8 PIC BASIC Compiler's program below also handles negative temperatures readily.

The program is fully compatible with standard 14-bit core devices, enhanced 14-bit core devices, 18F devices and PIC24 and dsPIC devices.

Hopefully it is useful to some users in this winter time.

' Read a DS18S20 1-wire temperature sensor and display the temperature on the serial terminal

'

' Circuit diagram

'

' VCC 3.3 Volts or 5 Volts

' ------------o----

' | |

' | .-.

' | | |

' | | | 4.7K

' | '-'

' ____ | |

' / VCC|-- |

' | DQ |-----o--> To PORTB.0

' \ GND|--

' ---- |

' DS18S20 |

' --- Gnd

'

Device = 16F18857 ' Choose an enhanced 14-bit core device

Declare Xtal = 16 ' Operating with a 16MHz external crystal

Declare Float_Display_Type = Fast ' Set for a faster, more accurate, float to ASCII conversion

'

' Setup USART1

'

Declare Hserial_Baud = 9600 ' Set the Baud rate. The compiler will set up everything else associated with USART1

Declare Hserout_Pin PORTC.6 ' Choose the pin for TX. So the compiler can sort out PPS

Declare Hserin_Pin PORTC.7 ' Choose the pin for RX. So the compiler can sort out PPS

'

' Allocate variables

'

Dim wRaw_Temperature As SWord ' Holds the raw temperature value from the DS18S20

Dim fTemperature As Float ' Holds the final temperature


Symbol DQ = PORTB.0 ' One-wire data pin


'-------------------------------------------------------------------------------------

' The main program starts here

'

Main:

Do ' Create a loop

Get_Temperature() ' Get the temperature from the chip

HRSOutLn Dec1 fTemperature, " Degrees C" ' Transmit the temperature serially

Loop ' Do it forever


'-------------------------------------------------------------------------------------

' Read the DS18S20 chip

' Input : None

' Output : fTemperature holds the temperature value

' Notes : None

'

Proc Get_Temperature()

OWrite DQ, 1, [$CC, $44] ' Start a temperature conversion

While ORead DQ, 4 = 0 ' \

DelayMS 10 ' | Check if the DS18S20 is still busy converting

Wend ' /

OWrite DQ, 1, [$CC, $BE] ' Setup to read the temperature

ORead DQ, 0, [wRaw_Temperature.Byte0, wRaw_Temperature.Byte1] ' Read the temperature



fTemperature = wRaw_Temperature / 2.0 ' Convert the temperature to a float

If fTemperature < 0 Then ' Is the temperature below 0?

fTemperature = fTemperature + 0.5 ' Yes. So adjust the value returned

EndIf

EndProc