// Buzzer pin
#define BUZZER_PIN 11
// LED connection pins
int ledPins[] = { 2, 3, 4, 5 };
// Button connection pins
int buttonPins[] = { 6, 7, 8, 9 };
String colors[] = { "Red", "Green", "Blue", "Yellow" };
int delayTime = 1000;
int currentLevel = 1;
String currentCode = "";
String userCode = "";
void setup() {
pinMode(BUZZER_PIN, OUTPUT);
// Set LED pins as output
for (int i = 0; i < sizeof(ledPins) / sizeof(ledPins[0]); i++) {
pinMode(ledPins[i], OUTPUT);
}
// Set button pins as input with pull-up resistor
for (int i = 0; i < sizeof(buttonPins) / sizeof(buttonPins[0]); i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
Serial.begin(9600);
Serial.println("LEVEL - " + String(currentLevel));
}
void loop() {
if (currentCode == "") {
currentCode = generateRandomCode();
displayCode(currentCode);
}
if (getUserInput()) {
if (userCode == currentCode) {
Serial.println("Correct!");
currentLevel++;
delayTime -= 100;
if (delayTime < 10) {
delayTime = 100;
}
currentCode = "";
userCode = "";
delay(1000);
} else {
Serial.println("Incorrect! Try again.");
playErrorSound();
userCode = "";
}
Serial.println("LEVEL - " + String(currentLevel));
}
}
String generateRandomCode() {
String code = "";
int lastPin = -1;
for (int i = 0; i < 4; i++) {
int newPin;
do {
newPin = random(0, 4); // Generate a random number between 0 and 3
} while (newPin == lastPin); // Keep generating until we get a different color
code += String(newPin);
lastPin = newPin;
}
return code;
}
void displayCode(String code) {
for (int i = 0; i < code.length(); i++) {
int pin = code.charAt(i) - '0';
digitalWrite(ledPins[pin], HIGH);
tone(BUZZER_PIN, 5 * (pin + 2));
delay(10);
noTone(BUZZER_PIN);
delay(delayTime);
digitalWrite(ledPins[pin], LOW);
}
}
boolean getUserInput() {
for (int i = 0; i < sizeof(buttonPins) / sizeof(buttonPins[0]); i++) {
if (digitalRead(buttonPins[i]) == LOW) {
userCode += String(i);
playButtonSound(i);
delay(200);
while (digitalRead(buttonPins[i]) == LOW) {}
}
}
return userCode.length() == currentCode.length();
}
void playButtonSound(int buttonIndex) {
tone(BUZZER_PIN, 5 * (buttonIndex + 2));
delay(10);
noTone(BUZZER_PIN);
}
void playErrorSound() {
tone(BUZZER_PIN, 100);
delay(1000);
noTone(BUZZER_PIN);
}