我正在尝试使用 PWM 调制提供正弦波。我的电路由以下部分组成:
- 阿杜诺
- H 桥 - 控制方向(引脚 4,5)和 PWM 电压(PWM 引脚 6)
- 电磁马达 - 正弦输出应馈送到马达
我在网上看到了一些指南,但其中大多数都使用了我不太理解的 Sinewave 表和低级代码,所以我决定尝试使用一些更简单的代码,如下所示:
const int DIR1_PIN = 4;
const int DIR2_PIN = 5;
const int PWM_PIN = 6;
const int LED_PIN = 9;
const int numSamples = 20;
const int sampleFreq = 2000;
const float pi = 3.1415;
float f = 1; // signal frequency
float T = 1/f;
float dt = T/numSamples;
int sineSignal[numSamples]; // sine values would be added here
int dir1Array[numSamples]; // 11....100....0 indicates direction
int dir2Array[numSamples]; // 00....011....1 indicates other direction
void setup()
{
pinMode(LED_PIN, OUTPUT); // the led is just an indicator to what the output is
pinMode(DIR1_PIN, OUTPUT);
pinMode(DIR2_PIN, OUTPUT);
pinMode(PWM_PIN, OUTPUT);
for (int n = 0; n < numSamples; n++)
{
sineSignal[n] = abs((int) (255 * (sin(2 * pi * f * n * dt))));
if (n < numSamples / 2)
{
dir1Array[n] = HIGH;
dir2Array[n] = LOW;
}
else
{
dir1Array[n] = LOW;
dir2Array[n] = HIGH;
}
}
}
void loop()
{
for (int n = 0; n < numSamples; n++)
{
analogWrite(LED_PIN, sineSignal[n]);
analogWrite(PWM_PIN, sineSignal[n]);
digitalWrite(DIR1_PIN, dir1Array[n]);
digitalWrite(DIR2_PIN, dir2Array[n]);
delay(sampleFreq); // not quite sure how the delay affects the frequency f
}
}
长话短说,这段代码不允许我控制频率f
(为不同的值获得相同的输出f
)
关于如何为变量生成这样的输出的任何想法f
?一个人应该如何建立一个delay
电话,如果甚至?
谢谢!