【问题标题】:floating point to scaled int conversion浮点到缩放的 int 转换
【发布时间】:2016-11-14 16:27:36
【问题描述】:

下面有一个函数使用浮点数D1D2。它们是方程中的变量。

我不想在我开发的嵌入式平台上使用内存受限的浮点数(浮点库很大)。我只想使用ints。因此该函数将返回一个int 并在计算中使用ints。

例如,该函数将返回 229500 度而不是 22.95 度。

有人知道我如何计算D1D2 应该变成什么值吗?

函数返回值的取值范围是-40到120度。

int 的大小为 4 个字节。

float readTemperatureC()
{
  int val;                // Raw value returned from sensor
  float temperature;      // Temperature derived from raw value

  // Conversion coefficients from SHT15 datasheet
  const float D1 = -40.0;  // for 14 Bit @ 5V
  const float D2 =   0.01; // for 14 Bit DEGC

  // Fetch raw value
  val = readTemperatureRaw();

  // Convert raw value to degrees Celsius
  temperature = (_val * D2) + D1;

  return (temperature);
}

这是我要转换为仅使用整数的函数。 int readTemperatureC() { 整数值; // 从传感器返回的原始值 国际温度; // 原始值得出的温度

  // Conversion coefficients from SHT15 datasheet
  const int D1 = ?;  // for 14 Bit @ 5V
  const int D2 = ?; // for 14 Bit DEGC

  // Fetch raw value
  val = readTemperatureRaw();

  // Convert raw value to degrees Celsius
  temperature = (val * D2) + D1;

  return (temperature);
}

【问题讨论】:

  • 函数readTemperatureRaw返回的值范围是多少,你的平台上sizeof int是多少?
  • 或许long D1 = -40*10000L; int D2 = 100; return (_val * D2) + D1;?
  • 我们需要 RAW 值的范围(不是计算温度的范围)。
  • 你还没有提到是什么阻止你做_val / 100 - 40
  • @barakmanos True - 删除评论(我专注于这个comment

标签: c int floating


【解决方案1】:

函数将返回 229500 度而不是 22.95 度。

将系数乘以 10,000 并使用整数运算。

// Conversion coefficients from SHT15 datasheet
// const float D1 = -40.0;  // for 14 Bit @ 5V
// const float D2 =   0.01; // for 14 Bit DEGC
const int D1 = (int) (-40.0*10000);
const int D2 = (int) (0.01*10000);
...
temperature = (_val * D2) + D1;

注意:OP 状态为 4 字节 int


在查看data sheet后,我怀疑-40.00.01的FP值是否正确

OP 有commented 正确的data sheet。来自第 4.3 节温度

表 8
d1(VDD = 5 伏)= -40.1°C
d2 = 0.01°C

T = d1 + d2 * SOT

#define d1 (-40.1 /* degrees C */)
#define d2 (0.01 /* degrees C/d2a */)

#define T_SCALE 10000
#define T_OFFSET ((int)(d1 * SCALE))
#define T_SLOPE  ((int)(d2 * SCALE))

// Sensor output - temperature
// 0 to 0x3FFF (14-bit)
int SOT = readTemperatureRaw();

// temeprature in 1/10,000 degree C
int temperature = (SOT * T_SLOPE) + T_OFFSET;

// With 32-bit `int`, no range issue
// -401000 <= temperature <= 1237300

【讨论】:

  • 你是如何猜到 OP 使用的是哪个硬件?
  • 好的,我错过了。我们可以删除这些 cmets。我会删除我的
  • 大家好,感谢您的帮助。传感器实际上是 adafruit 的 sht10。有一个可用于传感器的库,我从 [github.com/practicalarduino/SHT1x/blob/master/SHT1x.cpp] 获取值。
猜你喜欢
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 2012-11-04
  • 2014-09-03
  • 2021-01-02
  • 2015-05-23
  • 2011-03-24
相关资源
最近更新 更多