flt2int: CO2 sensor conversion
I've been evaluating the Sensirion SCD30 CO2 sensor lately. It's a handy little unit that senses CO2 concentration, local temperature, and relative humidity. My reason for doing this is to replace the COZIR 0-20% sensor that I've been working with, with something to operate in a less CO2-concentrated environment, suitable for monitoring CO2 in classrooms. This is being done in conjunction with mentoring a high-school student's senior project.
The results I was getting from this sensor were initially very puzzling -- until I read further in the datasheet. The results are in 32-bit floating point! Who does that? Anyway, I invoked the machinery of the Float32 module, and the results made more sense.
But why bring a WMD like Float32 to a knife fight when all you need to do is round floating-point numbers to integer form? So I endeavored to do the conversion in a short Spin routine:
PRI flt2int(flt, scale) | sign, exp if (flt == 0.0) return 0 sign := flt >> 31 exp := flt >> 23 & $ff - 149 result := (((flt & $7fffff | $800000) * scale) + 1) >> 1 if (exp < 0) result >>= -exp elseif (exp > 0) result <<= exp if (sign) -result
It does rounding, and it works for my application. The scale argument is there so I can read temperature in tenths of a degree, rather than being rounded to the nearest degree. I just set scale to 10.
I neglected to deal with the NaN stuff, since it doesn't come in to play here. Besides, what's NaN in integer form? $8000_0000?