0

我正在使用 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,temp:22.4

在另一个 ATMEGA2560 上,我得到的是:

temp_buf:53,temp_volt:-861,temp:0.00

正因为如此,我做了这个调整

temp_volt =(((unsigned long)temp_buf*256*100)/1023) - 904;

当我使用相同的代码时,为什么两个微控制器的行为不同?

4

1 回答 1

0

temp_volt 和 temp_buf 具有 double 类型,这样您就不会因为整数运算而丢失数据,例如 7/4 = 1 和 7.0/4.0 = 1.75 所以,

double temp_volt;
double temp_buf;

和你的计算:

temp_volt =temp_buf*256.0*10.0)/1023.0) - 993.0;   //  subtract offset gain    
temp = ((float)temp_volt*1000.0/1014.0*100.0/196.0)/10.0;       //  adjust the gain 

如果您需要 int 形式的结果,请在最后一步执行此操作,例如

 temp_volt =(double)(int)(temp_buf*256.0*10.0)/1023.0) - 993.0);
于 2014-10-10T06:57:20.463 回答