arduino-toy-projects/fastest_presser/src/main.cpp

130 lines
2.6 KiB
C++
Raw Normal View History

2021-04-28 21:59:11 +02:00
#include <Arduino.h>
2021-04-28 23:27:30 +02:00
#include <LiquidCrystal.h>
#include <main.h>
2021-04-29 07:23:14 +02:00
#define LCD_COLS 16
#define LCD_ROWS 2
#define PLAYER_A 2
#define PLAYER_B 3
#define TIE 0
2021-04-29 13:31:09 +02:00
LiquidCrystal lcd(9, 8, 4, 5, 6, 7);
2021-04-29 07:23:14 +02:00
unsigned int scoreA = 0;
unsigned int scoreB = 0;
2021-04-28 23:27:30 +02:00
2021-04-28 21:59:11 +02:00
void setup() {
2021-04-28 23:27:30 +02:00
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
2021-04-29 07:23:14 +02:00
pinMode(PLAYER_A, INPUT_PULLUP);
pinMode(PLAYER_B, INPUT_PULLUP);
2021-04-28 23:27:30 +02:00
randomSeed(analogRead(0));
2021-04-29 07:23:14 +02:00
lcd.begin(LCD_COLS, LCD_ROWS);
2021-04-28 21:59:11 +02:00
}
void loop() {
2021-04-29 07:23:14 +02:00
waitForReady();
2021-04-28 23:27:30 +02:00
displayCountdown();
delay(1000);
byte randomWait = random(6, 32);
lcd.clear();
for (byte i = 0; i < randomWait; i++) {
2021-04-29 07:23:14 +02:00
if (i == LCD_COLS) {
lcdSecondLine();
2021-04-28 23:27:30 +02:00
}
lcd.print(".");
delay(500);
}
lcd.clear();
lcd.print("Maintenant !");
2021-04-29 07:23:14 +02:00
const byte winner = computeWinner();
2021-04-28 23:27:30 +02:00
lcd.clear();
2021-04-29 07:23:14 +02:00
if (winner == PLAYER_A) {
lcd.print("Bravo joueur A !");
scoreA += 1;
}
else if (winner == PLAYER_B) {
lcd.print("Bravo joueur B !");
scoreB += 1;
}
else {
lcd.print("Egalite");
}
delay(4000);
printScore();
2021-04-28 23:27:30 +02:00
}
void displayCountdown() {
2021-04-29 07:23:14 +02:00
lcd.clear();
2021-04-28 23:27:30 +02:00
lcd.print("Prets ?");
2021-04-29 07:23:14 +02:00
lcdSecondLine();
2021-04-28 23:27:30 +02:00
displayDigit("3");
delay(600);
displayDigit("2");
delay(600);
displayDigit("1");
}
void displayDigit(const char *digit) {
lcd.print(digit);
for (byte i = 0; i < 3; i++) {
delay(200);
lcd.print(".");
}
lcd.print(" ");
}
2021-04-29 07:23:14 +02:00
byte computeWinner() {
int playerA = digitalRead(PLAYER_A);
int playerB = digitalRead(PLAYER_B);
while (playerA == HIGH && playerB == HIGH) {
// Wait for a button press
playerA = digitalRead(PLAYER_A);
playerB = digitalRead(PLAYER_B);
}
if (playerA == LOW && playerB == HIGH) {
return PLAYER_A;
}
if (playerA == HIGH && playerB == LOW) {
return PLAYER_B;
}
else {
return TIE;
}
}
void lcdSecondLine() {
lcd.setCursor(0, 1);
}
void printScore() {
lcd.clear();
lcd.print("A: ");
lcd.print(scoreA);
lcdSecondLine();
lcd.print("B: ");
lcd.print(scoreB);
delay(2000);
}
void waitForReady() {
lcd.clear();
lcd.print("A: Commencer");
lcdSecondLine();
lcd.print("B: Scores");
int playerA = digitalRead(PLAYER_A);
int playerB = digitalRead(PLAYER_B);
while (playerA == HIGH && playerB == HIGH) {
// Wait for a button press
playerA = digitalRead(PLAYER_A);
playerB = digitalRead(PLAYER_B);
}
if (playerB == LOW) {
printScore();
waitForReady();
}
}