Jak generovat sin a cos vlny pomocí LECD PWM na STM32

Na základě našeho předchozího postu Jak generovat PWM output reprezentující sine wave na ESP32 (Arduino/PlatformIO) tento post používá dva různé IO piny pro generování sin i cos vlny dynamicky.

stm32_sine_cos.cpp
#include <Arduino.h>
#include <driver/ledc.h>

void setup() {
    Serial.begin(115200);

    ledcSetup(LEDC_CHANNEL_0, 10000 /* Hz */, 12);
    ledcSetup(LEDC_CHANNEL_1, 10000 /* Hz */, 12);

    ledcAttachPin(GPIO_NUM_32, LEDC_CHANNEL_0);
    ledcAttachPin(GPIO_NUM_25, LEDC_CHANNEL_1);
}

/**
 * @brief Calculate the PWM duty cycle (assuming 12 bits resolution) of a sine wave of
 * given frequency. micros() is used as a timebase
 *
 * @param frequency The frequency in Hz
 * @return int the corresponding 12-bit PWM value
 */
int sinePWMValue(float frequency, int maxPWMValue, float (*sinCos)(float)) {
  unsigned long currentMicros = micros(); // get the current time in microseconds

  // calculate the sine wave value for the current time
  int halfMax = maxPWMValue/2;
  int sineValue = halfMax + (halfMax-10) * sinCos(2 * PI * currentMicros / (1000000 / frequency));
  return sineValue;
}

void loop() {
    // Example of how to change the duty cycle to 25%
    ledcWrite(LEDC_CHANNEL_0, sinePWMValue(1.0, 4096, sinf));
    ledcWrite(LEDC_CHANNEL_1, sinePWMValue(1.0, 4096, cosf));
}

Výstup, filtrovaný 4. řádem Salley-Key filtrem každý (pomocí LM324) vypadá takto:

Osciloskop stopa filtrovaných sine a cosine PWM vln generovaných ESP32 LEDC


Podívejte se na podobné články podle kategorie: Analog Arduino Elektronika ESP8266/ESP32 PlatformIO