// Include necessary libraries
#include <Wire.h> // For I2C communication with LCD
#include <LiquidCrystal_I2C.h> // For controlling LCD
#include <SPI.h> // For SPI communication with PIR sensor
// Define pins for buttons and PIR sensor
#define BUTTON1 9
#define BUTTON2 2
#define PIR_SENSOR A1
// Define LCD address and dimensions
#define LCD_ADDRESS 0x27
#define LCD_COLUMNS 16
#define LCD_ROWS 2
// Initialize LCD object with address and dimensions
LiquidCrystal_I2C lcd(LCD_ADDRESS, LCD_COLUMNS, LCD_ROWS);
// Define variables for game state and score
bool gameStarted = false;
int score = 0;
void setup() {
// Set button pins as inputs
pinMode(BUTTON1, INPUT_PULLUP);
pinMode(BUTTON2, INPUT_PULLUP);
// Initialize LCD and print starting message
lcd.init();
lcd.backlight();
lcd.print("Press button 1");
// Initialize PIR sensor
SPI.begin();
pinMode(PIR_SENSOR, INPUT);
}
void loop() {
// Check if button 1 is pressed to start game
if (digitalRead(BUTTON1) == LOW) {
// Set game state to true and print starting message
gameStarted = true;
lcd.clear();
lcd.print("Starting game...");
// Wait for 5 seconds
delay(2000);
// Clear LCD and print score message
lcd.clear();
lcd.print("Score = ");
}
// Check if game is started
if (gameStarted) {
// Check if PIR sensor detects motion
if (digitalRead(PIR_SENSOR) == HIGH) {
// Increase score by 1 and print updated score
score++;
lcd.setCursor(8, 0);
lcd.print(score);
delay(3000);
}
}
// Check if button 2 is pressed to end game
if (digitalRead(BUTTON2) == LOW) {
// Set game state to false and print game over message
gameStarted = false;
lcd.clear();
lcd.print("Game over.");
delay(2000);
// Clear LCD and print score message
lcd.clear();
lcd.print("Press Button 1");
score = 0;
}
}