processingcontrol-p5

control a toggle by a button click


i needed to create a gui where a toggle would be ON when we click on a specified button , the problem is i cant find the right command to do so , here is an example of how i added my toggle :

cp5.addToggle("condenseur")
     .setPosition(700,585)
     .setSize(70,70)
     .setValue(false)
     .setLabelVisible(false);

and here is the function (the button click) where i want it to return a char AND change the toggle state (makes it ON) void marche(){ port.write('a');

i tried to use setValue() or condensateur = true but none worked


Solution

  • The following code uses two buttons to toggle a cp5 toggle button. Reference: https://www.kasperkamperman.com/blog/processing-code/controlp5-library-example2/

    import controlP5.*;
    
    ControlP5 cp5;
    
    void setup() {
      size(400, 300);
      cp5 = new ControlP5(this);
      cp5.addToggle("toggle")
        .setPosition(200, 90)
        .setSize(70, 70)
        .setValue(false)
        .setLabelVisible(false)
        ;
    
      cp5.addButton("on")
        .setValue(0)
        .setPosition(50, 100)
        .setSize(50, 19)
        ;
    
      cp5.addButton("off")
        .setValue(0)
        .setPosition(120, 100)
        .setSize(50, 19)
        ;
    }
    
    void draw() {
    }
    
    void controlEvent(ControlEvent theEvent) {
    
      if (theEvent.isController()) {
        print("control event from : " + theEvent.getController().getName());
        println(", value : " + theEvent.getController().getValue());
    
        if (theEvent.getController().getName()=="on") {
          cp5.getController("toggle").setValue(1);
        }
    
        if (theEvent.getController().getName()=="off") {
          cp5.getController("toggle").setValue(0);
        }
      }
    }