Just some food for thought. This is the code I use for reading the DS18S20.
Code:
ReadDS18S20:
owout sensor,1,[$CC, $44] ' Send Start Temperature Conversion command
owout sensor,1,[$CC, $BE] ' Send Read Temperature command
owin sensor,0,[STR dq\9] ' Retrieve all 9 bytes of data
RawTemp.Byte0 = dq[0]
RawTemp.byte1 = dq[1]
if RawTemp.8 = 1 then ' Check if temperature is a negative reading
SignC = Negative
RawTemp.lowbyte = RawTemp.lowbyte ^ 255 ' Invert data
else
SignC = Positive
endif
dummy = RawTemp.0 ' Store the half degree indicator bit
TempC = ((RawTemp.lowbyte) >> 1) * 100 ' Divide raw data by 2 to give real temperature
TempC = TempC + (dummy * 50) ' Add the half degree is present
if SignC = Negative then ' Only proceed if temperature is negative
if TempC => 1770 then
SignF = Negative
TempF = (TempC + 5000) * 900
TempF = div32 500
TempF = TempF - 12200
return
else
SignF = Positive
TempF = (TempC + 5000) * 900
TempF = div32 500
TempF = 12200 - TempF
return
endif
endif
SignF = Positive
TempF = TempC * 18 / 10 + 3200
return
This is the code I use for the DS18B20. This one also includes the CRC calculation.
Code:
ReadDS18B20:
low portb.7 : low portb.6 : low portb.5
pause 10
owout sensor,1,[$CC,$44]
low RailPullUp
pause 750
high RailPullUp
owout sensor,1,[$CC,$BE]
owin sensor,0,[STR dq\9]
rawtemp.Byte0 = dq[0]
rawtemp.Byte1 = dq[1]
gosub getcrc
if SensorError[sensor] = 1 and y < 3 then ReadDS18B20
gosub ConvertTemp
if SensorError[sensor] = 1 then
y = 0
TempC = 0
TempF = 3200
Signc = Positive
SignF = Positive
endif
high portb.7 : high portb.6 : high portb.5
return
ConvertTemp:
if NegBit = 1 then BelowZero
SignC = Positive
SignF = Positive
dummy = 625 * RawTemp
TempC = DIV32 100
dummy = 0
dummy = 1125 * Rawtemp
TempF = DIV32 100
TempF = TempF + 3200
return
BelowZero:
SignC = Negative
dummy = 0
RawTemp.byte0 = RawTemp.byte0 ^ 255
RawTemp.Byte1 = RawTemp.byte1 ^ 255
dummy = 625 * RawTemp + 1
TempC = DIV32 100
TempF = (TempC + 5000) * 900
TempF = DIV32 500
if RawTemp >= 285 then
TempF = TempF - 12199
SignF = Negative
else
TempF = 12199 - TempF
SignF = Positive
endif
return
'------------------------ Calculate the CRC from Byte 9 ------------------------
GetCRC:
for x = 0 to 7
DataByte = dq[x]
gosub CalcCRC
next x
if dq[8] <> CRCCalc then
SensorError[sensor] = 1
y = y + 1
else
SensorError[sensor] = 0
y = 0
endif
CRCCalc = 0
return
'--------------------- CRC Bit Calcuation Method -------------------------------
CalcCRC:
for i = 0 to 7
DataBit = CRCCalc.0 ^ DataByte.0
DataByte = DataByte >> 1
if DataBit = 0 then Shift
CRCCalc = CRCCalc ^ $18
Shift:
CRCCalc = CRCCalc >> 1
CRCCalc.7 = DataBit
next i
return
Bookmarks