如何在 STM32 上使用 LECD PWM 生成 sin 和 cos 波
基于我们之前的文章如何在 ESP32 上生成表示正弦波的 PWM 输出 (Arduino/PlatformIO),本文使用两个不同的 IO 引脚动态生成正弦和余弦波。
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 计算给定频率正弦波的 PWM 占空比(假设 12 位分辨率)
* 给定频率。micros() 用作时基
*
* @param frequency 频率,单位 Hz
* @return int 对应的 12 位 PWM 值
*/
int sinePWMValue(float frequency, int maxPWMValue, float (*sinCos)(float)) {
unsigned long currentMicros = micros(); // get the current time in microseconds
// 计算当前时间的正弦波值
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));
}输出由各自的 4 阶 Sallen-Key 滤波器(使用 LM324)滤波后如下:

Check out similar posts by category:
Analog, Arduino, Electronics, ESP8266/ESP32, PlatformIO
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow