Using a slider widget to enable/disable a feature

I was thinking about a way to use a slider widget for both enable/disable and change a parameter of a feature of the sketch. The idea is: drag the slider to zero to disable the feature, drag the slider to any other value to enable the feature and set the parameter to this value (for example enable a Timer an set the time interval).

I came up with the solution below:

bool flagVar = false;   // Flag variable for enabling/disabling a feature, a function etc.
int parameter = 0;      // Define any parameter.

void setup() {

// Input resource connected with a slider widget.
      thing["enable_disable"] << [](pson& in){
        if (in.is_empty()){        
            if (flagVar){
                in = parameter;
            } else {
              in = 0;
              }
        } else {
          int var = in;           
          if (var == 0){
              flagVar = false;                             
          } else {
            parameter = var;
            flagVar = true;                                          
            }              
          }    
        };

if there is a more “professional” way to accomplish this task please leave a comment.

I think that this can be simplified like this:

int parameter = 0;

bool enabled(){
  return parameter!=0  
}

void setup(){
  thing["enable_disable"] << inputValue(parameter);
}

Instead of using flagVar, you can just call the enabled function, or directly check if parameter != 0.

Or, if you want to keep flagVar, you can also code this way:

int parameter = 0;
bool flagVar = false;

void setup(){
  thing["enable_disable"] << inputValue(parameter,{
    flagVar = parameter>0;
  });
}

:wink:

Hi @alvarolb, this macro is awesome! and yes, you are right, after rethinking about my code logic I don’t really need the flagVar. I was able to get rid off several code lines and now my code looks pretty neat. I love it! :slight_smile:

Thanks!