如何在此Arduino游戏中暂停为LED分配值以等待玩家输入?

时间:2015-12-17 10:28:33

标签: arduino

我正在制作一款小型Arduino游戏。 随机二进制数由4个LED创建并显示。 (例如,如果它是3,则LED变为0011)。 玩家需要猜测并按下按钮次数。 如果你猜对了,你就赢了,单独的结果 - LED闪烁。如果你输了,它会打开并保持很长时间。

我会发布到目前为止的代码。 问题是LED只是开始快速闪烁(所以随机数被分配)但程序没有等待用户输入。

我的错误在哪里?

//declaring and initializing button and leds
int led1 = 9;
int led2 = 6;
int led3 = 5;
int led4 = 3;

int ledResult = 13; //will blink when you won, stay on when you lost

int buttonPin = 2;
int val = 0; // variable for reading the pin status
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;


long interval = 2000;

long randomNumber;


void setup() {
  Serial.begin(9600); //starts serial communication

  pinMode (led1, OUTPUT);
  pinMode (led2, OUTPUT);
  pinMode (led3, OUTPUT);
  pinMode (led4, OUTPUT);

  pinMode (ledResult, OUTPUT);

  pinMode (buttonPin, INPUT);

  randomSeed(analogRead(A0)); //the pin is unconnected so it'll return something random (0-1023)


}

void loop() {

  randomNumber = random(1, 16);

  Serial.println("Random Numbers sequence"); //just for self-check
  Serial.println(randomNumber);

  if (randomNumber >= 8)
   {
    digitalWrite (led1, HIGH);
    randomNumber - 8;
  }
  else
  {
   digitalWrite (led1, LOW);
  }

  if (randomNumber >= 4)
  {
    digitalWrite (led2, HIGH);
    randomNumber - 4;
  }
  else
  {
    digitalWrite (led2, LOW);
  }

  if (randomNumber >= 2)
  {
    digitalWrite (led3, HIGH);
    randomNumber - 2;
  }
  else
  {
    digitalWrite (led3, LOW);
  }

  if (randomNumber = 1)
  {
    digitalWrite (led4, HIGH);
  }
  else
  {
    digitalWrite (led4, LOW);
  }


 //READ BUTTON STATE
  buttonState = digitalRead(buttonPin);
// compare the buttonState to its previous state
  if (buttonState != lastButtonState) {

unsigned long start = millis();
if ((millis() - start) >= interval); {

  if (buttonState == HIGH)
  {

    buttonPushCounter++;
    Serial.println("Button push counter:");
    Serial.println(buttonPushCounter);
  }
  // Delay a little bit to avoid bouncing
  delay(50);
}
// save the current state as the last state, for next time through the loop
lastButtonState = buttonState;

if (buttonPushCounter == randomNumber) {
  Serial.println("You won!");
  digitalWrite(ledResult, HIGH);
  delay(700);
  digitalWrite(ledResult, LOW);
  delay(700);
}
else
{
  Serial.println("You lost.");
  digitalWrite(ledResult, HIGH);
    }

  }
}

0 个答案:

没有答案