#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Pin Definitions
const int buttonPin1 = 2; // Button for Answer A
const int buttonPin2 = 3; // Button for Answer B
const int buttonPin3 = 4; // Button for Answer C
// Create an LCD object
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Questions and answers
String questions[] = {
"2 + 2 =",
"29 + 3 =",
"15 + 15 ="
};
String options[3][3] = {
{"5", "4", "6"},
{"32", "30", "36"},
{"20", "25", "30"}
};
int correctAnswers[] = {1, 0, 2}; // Correct answer indexes for each question (0=A, 1=B, 2=C)
int currentQuestion = 0; // Track current question
bool isAnswerSelected = false; // Flag for when an answer is selected
void setup() {
// Initialize the LCD and buttons
lcd.begin(16, 2);
lcd.print("Math Exercise!");
delay(2000); // Display welcome message for 2 seconds
lcd.clear();
// Set up button pins as inputs
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
pinMode(buttonPin3, INPUT);
// Show the first question
displayQuestion(currentQuestion);
}
void loop() {
if (isAnswerSelected) {
return; // Wait for answer selection to be processed
}
// Read button states
if (digitalRead(buttonPin1) == HIGH) {
checkAnswer(0);
} else if (digitalRead(buttonPin2) == HIGH) {
checkAnswer(1);
} else if (digitalRead(buttonPin3) == HIGH) {
checkAnswer(2);
}
}
void displayQuestion(int questionIndex) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(questions[questionIndex]); // Display the question
// Display the options
lcd.setCursor(0, 1);
lcd.print("A:" + options[questionIndex][0] + " B:" + options[questionIndex][1] + " C:" + options[questionIndex][2]);
}
void checkAnswer(int selectedAnswer) {
isAnswerSelected = true;
if (selectedAnswer == correctAnswers[currentQuestion]) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Correct!");
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Wrong!");
}
delay(2000); // Show feedback for 2 seconds
isAnswerSelected = false; // Reset the flag to select the next answer
// Move to next question
currentQuestion++;
if (currentQuestion >= sizeof(questions) / sizeof(questions[0])) {
currentQuestion = 0; // Restart the trivia game after all questions have been answered
}
// Display next question
displayQuestion(currentQuestion);
}