【问题标题】:How can I combine an LED and a piezzo with a push button on arduino?如何将 LED 和压电与 arduino 上的按钮结合起来?
【发布时间】:2015-11-25 23:04:58
【问题描述】:

我想知道如何在一个代码中组合我的 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 ?哪个板子?
  • if (long i = 0; i

标签: arduino led qpushbutton speaker


【解决方案1】:

您的代码无法正常工作的原因可能有多种。 对于初学者:您还没有定义 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  

}

你明白了!希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 2014-01-04
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多