# Simple math for conversions

Hello, I was trying to get the imp to do some math to convert a millivolt reading to a temperature and had some issues doing it. This is what I was trying to do to get it to work but had to do it this way to get it to work. And I could be doing it wrong to begin with but it seems to be working for now.

Non working code
`
local temps;
local val1;
local val2;
local val3

{

//server.show(hardware.voltage())

server.show(temps);

val1 = temps * .00005;
val2 = 100 * val1 - 50;
val3 = val2 * 1.8 + 32;
server.show(val3);
}
`

Here is what did work and I am not sure why
`
local a;
local b = 0.00005;
local c = 0.0;
local d;

{

server.show(temps);
a = temps * b;
c = 100 * a;
//d = c * 1.8 + 32; // not too sure what happened here but it make the temp all wrong for some reason. This was to //convert from C to F.
}
`
The device that I am using give a voltage that is equal to 10 mv per degree C. And on other thing it will only go to around 15 degrees C.

You need to have the leading zero in your “.00005”, ie it should be “0.00005”. If not, the parser barfs on it - that’s likey your issue.

You’ve not said what temperature it is when your sensor outputs 0.0v, which makes this a bit hard, but:

hardware.pin1.read() will be returning a value 0-65535, which is the ADC read value. This is a proportion (in 1/65535’ths) of the ADC reference voltage, which happens to be the chip supply voltage. This can be read with hardware.voltage().

So, the voltage on pin1 is:

local voltage = (hardware.pin1.read() / 65535) * hardware.voltage();

…in volts. If, say, it’s 0.0v for -40C, then:

local celsius = (voltage / 0.010) - 40;

Thanks Hugo. That is a much easier way to do what I was trying to do. At .750 volts the tempature is supposed to be 25 C. I am going to use your example and see how it works for me. Again thank you.

Ah, I just spotted a bug. Probably should be “65535.0” to ensure the division is a floating point one!

That is what I figured had to happen if you need to use floating points I just made the local variables 0.0 etc.

One further problem in your original listing is that readtemp() calls imp.wakeup() twice. That means that every time it’s called, two further callbacks will be scheduled, both for the same moment. Then when they run, they’ll schedule two each, and so on. Pretty soon the imp will be drowning in readtemp() calls…

Peter

Peter short of using flags is there any way of knowing if a timer is running to avoid this type of over scheduling problem?

Not at present, no. We should enforce a limit really, quite a large one of course, just to detect these sort of “fork bomb” problems.

Peter