So you're a Noob? Post your questions here until you graduate! Don't be shy.

User avatar
By liderbug
#73652 OK a search for server.on returned 3375 (now 6) and the first 20 didn't come close. So... help...

I can't find a "man page" for "server.on", examples, yes. But as I gather the description would be:
server.on ([path], [function]);
I'd like to pass a value to the to the function ie. on/off, 1/0, up/down etc. It didn't have a problem with "function (int n) {dosomething;}" but went screaming into the night with "invalid use of the void expression "server.on... switchRelay(1));" Now I can work around by creating 2 unique subroutines but I'm a minimalist - as is never do anything in 20 lines of code you can do in 2000 - NOT!
Anyhow, I think I know the answer - SOL - but I'd like someone to verify. Thanks
User avatar
By btidey
#73654 Although not minimalist, I prefer to keep the function definition away from the server.on code. This makes it clearer and something likely to be understandable when you look at it 6 months later.

So server.on("/on", switchRelayOn);

accompanied by

void switchRelayOn() {
switchRelay(1);
server.send(200, "text/html", "Done");
}

If you want to include the arguments in the url like /switch?value=1 then it would be like

server.on("/switch", "switch")
accompanied by
void switch() {
if(server.arg("value").toInt() == 1)
switchRelay(1);
else
switchRelay(0);
server.send(200, "text/html", "Done");
}
User avatar
By liderbug
#73655 So this is the code I ended with:
Code: Select all 
server.on("/on", switchRelay1);
server.on("/off", switchRelay0);


Code: Select allvoid switchRelay1(){ switchRelay (1); }
void switchRelay0(){ switchRelay (0); }

void switchRelay(int n){
  char msg[32] = "";
  digitalWrite (5, n);
switch (n)
{
   case 1: strcpy (msg, "Relay ON"); break;
   case 0: strcpy (msg, "Relay OFF"); break;
   default: break;
}
  server.send (200, "text/html", msg);
}


Guess it's the way my mind works, but ... you should be able to say
Code: Select allserver.on ("/on", callrelay(1));
server.on ("/off", callrelay(0));


... for the suggestion box.