如何检查值是否按正确顺序更改? C ++

时间:2015-11-22 15:44:38

标签: c++ arduino

我需要一种方法来检查这些引脚是否按正确顺序从HIGH变为LOW。 (即RED> BROWN> BLUE> GRAY> BLACK> YELLOW> WHITE> ORANGE> PURPLE> GREEN)如果其中一个引脚无序更改,则必须向“errorCount”添加1如果错误计数超过4,则调用函数。

引脚的部分代码:

  const int wire_BROWN =  30;
  int wire_BROWN_state = 0;
  int wire_BROWN_lastState = 0;

  const int wire_RED =    32;
  int wire_RED_state = 0;
  int wire_RED_lastState = 0;

  const int wire_ORANGE = 34;
  int wire_ORANGE_state = 0;
  int wire_ORANGE_lastState = 0;

  const int wire_YELLOW = 36;
  int wire_YELLOW_state = 0;
  int wire_YELLOW_lastState = 0;

  const int wire_GREEN =  38;
  int wire_GREEN_state = 0;
  int wire_GREEN_lastState = 0;

  const int wire_BLUE =   40;
  int wire_BLUE_state = 0;
  int wire_BLUE_lastState = 0;

  const int wire_PURPLE = 42;
  int wire_PURPLE_state = 0;
  int wire_PURPLE_lastState = 0;

  const int wire_GREY =   44;
  int wire_GREY_state = 0;
  int wire_GREY_lastState = 0;

  const int wire_WHITE =  46;
  int wire_WHITE_state = 0;
  int wire_WHITE_lastState = 0;

  const int wire_BLACK =  48;
  int wire_BLACK_state = 0;
  int wire_BLACK_lastState = 0;

1 个答案:

答案 0 :(得分:1)

您可以按照要检查的顺序将它们放入数组中,然后遍历数组,运行检查

伪代码:

byte check(int a[]){ // Get's called on update of pins
    byte error = 0;
    for (byte i=1; i < a.length - 1; a++);
    if (a[i] < a[i-1]){
       error++;
    }
    return(error)
}

byte stateArray[] = {
  digitalRead(wire_BROWN),
  digitalRead(wire_BLUE),
  digitalRead(wire_BLACK),
  digitalRead(wire_YELLOW),
  digitalRead(wire_WHITE),
  digitalRead(wire_ORANGE),
  digitalRead(wire_PURPLE),
  digitalRead(wire_GREEN),
};
byte errorCount = check(stateArray);
if (errorCount > 4) {
    // Error Handling
}