我想知道如何将我的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
}
你明白了!希望这可以帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句