Painonapeilla toteutettu nopeuspeli on tuttu meille kaikille, iloisilla 80- ja 90-luvulla eläneille. (Speden spelit)
Kokeillaan tehdä Controllinon avulla itse tällainen nopeuspeli.
#include <Controllino.h>
const int buttonPins[] = {A0, A1, A2, A3};
const int ledPins[] = {CONTROLLINO_D0, CONTROLLINO_D1, CONTROLLINO_D2, CONTROLLINO_D3};
int gameSpeed = 2000;
int playerScore = 0;
void setup() {
pinMode(CONTROLLINO_D0, OUTPUT);
pinMode(CONTROLLINO_D1, OUTPUT);
pinMode(CONTROLLINO_D2, OUTPUT);
pinMode(CONTROLLINO_D3, OUTPUT);
for (int i = 0; i < 4; i++) {
pinMode(buttonPins[i], INPUT);
//digitalWrite(buttonPins[i], LOW); // Use internal pull-up resistor
pinMode(ledPins[i], OUTPUT);
digitalWrite(ledPins[i], LOW);
}
randomSeed(analogRead(0));
Serial.begin(9600);
Serial.println("Tervetuloa, Nopeuspeli neljällä napilla!");
}
void loop() {
delay(2000);
int targetButton = random(4);
int targetLED = ledPins[targetButton];
digitalWrite(targetLED, HIGH);
delay(1000);
digitalWrite(targetLED, LOW);
int startTime = millis();
int buttonPressed = -1;
while (millis() - startTime < gameSpeed) {
for (int i = 0; i < 4; i++) {
if (digitalRead(buttonPins[i]) == HIGH) {
buttonPressed = i;
while (digitalRead(buttonPins[i]) == LOW) {} // Wait until the button is released
delay(100); // Small delay to avoid continuous registration
break;
}
}
}
if (buttonPressed == targetButton) {
playerScore++;
Serial.print("OIKEIN! Pisteet: ");
Serial.println(playerScore);
} else {
Serial.println("Väärin! Peli päättyy.");
playerScore = 0;
gameSpeed = 1000;
}
gameSpeed = max(200, gameSpeed - 50);
for (int i = 0; i < 4; i++) {
digitalWrite(ledPins[i], LOW);
}
Serial.print("Peli päättyi. Käyttäjä painoi oikein ");
Serial.print(playerScore);
Serial.print(" kertaa. Oikea nappi oli: ");
Serial.println(targetButton + 1);
delay(1000);
}