同时具有led的手动和自动功能

问题描述 投票:-1回答:1

所以我遇到了一个问题,当我进入循环之后,我就无法摆脱循环。因此我的项目有两个功能,一个用于手动,另一个用于自动运行,它将永远运行,但是我希望当我处于自动状态时,无法通过单击手机上的手动按钮退出该功能。我不知道这是否有意义,但我真的需要帮助,哈哈,谢谢。

//Program to control LED (ON/OFF) from ESP32 using Serial Bluetooth

#include <Arduino.h>
#include <BluetoothSerial.h> //Header File for Serial Bluetooth, will be added by default into Arduino

BluetoothSerial ESP_BT; //Object for Bluetooth

int incoming;
int yellow_led = 13;

void setup() {
  Serial.begin(9600); //Start Serial monitor in 9600
  ESP_BT.begin("ESP32_LED_Control"); //Name of your Bluetooth Signal
  Serial.println("Bluetooth Device is Ready to Pair");

  pinMode (yellow_led, OUTPUT);//Specify that LED pin is output
}



void automatic()
{
  while (incoming != 51)
  {
    digitalWrite(yellow_led, HIGH);
    ESP_BT.println("LED turned ON");

    delay(1000);

    digitalWrite(yellow_led, LOW);
    ESP_BT.println("LED turned OFF");

    delay(1000);
  }
}

void manual()
{
    if (incoming == 49)
    {
      digitalWrite(yellow_led, HIGH);
      ESP_BT.println("LED turned ON");    
    }
    else if(incoming == 48)
    {
      digitalWrite(yellow_led, LOW);
      ESP_BT.println("LED turned OFF");    
    }
}

void loop() {

  if (ESP_BT.available()) //Check if we receive anything from Bluetooth
  {
    incoming = ESP_BT.read(); //Read what we recevive 
    Serial.print("Received:"); Serial.println(incoming);

    if (incoming == 51) //#3
        {
          ESP_BT.println("In Manual Mode");
          manual();
        }

    else if (incoming == 52) //#4
        {
          ESP_BT.println("In Automatic Mode");
          automatic();
        }
  }
  delay(20);
}
arduino bluetooth project esp32
1个回答
0
投票

自动功能中的while循环是不必要的。您已经在loop()中无限循环,这样就足够了。尽管乍一看似乎会中断,但添加另一个循环却变成了无限循环。我稍后再讲。

因此您需要做的就是摆脱while循环,它应该可以工作。但是,只有在保证每次循环中都有一个incoming值(这在您的代码中看起来是这样)时,此方法才起作用。

[我在这里看到的另一个问题是,如果您输入manual(),并没有真正改变incoming的值,那么当您重用之前的值时,注定会有51,而没有所需的代码路径将被触发。同样也适用于authomatic(),因此我希望您能看到该循环如何变为无限。

因此,您还需要在以下几行中添加一些内容。

void manual()
{
    if (!ESP_BT.available())
        return;
    incoming = ESP_BT.read();
    if (incoming == 49)
    {
        digitalWrite(yellow_led, HIGH);
        ESP_BT.println("LED turned ON");    
    }
    else if(incoming == 48)
    {
        digitalWrite(yellow_led, LOW);
        ESP_BT.println("LED turned OFF");    
    }
}

最后,need help lol, please and thank you的描述性可能不足以让任何人来解决您的问题,请在下一次发布时仔细阅读how to ask a good question

© www.soinside.com 2019 - 2024. All rights reserved.