2

this probably simple thing to do however I can't think of a way to pass argument to function call

ESP8266WebServer server ( 80 );

void toggleRelayOne() {
  char temp[400];
  String msg = "";
  if (relay1 == 0) {
    relay1 = 1;
    msg = "Light is turned on";
  }
  else {
    relay1 = 0;
    msg = "Light is turned off";
  }


  digitalWrite (5, relay1); //GPIO 5 // Relay 1
  snprintf ( temp, 400,
             "<html>\
  <head>\
    <meta http-equiv='refresh' content='5'/>\
    <title>NodeMCU DHT11 Sensor and Relay Board</title>\
    <meta http-equiv='refresh' content='0; url=../'>\
    </head>\
  <body>\
  %d .</body>\
  </html>"
             , 1);
  server.send ( 200, "text/html", temp );
}

void setup ( void ) {

  pinMode(10, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);

  Serial.begin ( 9600 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );
  // Wait for connection
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( host ) ) {
    Serial.println ( "MDNS responder started" );
  }
  MDNS.addService("http", "tcp", 80);
  server.on ( "/", handleRoot );
  server.on("/relay1", toggleRelayOne);
  server.begin();
  Serial.println ( "HTTP server started" );
}

in the above function where I am calling toggleRelayOne using server.on("/relay1", toggleRelayOne); I want to be able to pass relay id so I can use same function to toggle multiple relays.

  • server.on ( "/", handleRoot ); why it used?? – Guru Prasad Nayak Dec 27 '18 at 11:33
  • When a user tries to navigate to "/" I call a function handleRoot . This function reads the data from sensors connected to ESP826. – Ciasto piekarz Dec 27 '18 at 14:10
2

Use server.arg() to pass commands from the web as GET params:

digitalWrite (5, relay1);

becomes

digitalWrite (server.arg("pin").toInt(), relay1);

where the URL is something like http://192.168.1.5/relay1?pin=15

Of course, the rest of your code probably needs to be adapted to manage the extra states, read/write all in one http call, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.