我需要创建一个Arduino Wave Generator,但我真的无法让它正常工作。
发生器必须输出正弦波,方波,三角波和锯齿波,我得到正方形波,我尝试了很多东西,但不能让其他人正常工作。
这是我的电路:
这是我正在使用的代码
int led1 = 3;
int led2 = 4;
int led3 = 5;
int led4 = 6;
int display = 13;
int inBtn = 8;
int btnSt = 0;
int btnLastSt = 0;
int cont = 0;
void setup() {
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(display, OUTPUT);
pinMode(inBtn, INPUT);
}
void loop() {
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
switch(cont){
case 0:
digitalWrite(led1, HIGH);
digitalWrite(display, HIGH);
delay(250);
digitalWrite(display, LOW);
delay(250);
break;
case 1:
digitalWrite(led2, HIGH);
break;
case 2:
digitalWrite(led3, HIGH);
break;
case 3:
digitalWrite(led4, HIGH);
break;
}
if (digitalRead(inBtn) == LOW) {
cont++;
delay(150);
}
if (cont == 4) cont = 0;
if (btnLastSt != cont){
btnLastSt = cont;
}
}
其他波浪会进入其他“案例”。 我很抱歉缺乏信息和研究,但在这一点上我非常绝望(这是一项任务)。
如果有人可以帮我一点,那就太好了。
更新
int led1 = 3;
int led2 = 4;
int led3 = 5;
int led4 = 6;
int display = 11;
int inBtn = 8;
int btnSt = 0;
int btnLastSt = 0;
int cont = 0;
void setup() {
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(display, OUTPUT);
pinMode(inBtn, INPUT);
}
void loop() {
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
switch(cont){
case 0:
//Square
digitalWrite(led1, HIGH);
digitalWrite(display, HIGH);
delay(200);
digitalWrite(display, LOW);
delay(200);
break;
case 1:
//Sawtooth
digitalWrite(led2, HIGH);
for(int i = 0; i < 255; i++){
analogWrite(display, i);
delay(1);
}
analogWrite(display, 0);
delay(1);
break;
case 2:
//Triangular
digitalWrite(led3, HIGH);
for (int i = 0; i < 254; i++){
analogWrite(display, i);
delay(1);
}
for (int i2 = 254; i2 > 0; i2--){
analogWrite(display, i2);
delay(1);
}
break;
case 3:
//Sine
digitalWrite(led4, HIGH);
analogWrite(display, 10); delay(10);
analogWrite(display, 19); delay(10);
analogWrite(display, 45); delay(10);
analogWrite(display, 84); delay(10);
analogWrite(display, 130); delay(10);
analogWrite(display, 176); delay(10);
analogWrite(display, 215); delay(10);
analogWrite(display, 241); delay(10);
analogWrite(display, 250); delay(10);
analogWrite(display, 241); delay(10);
analogWrite(display, 215); delay(10);
analogWrite(display, 176); delay(10);
analogWrite(display, 130); delay(10);
analogWrite(display, 84); delay(10);
analogWrite(display, 45); delay(10);
analogWrite(display, 19); delay(10);
break;
}
if (digitalRead(inBtn) == LOW) {
cont++;
delay(100);
}
if (cont == 4) cont = 0;
if (btnLastSt != cont){
btnLastSt = cont;
}
}
这不是完美的,但它足够好哈哈。
答案 0 :(得分:4)
您的硬件设置不足以达到您想要达到的效果。
您需要模拟输出,但使用的是数字输出。您必须添加DAC(数模转换器)(MAX98357A example)或使用PWM(脉冲宽度调制)输出(引脚3,5,6,9-11)。这两个都需要输出上额外的LPF(低通滤波器)。
对于PWM,您可以设置输出pinMode(pin, OUTPUT)
,然后可以使用analogWrite(pin, value)
,其值为0 - 255。