我需要创建一个Arduino波形发生器,但我真的无法让它正常工作。
发电机必须输出正弦波、方波、三角波和锯齿波,我让方波正常工作,我尝试了很多方法,但无法让其他方法正常工作。
这是我的电路:
这是我使用的代码
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;
}
}
虽然不完美,但已经足够好了哈哈。