Arduino让我错了号码

时间:2016-09-14 14:52:17

标签: arrays if-statement arduino logical-operators

我制作了一个小脚本,它随机给出了0到3之间的数字并将它们写入数组。

代码应该是,只有特定的时间,数字才能在自己之后相同。因此,例如,如果之前有过两次,他必须采取另一个数字......但这个合乎逻辑的事情似乎不起作用?有人有想法吗? :/

int gameCount = 0;
int setupCount = 0;
long game[50];
int maxRepeat = 2;

void setup() {
  Serial.begin(9600);  

  for (int i = 0; i < 50; i++) {
    getNumber();
  }

  Serial.println("");
  for (int i = 0; i < 50; i++) {
    Serial.print(game[i]);
  }      
}

void loop() {
}

int getNumber() {  
  randomSeed(analogRead(A0));
  int number = random(1, 32)%4;

  if (setupCount < maxRepeat) {
    game[setupCount] = number;
    setupCount++;
  } else {

    int hits = 0;
    for (int i = setupCount; i < setupCount+maxRepeat; i++) {
      if (game[i] == number) {
        hits++;
      }
    }          

    if (hits == maxRepeat) {

      if (number == 0) {
        number = 1;
        Serial.println("It was a 0!!!");
      }

       else if (number == 1) {
        number = 2;
        Serial.println("It was a 1!!!");
      }

       else if (number == 2) {
        number = 3;
        Serial.println("It was a 2!!!");
      }

      else if (number == 3) {
        number = 0;
        Serial.println("It was a 3!!!");
      }           
    }

    game[setupCount] = number;
    setupCount++;        
  }

  return number;     
}

1 个答案:

答案 0 :(得分:1)

byte game[50]; // 50 values 0 .. 3, but never 3 identical numbers in sequence
void setup() {
  randomSeed(analogRead(A0));
  byte prev = 99;
  byte pprev = 99;
  for (int i = 0; i < 50; i++) {
    byte candidate = random(4);  // a random value 0..3
    if (candidate != prev || prev != pprev) {
      game[i] = candidate;
      pprev = prev;
      prev = candidate;
    }
  }
}

void loop() {}