#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Pin definitions
const int buttonPin = 2; // Pin for push button
const int ledPin = 9; // Pin for LED
const int buzzerPin = 10; // Pin for Buzzer
// Game variables
int secretNumber; // Number to guess
int playerGuess; // Player's guess
int score = 0; // Player's score
// Initialize LCD with I2C address 0x27 and size 16x2
LiquidCrystal_I2C lcd(0x27, 16, 2); // Ganti alamat I2C jika diperlukan
void setup() {
Serial.begin(9600); // Start serial communication
pinMode(buttonPin, INPUT_PULLUP); // Set button pin as input with pull-up resistor
pinMode(ledPin, OUTPUT); // Set LED pin as output
pinMode(buzzerPin, OUTPUT); // Set Buzzer pin as output
randomSeed(analogRead(0)); // Seed random number generator
lcd.begin(16, 2); // Initialize the LCD with columns and rows
lcd.backlight(); // Turn on the backlight
startGame(); // Start the game
}
void loop() {
if (digitalRead(buttonPin) == LOW) { // Check if button is pressed
delay(50); // Debounce delay
playerGuess = random(1, 11); // Simulate player guess (1 to 10)
Serial.print("Player guessed: ");
Serial.println(playerGuess); // Show guessed number on serial monitor
// Check if the guess is correct
if (playerGuess == secretNumber) {
digitalWrite(ledPin, HIGH); // Turn on LED for correct guess
tone(buzzerPin, 1000, 200); // Play buzzer sound for 200 milliseconds
Serial.println("Correct!"); // Indicate correct guess
lcd.clear();
lcd.print("Correct!");
score++; // Increase score
lcd.setCursor(0, 1); // Move cursor to second line
lcd.print("Score: ");
lcd.print(score); // Display score
delay(1000); // Keep LED on for a while
digitalWrite(ledPin, LOW); // Turn off LED
startGame(); // Start a new game
} else {
Serial.println("Try again!"); // Indicate wrong guess
lcd.clear();
lcd.print("Try again!");
delay(1000); // Display for a while
}
while (digitalRead(buttonPin) == LOW); // Wait for button release
}
}
void startGame() {
secretNumber = random(1, 11); // Generate a random number between 1 and 10
lcd.clear();
lcd.print("Guess a number");
lcd.setCursor(0, 1); // Move cursor to second line
lcd.print("1 to 10");
}