dimanche 2 mai 2021

Simplifying for cycle

I have this code in C++ for my arduino:

void loop() {
  unsigned long time = millis();
  bool isDown[] = { digitalRead(button1_pin) == ON, digitalRead(button2_pin) == ON, digitalRead(button3_pin) == ON };
  int change = power(10, currentDigit);

  if (wasDown[0] != isDown[0] && isDown[0]){
    sum = (sum + change) % modulo;
  }
  if (wasDown[1] != isDown[1] && isDown[1]){
    sum = (sum - change + modulo) % modulo;
  }

  for (int i = 0; i < wasDownCount; ++i){
    if (wasDown[i] != isDown[i] && isDown[i]){
      if (i == wasDownCount - 1){
        currentDigit = (currentDigit + 1) % displayDigits;
      }
      else {
        CalculateDigits(sum, displayDigits, digitsOfSum);
      }
      displayDigit(digitsOfSum[currentDigit], currentDigit);
    }
    wasDown[i] = isDown[i];
  }
}

Is there a way I can simplify it? Because now there are many if statements and even for loop is divided by if. I have no idea how I can put these things outside from loop when they need only be done if the statement is true.

Aucun commentaire:

Enregistrer un commentaire