如何优化以下代码? (它在arduino中)

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

我需要执行一个根据路径设置颜色的函数,也就是说,只有一个函数而不是调用 bring up void red, void green, void blue。我知道我必须将路由和每种颜色的值作为参数传递 (String route, int color) 但我不知道该怎么做。

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

    #define PIN 21
    #define NUM_LEDS 20
    #define FIREBASE_HOST "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    #define FIREBASE_AUTH "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

     const char* ssid = "XXXXXXXXXXXX";
     const char* password = "XXXXXXXXXXXX";

     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();
    }

如果我正确理解你的问题,你可以通过传递你想要设置的颜色变量作为引用参数调用来实现,如下所示:

  void setRGB(String route, int &colorValue) {
   if (Firebase.getInt(firebaseData,route)) {
   if  (firebaseData.dataType() == "int") {
    int val = firebaseData.intData();
    if (val != colorValue) {
     colorValue = val;
     setLedColor();
     }
    }
   }
  }

然后你可以像这样调用setRGB来设置redValue等:

setRGB("/lampara4/red", redValue);
setRGB("/lampara4/green", greenValue);
setRGB("/lampara4/blue", blueValue);