我正在尝试用 2 个正弦波创建调制波形。为此,我需要模(fmodf)来知道具有特定频率(lo_frequency)的正弦在那个时间(t)的幅度。但是当执行以下行时,我遇到了一个硬故障:
j = fmodf(2 * PI * lo_frequency * t, 2 * PI);
你知道为什么这给了我一个硬故障吗?
编辑1:
我用 my_fmodf 交换了 fmodf:
float my_fmodf(float x, float y){
if(y == 0){
return 0;
}
float n = x / y;
return x - n * y;
}
但是仍然发生硬故障,当我调试它时,它甚至没有跳转到这个函数(my_fmodf)。
这是发生此错误的整个函数:
int* create_wave(int* message){
/* Mixes the message signal at 10kHz and the carrier at 40kHz.
* When a bit of the message is 0 the amplitude is lowered to 10%.
* When a bit of the message is 1 the amplitude is 100%.
* The output of the STM32 can't be negative, thats why the wave swings between
* 0 and 256 (8bit precision for faster DAC)
*/
static int rf_frequency = 10000;
static int lo_frequency = 40000;
static int sample_rate = 100000;
int output[sample_rate];
int index, mix;
float j, t;
for(int i = 0; i <= sample_rate; i++){
t = i * 0.00000001f; // i * 10^-8
j = my_fmodf(2 * PI * lo_frequency * t, 2 * PI);
if (j < 0){
j += (float) 2 * PI;
}
index = floor((16.0f / (lo_frequency/rf_frequency * 0.0001f)) * t);
if (index < 16) {
if (!message[index]) {
mix = 115 + sin1(j) * 0.1f;
} else {
mix = sin1(j);
}
} else {
break;
}
output[i] = mix;
}
return output;
}
编辑2:
我修复了警告:函数以“chux - Reinstate Monica”建议的方式返回局部变量 [-Wreturn-local-addr] 的地址。
int* create_wave(int* message){
static uint16_t rf_frequency = 10000;
static uint32_t lo_frequency = 40000;
static uint32_t sample_rate = 100000;
int *output = malloc(sizeof *output * sample_rate);
uint8_t index, mix;
float j, n, t;
for(int i = 0; i < sample_rate; i++){
t = i * 0.00000001f; // i * 10^-8
j = fmodf(2 * PI * lo_frequency * t, 2 * PI);
if (j < 0){
j += 2 * PI;
}
index = floor((16.0f / (lo_frequency/rf_frequency * 0.0001f)) * t);
if (index < 16) {
if (!message[index]) {
mix = (uint8_t) floor(115 + sin1(j) * 0.1f);
} else {
mix = sin1(j);
}
} else {
break;
}
output[i] = mix;
}
return output;
}
但现在我在这条线上遇到了硬故障:
output[i] = mix;
编辑 3:
因为之前的代码包含一个非常大的缓冲区阵列,不适合 STM32F303K8 的 16KB SRAM,我需要对其进行更改。
现在我使用一个“乒乓”缓冲区,其中我使用 DMA 的回调进行“前半传输”和“完全传输”:
void HAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef * hdac){
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_3, GPIO_PIN_SET);
for(uint16_t i = 0; i < 128; i++){
new_value = sin_table[(i * 8) % 256];
if (message[message_index] == 0x0){
dac_buf[i] = new_value * 0.1f + 115;
} else {
dac_buf[i] = new_value;
}
}
}
void HAL_DAC_ConvCpltCallbackCh1 (DAC_HandleTypeDef * hdac){
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_3, GPIO_PIN_RESET);
for(uint16_t i = 128; i < 256; i++){
new_value = sin_table[(i * 8) % 256];
if (message[message_index] == 0x0){
dac_buf[i] = new_value * 0.1f + 115;
} else {
dac_buf[i] = new_value;
}
}
message_index++;
if (message_index >= 16) {
message_index = 0;
// HAL_DAC_Stop_DMA (&hdac1, DAC_CHANNEL_1);
}
}
但是创建的正弦频率太低了。我的上限在 20kHz 左右,但我需要 40kHz。我已经将时钟增加了 8 倍,以使时钟达到最大值:
. 我仍然可以减少计数器周期(目前是 50),但是当我这样做时,中断回调似乎需要比下一个周期更长的时间。至少看起来如此,因为当我这样做时输出变得非常失真。
我还尝试通过只取每 8 个正弦值来降低精度,但我不能再这样做了,因为这样输出看起来不再像正弦波了。
有什么想法可以优化回调以减少时间吗?还有其他想法吗?