#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // LCD address
// Ultrasonic Sensor Pins
const int trigPin = 11;
const int echoPin = 12;
// Joystick Pins
const int joyY = A0;
const int joyBtn = 8;
// Buzzer Pin
const int buzzerPin = 3;
// Game Elements
#define DINO 'D'
#define CACTUS '#'
#define GROUND '_'
// Game Variables
int dinoPos = 1; // 1=ground, 0=jumping
int cactusPos = 15;
int score = 0;
bool gameRunning = false;
const int jumpDistance = 15; // Distance (cm) to trigger jump
void setup() {
lcd.init();
lcd.backlight();
// Ultrasonic Sensor
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Joystick Button
pinMode(joyBtn, INPUT_PULLUP);
// Buzzer
pinMode(buzzerPin, OUTPUT);
showStartScreen();
}
void loop() {
if (!gameRunning && digitalRead(joyBtn) == LOW) {
startGame();
}
if (gameRunning) {
playGame();
delay(200); // Game speed
}
}
float getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
return duration * 0.034 / 2;
}
void showStartScreen() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Wave Hand to Start");
lcd.setCursor(0, 1);
lcd.print("or Press Button");
}
void startGame() {
gameRunning = true;
score = 0;
dinoPos = 1;
cactusPos = 15;
lcd.clear();
beep(100);
}
void playGame() {
float distance = getDistance();
// Jump if hand detected OR joystick up
if ((distance > 0 && distance < jumpDistance) || analogRead(joyY) < 300) {
dinoPos = 0; // Jump
beep(50);
} else {
dinoPos = 1; // On ground
}
drawGame();
checkCollision();
moveCactus();
}
void drawGame() {
lcd.clear();
// Draw ground
for (int i = 0; i < 16; i++) {
lcd.setCursor(i, 1);
lcd.print(GROUND);
}
// Draw dino
lcd.setCursor(1, dinoPos);
lcd.print(DINO);
// Draw cactus
lcd.setCursor(cactusPos, 1);
lcd.print(CACTUS);
// Draw score
lcd.setCursor(12, 0);
lcd.print(score);
}
void checkCollision() {
if (cactusPos == 1 && dinoPos == 1) {
gameOver();
}
}
void moveCactus() {
cactusPos--;
if (cactusPos < 0) {
cactusPos = 15;
score++;
beep(50);
}
}
void gameOver() {
gameRunning = false;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Game Over!");
lcd.setCursor(0, 1);
lcd.print("Score: ");
lcd.print(score);
beep(300);
delay(2000);
showStartScreen();
}
void beep(int duration) {
tone(buzzerPin, 1000, duration);
}