我想知道如何将LED和piezzo蜂鸣器组合在一个代码中。我想一按下按钮就停止音乐,同时打开一盏灯(LED)。我的代码不起作用,你能告诉我该怎么办吗?
int buttonState = 0;
int speakerPin = 10;
int buttonPin= 7;
int frequency = 500;
int ledPin = 13;
int length = 17; // the number of notes
char notes[] = "gcefgcefgcefgcefga "; // a space represents a rest
int beats[] = {2,2,1,1,2,2,1,1,2,2,1,1,2,2,1,1};
int tempo = 250;
void setup() {
pinMode(speakerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin,INPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState==HIGH){
digitalWrite(ledPin, HIGH);
noTone(speakerPin);
}else {
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
char notes[] = "gcefgcefgcefgcefga ";
digitalWrite(ledPin, LOW);
digitalWrite(speakerPin,HIGH);
if (long i = 0; i < duration * 5000L; i += tone * 15) {
}
void playTone(int tone, int duration) {
for (long i = 0; i < duration * 5000L; i += tone * 15) {
if (buttonState==LOW){
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
}
}
}
}}
您的代码不起作用的原因可能有几个。首先:你还没有定义noTone,我也没有看到playTone被实际使用,但在高级别上,你试图做的事情非常简单,这个伪代码应该会有所帮助:
void loop() {
buttonState = digitalRead(buttonPin);
if buttonState==LOW
playTone();
digitalWrite(ledPin, LOW);
else {break out of loop}
//add in your pause here
delayMicroseconds(pause);//I'm not sure why you put tone here in your code, just initialize int of 1000 or something
}
你明白了!希望这能有所帮助!