I have successfully used the code below with an 18F2321.
It should work the same with a 16F part.
I found it somewhere here on the forum, and it works great.
Code:
'------------------ Read SHT71 Temperature / Humidity Sensor -------------------
ReadSHT71:
SHTCommand = ReadTemp
gosub Initialize
GOSUB TransmissionStart
GOSUB IssueCMD
gosub ConvertToCelsius
SHTCommand = ReadHumidity
gosub Initialize
GOSUB TransmissionStart
GOSUB IssueCmd
gosub ConvertToRH
TEMPC = (TempC/100) - 2
TempC.7 = SignC
RHTempComp = RHTempComp/100
RETURN
'--------------------- Calculate Relative Humidity -----------------------------
ConvertToRH:
' 12 Bit RHLinear = -4 + 0.0405 * DataOutput -0.0000028 * DataOutput^2
w = 405 * RawData
w = div32 100
x = RawData * RawData
x = div32 1000
x = x * 28
x = div32 100
RHLinear = w - x - 400
'---------- Calculate Relative Humidity with Temperature Compensation ----------
w = (8 * RawData + 1000) / 10
IF SignC = 0 THEN ' "+"
if tempC > 2500 then
x = (tempC - 2500) * w
x = div32 100
RHTempComp = RHLinear + x / 100
else
x = (2500 - tempc) * w
x = div32 100
RHTempComp = RHLinear - x / 100
endif
else
x = (2500 + tempC) * w
x = div32 10000
RHTempComp = RHLinear - x
endif
return
'---------------------------- Initialize the Sensor ----------------------------
Initialize:
high DataPin ; Start condition
low clk
for i = 1 to 10
high clk
pause 1
low clk
pause 1
next i ; Leaves clock low
return
'---------------------------- Get Data from Sensor -----------------------------
IssueCmd:
Pause 2
low Clk
shiftout DataPin,clk,1,[SHTCommand\8] ' Send command byte
input DataPin
WaitForAck:
x = 0
WaitForAck2:
IF DataPin = 1 THEN
x = x + 1
if x = 0 then goto NoAck
Pauseus 2
GotoWaitForAck2
ENDIF
High Clk
pause 10 ' Issue ACK from PIC
low clk
pause 10 ' Make certain we don't move forward on a glitch
WHILE DataPin:WEND
shiftin DataPin,clk,0,[RawData.byte1\8] ' Get the first byte, 8 bits
low DataPin
HIGH Clk
PAUSE 10
LOW Clk
pulsout clk,10 ' Send NACK
shiftin DataPin,clk,0,[RawData.byte0\8] ' Get the second byte, 8 bits
low DataPin
pulsout clk,10 ' Send acknowledge
shiftin DataPin,clk,0,[crc\8] ' Get third byte, 8 bits, CRC
high DataPin
pulsout clk,10 ' Send acknowledge
input DataPin ' End of Transmission
input clk
ERR = 0
return
NoAck:
ERR = 1
RETURN
'---------------------------- Start Transfer -----------------------------------
TransmissionStart:
HIGH DataPin ; Make sure it is high
Pause 1
high clk
pause 1
low DataPin
pause 1
low clk
pause 1
high clk
pause 1
high DataPin
pause 1
low clk
return
'----------------------------- Raw Data to Degrees C ---------------------------
ConvertToCelsius:
' 14 Bit Temperature = -40.00 + 0.01 * DataOutout
if RawData => 4000 then
tempC = RawData - 4000
SignC = 0
else
tempC = 4000 - RawData ; Negative Temps
SignC = 1
endif
return
Bookmarks