如何将 LED 和压电与 arduino 上的按钮结合起来?
How can I combine an LED and a piezzo with a push button on arduino?
我想知道如何将我的 LED 和压电蜂鸣器组合在一个代码中。我想一按下按钮就停止播放音乐,同时打开一盏灯(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
}
你明白了!希望这对您有所帮助!
我想知道如何将我的 LED 和压电蜂鸣器组合在一个代码中。我想一按下按钮就停止播放音乐,同时打开一盏灯(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
}
你明白了!希望这对您有所帮助!