How can I optimize the following code? (it’s in arduino)

  arduino, c++, firebase

I need to perform a function that sets the color depending on the path, that is, to have a single function instead of calling bring up void red, void green, void blue. I understand that I must pass the route and the value of each color as parameters (String route, int color) but I don’t know how to do it.

    #include<WiFi.h>
    #include<FirebaseESP32.h>
    #include <Adafruit_NeoPixel.h>

    #define PIN 21
    #define NUM_LEDS 20
    #define FIREBASE_HOST "techsoftcbot-qnnvcm.firebaseio.com/"
    #define FIREBASE_AUTH "5PP2gj9FnBQGpskbBqHqMUJb3NtT4CP1cO5w4h2w"

     const char* ssid = "ARRIS-7BF2";
     const char* password = "630E2A513DB64FE9";

     FirebaseData firebaseData;

     Adafruit_NeoPixel leds(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);

   // Current color values
      int redValue = 0;
      int greenValue = 0;
      int blueValue = 0;

       void setup() {
       Serial.begin(9600);
       WiFi.begin(ssid, password);

        while (WiFi.status() != WL_CONNECTED) {
          delay(500);
         Serial.print(".");
         }

     Serial.println(".......");
     Serial.println("WiFi Connected....IP Address:");
     Serial.println(WiFi.localIP());

     leds.begin();
  
     Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
     Firebase.reconnectWiFi(true);
      }


     void setLedColor() {
      for (int i=0; i < NUM_LEDS; i++) 
      leds.setPixelColor(i, leds.Color(redValue, greenValue, blueValue));
      leds.show();
     }


      void red(String route) {
       if (Firebase.getInt(firebaseData,route)) {
       if  (firebaseData.dataType() == "int") {
        int val = firebaseData.intData();
        if (val != redValue) {
         redValue = val;
         setLedColor();
         }
        }
       }
      }
    void green(String route){
      if (Firebase.getInt(firebaseData,route)) {
      if  (firebaseData.dataType() == "int") {
      int val = firebaseData.intData();
      if (val != greenValue) {
        greenValue = val;
        setLedColor();
         }
       }
      }
     }

    void blue(String route){

     if (Firebase.getInt(firebaseData,route)) {
      if  (firebaseData.dataType() == "int") {
       int val = firebaseData.intData();
       if (val != blueValue) {
        blueValue = val;
        setLedColor();
         }
        }
     }
   }

    void init(){
    red("/lampara4/red");
    green("/lampara4/green");
    blue("/lampara4/blue"); 
     }

    void loop() {
    init();
    }

Source: Windows Questions C++

LEAVE A COMMENT