Been trying to figure out what this line does in the code below. I've done a log of reverse engineering and found that if I set the (val) to (1) I get the high response or whatever I put in that first "" same thing goes if I put (0) in the place of Val I get Low or whatever I change the word to... But just don't understand how its working because I can't do s += (val)?"high":"Low":"LowLow";
s += (val)?"high":"Low";
so really just want to know what the ? does. I know this is probably really basic but looked on the leaning center under strings and can't figure it out.
thanks let me know if you need more info.
int val; // create the Integer val
if (req.indexOf("/gpio/0") != -1) //if the data sent to the webserver "request" matches /gpio/0"
{
val = 0; // Set val to 0
Serial.println(val); // print the val to serial
}
else if (req.indexOf("/gpio/1") != -1) // if the data sent to the webserver "request" matches /gpio/1"
{
val = 1; // Set val to 0
Serial.println(val); // print the val to serial
}
else { // for everything else print invalid request
Serial.println("invalid request");
client.stop();
return;
}
// Prepare the response
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n\r\n\r\nGPIO is now "; // http response
s += (val)?"high":"Low";
s += "\n";
// Send the response to the client
client.print(s);
delay(1);
Serial.println("Client disonnected");
The ternary operator is shorthand for an if-else block. In your case:
if (val != 0) {
s += "high"; // s = s + "high"
} else {
s += "Low"; // s = s + "Low"
}
That is, if the logical test on val is logic True (i.e., non-zero), "high" is added to s. If val is 0, then "Low" is added to s. Evidently, s is a String variable.
int valueA = 12;
int valueB = 7;
Serial.println((valueA > 10) ? "Greater than 10" : "Less than 10");
Serial.println((valueB > 10) ? "Greater than 10" : "Less than 10");
This will print:
Greater than 10
Less than 10
P.S: Please use code tags, using the </> button or by using [code][/code] around your code.
Syntax details...
Notice that a single question mark separates the boolean test from the values.
Notice that a SINGLE colon is used to separate the two (and only TWO) values.