0

我已使用 MOSFET 晶体管将 ESP32 板连接到 12V LED,并使用 touchPin 进行操作。这个想法是有两个相同的板,当我打开一个板上的灯时,它也应该使用 Wifi 在另一个板上点亮(因为板不会位于相同的物理位置,而是连接到不同的网络)。

就其本身而言,它们确实像魅力一样工作,但是一旦我想通过 GET 请求检索其他板的晶体管状态,它就无法按预期工作,这意味着晶体管状态不会传递给其他板,因此不会影响 LED . 我怀疑错误可能在我的 void setup() 见下文

void setup() {
  Serial.begin(1155200);
  delay(1000);
  // Initialise the LED Pin as an output
  pinMode(transistor, OUTPUT);

  // Send a GET request to <IP>/led/<number>/state/<0 or 1>
  server.on("^\\/led\\/([0-9]+)\\/state\\/([0-9]+)$", HTTP_GET, [] (AsyncWebServerRequest *request) {
    String ledNumber = request->pathArg(0); // currently unused - we use only a predefined LED number
    String state = request->pathArg(1);

    request->send(200, "text/plain", "LED: " + ledNumber + ", with state: " + state);
  });

或者在 void loop() 中的 for 循环中如下所示:

void loop() {
  while (1) {
    
  touchValue = touchRead(touchPin);

  //Serial.print(touchValue);

  if (millis() - lastTimeButtonStateChanged > debounceDuration) {
  // check if the touchValue is below the threshold
  // if it is, set ledPin to HIGH

    buttonState = (touchValue < threshold) ? HIGH: LOW;

    if (buttonState != lastButtonState) {
      lastTimeButtonStateChanged = millis();
      lastButtonState = buttonState;
      if (buttonState == LOW) {
        transistorState = (transistorState == HIGH) ? LOW: HIGH;
        digitalWrite(transistor, transistorState);
        if(transistorState == LOW){
          transistorStateInt = 0;
        } else{
          transistorState = 1;
        }
      }
    }
  }
  for (auto const &host : Husarnet.listPeers()) {
    IPv6Address peerAddr = host.first;
    if(host.second == "master") {
      ;
    } else {
      AsyncClient* client_tcp = new AsyncClient;
      
      client_tcp->onConnect([](void *arg, AsyncClient *client) {
        String requestURL = "/led/1/state/" + String(transistorStateInt);
        String GETreq = String("GET ") + requestURL + " HTTP/1.1\r\n" + "Host: esp32\r\n" + "Connection: close\r\n\r\n";

        if ( client->canSend() && (client->space() > GETreq.length())){
          client->add(GETreq.c_str(), strlen(GETreq.c_str()));
            client->send();
        } else {
          Serial.printf("\r\nSENDING ERROR!\r\n");
        }
      }, client_tcp);

  }
}
4

0 回答 0