0

I have the following function piece of code in my ESP8266 based NodeMCU:

  snprintf ( temp, 800,
             "<html>\
  <head>\
    <meta http-equiv='refresh' content='25'/>\
    <title>NodeMCU DHT11 Sensor \and Relay Board</title>\
    <style>\
      body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\
      li { margin: 10px 0;}\
    </style>\
  </head>\
  <body>\
  <h1>Hello from NodeMCU!</h1>\
  <p>Temperature: %02d &#8451;<br>\
  Humidity: %2d %<br></p><ol>\
  <li><a href='/control?relay=5&state=%d'>Turn Relay 1 On\/Off</a>\
  <li><a href='/control?relay=4&state=%d'>Turn Relay 2 On\/Off</a></ol>\
    <p> Uptime: %02d:%02d:%02d </p>\
  </body>\
</html>",
             t, h, !digitalRead(5), !digitalRead(4), hr, min % 60, sec % 60
           );

I want to be able to replace text on with off and vice versa based on the state of pin which comes from digitalRead(5). So I don't have to write Turn Relay 1 On/Off and instead I should get the state using digitalRead(pinNum) and set the text on or off based on state.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Ciasto piekarz
  • 7,853
  • 18
  • 101
  • 197

1 Answers1

0

The ternary (conditional) operator is your friend here. You could treat it as an inline if-statement. The syntax looks like this

condition ? val1 : val2

The expression will yield a result depending on condition. If the condition is true it will yield val1, otherwise it will yield val2.

You can use this inside of sprintfs argument list to return a string depending on the pin state.

snprintf(temp, 800, 
    "... <li><a href='/control?relay=5&state=%d'>Turn Relay 1 %s</a><li> ... ", 
    !digitalRead(5), (digitalRead(5) ? "Off" : "On");

%s is a placeholder for a string and depending on the state of the pin 5 it will be replaced by "On" or "Off"

Community
  • 1
  • 1
muXXmit2X
  • 2,745
  • 3
  • 17
  • 34
  • it's hard to imagine a library that offers `snprintf` but doesn't support `%s` in its format string... maybe you have a bug elsewhere in your program – M.M Mar 31 '17 at 07:09