signal-processingstm32dacsine-wave

How to generate mixed frequency sinewave using STM32F4 DAC?


I am using STM32F4 Discovery board. I have generated a 10Hz sine wave using DAC Channel1.

As per STM's Application note, the sine wave generation should be done as follows:

enter image description here

And it can be used to produce desired frequency using following formula:

enter image description here

This is my simple function which populates 100 Samples. Since I used fTimerTRGO = 1kHz, fSinewave is correctly coming as 1k/100 = 10Hz

Appl_getSineVal();
HAL_DAC_Start_DMA(&hdac, DAC_CHANNEL_1, (uint32_t*)Appl_u16SineValue, 100, DAC_ALIGN_12B_R);
.
.
.
.
void Appl_getSineVal(void)
{
    for (uint8_t i=0; i<100; i+=1){
        Appl_u16SineValue[i] = ((sin(i*2*PI/100) + 1)*(4096/2));
    }
}

Now I want to super impose another sine wave of frequency 5Hz in addition to this on the same channel to get a mixed frequency signal. I need help how to solve this.

I tried by populating Appl_u16SineValue[] array with different sine values, but those attempts doesnot worth mentioning here.


Solution

  • In order to combine two sine waves, just add them:

    sin(...) + sin(...)
    

    Since the sum is in the range [-2...2] (instead of [-1...1]), it needs to be scaled. Otherwise it would exceed the DAC range:

    0.5 * sin(...) + 0.5 * sin(...)
    

    Now it can be adapted to the DAC integer range as before:

    (0.5 * sin(...) + 0.5 * sin(...) + 1) * (4096 / 2)
    

    Instead of the gain 0.5 and 0.5, it's also possible to choose other gains, e.g. 0.3 and 0.7. They just need to add up to 1.0.

    Update

    For your specific case with a 10Hz and a 5Hz sine wave, the code would look like so:

    for (uint8_t i=0; i < 200; i++) {
        mixed[i] = (0.5 * sin(i * 2*PI / 100) + 0.5 * sin(i * 2*PI / 200) + 1) * (4096 / 2);
    }