Timer 如何使用步长在正弦表中查找音调频率?STM32

Timer 如何使用步长在正弦表中查找音调频率?STM32,timer,stm32,pwm,dac,Timer,Stm32,Pwm,Dac,我尝试使用正弦表查找方法来查找不同步长下的音调频率,但当我将浮点转换为整数并使用OSCIOPTE查看频率时,它无法在屏幕上显示任何内容 有人知道这个问题的解决方案吗。需要任何帮助 代码如下: // use the formula: StepSize = 360/(Fs/f) Where Fs is the Sample frequency 44.1 kHz and f is the tone frequency. // example: StepSize = 360/(44100/440) =

我尝试使用正弦表查找方法来查找不同步长下的音调频率,但当我将浮点转换为整数并使用OSCIOPTE查看频率时,它无法在屏幕上显示任何内容

有人知道这个问题的解决方案吗。需要任何帮助

代码如下:

// use the formula: StepSize = 360/(Fs/f) Where Fs is the Sample frequency 44.1 kHz and f is the tone frequency.
// example: StepSize = 360/(44100/440) = 3.576, since the STM32 doesn't support the floating point, therefore, we have to use the fixed-point format which multiply it by 1000 to be 3575

int StepSize = 3575;  
unsigned int v=0;

signed int sine_table[91] = {
          0x800,0x823,0x847,0x86b,
          0x88e,0x8b2,0x8d6,0x8f9,
          0x91d,0x940,0x963,0x986,
          0x9a9,0x9cc,0x9ef,0xa12,
          0xa34,0xa56,0xa78,0xa9a,
          0xabc,0xadd,0xaff,0xb20,
           0xb40,0xb61,0xb81,0xba1,
           0xbc1,0xbe0,0xc00,0xc1e,
           0xc3d,0xc5b,0xc79,0xc96,
           0xcb3,0xcd0,0xcec,0xd08,
            0xd24,0xd3f,0xd5a,0xd74,
            0xd8e,0xda8,0xdc1,0xdd9,
            0xdf1,0xe09,0xe20,0xe37,
            0xe4d,0xe63,0xe78,0xe8d,
            0xea1,0xeb5,0xec8,0xedb,
            0xeed,0xeff,0xf10,0xf20,
            0xf30,0xf40,0xf4e,0xf5d,
            0xf6a,0xf77,0xf84,0xf90,
            0xf9b,0xfa6,0xfb0,0xfba,
            0xfc3,0xfcb,0xfd3,0xfda,
            0xfe0,0xfe6,0xfec,0xff0,
            0xff4,0xff8,0xffb,0xffd,
            0xffe,0xfff,0xfff};

unsigned int sin(int x){
   x = x % 360;
   if(x <= 90)
      return sine_table[x];
    else if ( x <= 180){
      return sine_table[180 - x];
    }else if ( x <= 270){
      return 4096 - sine_table[x - 180];
    }else{
      return 4096 - sine_table[360 - x];
     }
}

void main(void)
{
while(1){
            v+=StepSize;                // Don't know why it doesn't work in this way. not display anything on screen.
           DAC->DHR12R2 = sin(v/1000);      // DAC channel-2 12-bit Right aligned data
           if (v >= 360) v = 0;
           }
}
但是,如果我改变步长=3;它显示频率:


您的代码存在一些问题。但我会从你问的那个开始

int StepSize = 3575;  
unsigned int v=0;
while(1){
       v+=StepSize;
       DAC->DHR12R2 = sin(v/1000);
       if (v >= 360) v = 0;
}
此代码不起作用的原因是,在循环结束时v始终设置为0,因为3575大于360。所以你总是叫sin3,因为3575/1000是3英寸

也许,您应该重写最后一行,就像v/1000>=360 v=0;一样;。否则,我会像这样重写你的循环

while(1){
       v+=StepSize;
       v/=1000;
       DAC->DHR12R2 = sin(v);
       if (v >= 360) v = 0;
}    
我还建议您将查找表声明为常量。所以看起来像

const signed int sine_table[91] = {
最后一个建议是为您的sin函数选择另一个名称,以免与。即使在这种情况下,也不应该有问题