我使用atmega2560从温度传感器tmp36读取温度。在读取两个atmega2560微控制器的温度传感器数字值并将其转换为可读形式后,我得到了不同的答案。为什么我会得到这种类型的答案。 ? 一段代码如下存在:浮点运算异常
float temp; // global variable
{
unsigned long temp_volt;
unsigned char temp_h, temp_l;
unsigned int temp_buf;
temp_l=ADCL;
temp_h=ADCH;
temp_buf=((int)temp_h<<8)|temp_l;
temp_volt =(((unsigned long)temp_buf*256*10)/1023) - 993; // subtract offset gain
temp = ((float)temp_volt*1000/1014*100/196)/10; // adjust the gain
printf("temp_buf: %d, temp_volt: %d, temp: %0.2f\r\n", temp_buf, temp_volt, temp);
}
在一个ATMEGA2560答案我得到的是:
temp_buf:55,temp_volt:447,温度:22.4
在另一ATMEGA2560什么,我得到的是:
temp_buf:53,temp_volt:-861,温度:0.00
正因为如此我做了这个调整
temp_volt =(((unsigned long)temp_buf*256*100)/1023) - 904;
为什么两个微控制器在我是同一个代码时表现不同?
我会说代码是由于某种原因不同。下载它和差异。但第二次评估似乎应该使用浮点常量* 1000.0/1014.0 * 100.0/196.0 *。还怎么声明* temp_buf,temp_volt *,他们是* unsigned int *?理想情况下运行调试器并在运行时检查。否则,检查编译的asm代码,旧的gcc 4.3.2有时是越野车。 – TMa 2014-10-10 06:40:42