【问题标题】:Rounding numbers on AVRs in CC 中 AVR 上的舍入数字
【发布时间】:2013-04-16 08:45:41
【问题描述】:

我正在为 AVR(C 语言)编写代码,以连续改变三个 PWM 通道的占空比。为此,我编写了一个函数,它接收一个值作为百分比,并将某些寄存器设置为由百分比和定时器的 TOP 值确定的某些值。这个的伪代码--

register = (int) (duty / 100 * timer_top);

但是,除非 duty = 100,否则这是行不通的(没有 PWM 输出)。

我尝试在 math.h 中使用 round() 函数,但这也给出了类似的输出,并使编译的文件变得不必要地大。我尝试了其他方法,例如--

register = duty / 100 * timer_top
register = (duty / 100 * timer_top) + 0.5
register = (int) (duty / 100 * timer_top) + 0.5

但没有一个工作。有人可以帮我吗?谢谢!

【问题讨论】:

  • 只是确保:您的意思是 (duty/100)*timer_top 还是 (duty/timer_top)*100?
  • dutytimer_top的类型是什么?他们的价值观是什么?请记住,如果duty 是一个整数并且小于100,那么duty / 100 将为零。
  • 这显然不是你的实际代码,因为它不会编译......请在提问时尽量准确,我们越猜越难。

标签: c avr atmega


【解决方案1】:

如果duty 是一个整数,那么duty / 100 将是整数 商,即截断为整数,对于duty

register = duty * timer_top / 100;

如果你想做真正的浮点除法,你可以写成

register = (int) (duty / 100. * timer_top);

常量中的小数点使其成为双精度值。在这种情况下,您还可以使用您编写的其他替代方法来影响舍入行为。但是您也可以仅使用整数除法来获得不同的舍入行为,例如

register = (duty*timer_top + 50)/100;

这将四舍五入到最近而不是零,就像您的 + 0.5 在双值方法中一样。

【讨论】:

  • 将 0.5 添加到浮点数并将其转换为 uint 是天才,不是吗?用于舍入无符号。谢谢,MVG!
【解决方案2】:

试试这个:

Register = (long long)duty * timer_top / 100;

【讨论】:

    【解决方案3】:

    您可以仅使用整数数学来进行舍入函数的粗略版本。以下伪代码假定所有数字都是正数:

    intermediate = 100 * timer_top
    register = duty/intermediate;
    if (duty%intermediate>intermediate/2) {
        register++;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多