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.

asked Mar 26, 2017 at 16:42
2
  • server.on ( "/", handleRoot ); why it used?? Commented Dec 27, 2018 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. Commented Dec 27, 2018 at 14:10

1 Answer 1

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.

answered Mar 27, 2017 at 8:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.