我怎样才能解决这个问题。 “__builtin_avr_delay_cycles 需要一个编译时整数常量”

How can I fix this. "__builtin_avr_delay_cycles expects a compile time integer constant"

我正在使用 伺服电机atmega32A MCU。我想通过将度数发送给函数来转动电机。这是我的主要方法。

#ifndef F_CPU
#define F_CPU 8000000UL 
#endif

#include <avr/io.h>
#include <util/delay.h>
#include "servo.h"

int main(void)
{
    DDRC = 0b00000001; 
    PORTC = 0x00;

    while(1)
    {
        turnTo(90);
    }
}

这是我的伺服电机代码。

#ifndef F_CPU
#define F_CPU 8000000UL // 8 MHz clock speed
#endif

#include <avr/io.h>
#include <util/delay.h>

int turnTo(double degree){
    int pulse=(degree*500/90)+1000;
    PORTC = 0x01;

    _delay_us(pulse);

    PORTC = 0x00;
    
    return 0;
}

我尝试了以下答案。但是什么都没有用。我该如何解决这个问题?

延迟函数在编译时计算 no operation 循环,不能在控制器上动态计算。所以尝试添加这样的功能:

void wait(unsigned int us)
{
  for(unsigned int i=0; i < us; i++)
  {
    _delay_us(1);
  }
}

并调整你的程序


int turnTo(double degree){
    unsigned int pulse=(degree*500/90)+1000;
    PORTC = 0x01;

    wait(pulse)

    PORTC = 0x00;
    
    return 0;
}

It is not exactly cause the for loop also takes some assembler instructions. At the moment i have got no compiler to check but you can correct the result by counting the assembler instructions that the compiler uses and adapt us variable. A better solution is to use timer instead of delay. They have got a better accuracy as delay and the controller can do other things during counting!