Help with shift instruction
mynet43
Posts: 644
I have a routine that converts a thermistor reading from resistance to temperature.
I tried to be clever by using shift instructions instead of divide and multiply by powers of two.
Somehow the two versions don't give the same answer. Can you help me figure out what is different? The divide/multiply version gives the right answer...
Thank you for your help.
Jim
I tried to be clever by using shift instructions instead of divide and multiply by powers of two.
Somehow the two versions don't give the same answer. Can you help me figure out what is different? The divide/multiply version gives the right answer...
PRI thermistor_temp | i, resistance, adc_val, denom ' interpolate to get temperature (C) from thermistor adc_val := adc.average(thermo_adc,4) ' ADC of voltage of thermistor denom := 4096-adc_val resistance := (10000*adc_val+denom>>1)/denom ' calculate thermistor resistance from adc_val (rounded) temperature := 25 ' init to 25 in case out of bounds repeat i from 0 to constant(max_th_table/5+10) ' get table entry range of resistance if resistance =< rt[i] and resistance => rt[i+1] temperature := tt[i] + ((((resistance - rt[i])*(tt[i+1]-tt[i])+(rt[i+1]-rt[i])>>1))<<10)/(((rt[i+1]-rt[i]))>>10) ' BAD CODE temperature := tt[i] + ((((resistance - rt[i])*(tt[i+1]-tt[i])+(rt[i+1]-rt[i])/2))*1024)/((rt[i+1]-rt[i]))/1024 ' GOOD CODE quit
Thank you for your help.
Jim
Comments
In the bad code you are calculating "rt)*(tt[i+1]-tt)+(rt[i+1]-rt)/2))*1024)" and dividing that by "(((rt[i+1]-rt))>>10)".
You are absolutely right. However, I believe I tried it without the extra bracket and got the same bad result.
It looks like I should include the whole thing in parentheses before I do the shift.
Does that sound right?
I'll try it.
Thanks!
Jim
Thanks again.
Jim