I'm trying to interface a SHT21 humidity sensor to a PIC (and learning C18 along the way, MPLAB, C18, PIC18LF44K22).
A 16 bit serial value, S_RH, is read from the sensor. To convert this value into relative humidity, RH, it needs to be inserted into an equation.
RH = (125 x S_RH)/ 2^16 - 6
The data sheet gives a test value of S_RH = 25424 giving RH = 42.5% which works nicely.
I want the result in a from that I can easily convert to hundreds/tens/units/tenths etc for outputing from the uC. To achieve this I want to multiply the above formula by 100 so the result represents tens/units/tenths/hundredths with the decimal point shifted right two places.
So the formula will become:
RH = (100 x 125 x S_RH)/2^16 - 600
Now for my problem.....
I'm having problems with what number types to use.
The maximum value for RH DURING the calulation should be;
100 x 125 x 65536 = 81987500 which is Ox30D3CF2CThis needs 32 bits so I define RH as unsigned long but it appears to overflow corrupting the result when I run the code in the simulator
volatile unsigned int S_RH; //raw serial rh value, 16 bits volatile unsigned long RH; //RH value, 32 bits
#pragma code // declare executable instructions void main (void) {
//load test serial data S_RH = 25424;
RH = 125*(S_RH); //65536;
.....}
Even with the calculation reduced to 125 x S_RH to limit the size of the result I can see that the result gets clipped with RH register containing 0x00007E10 after the above calculation. The correct value which would be 0X00307E10. So it appears the RH is being treated as a 16 bit variable.
Apologies for the long post, any advice gratefully received.
Thanks.