#include <avr/sleep.h>
#include <avr/interrupt.h>
#include "pitches.h"
const byte buttonPins[] = {1, 2, 3, 4};
const byte SPEAKER_PIN = 0;
const byte MAX_GAME_LENGTH = 100;
int gameTones[] = { NOTE_G3, NOTE_C4, NOTE_E4, NOTE_G5};
byte gameSequence[MAX_GAME_LENGTH] = {0};
byte gameIndex = 0;
void setup() {
randomSeed(analogRead(1));
ADCSRA = 0; // Disable ADC
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
for (int i = 0; i < 4; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
pinMode(SPEAKER_PIN, INPUT);
}
ISR(PCINT0_vect) {
// Disable pin change interrupts here for your specific microcontroller
PCMSK1 &= ~(1 << PCINT0); // Пример: отключить прерывание на PCINT0
sleep_disable();
}
void sleep() {
sleep_enable();
noInterrupts();
// Включите прерывания по изменению состояния для ваших конкретных пинов
for (byte i = 0; i < 4; i++) {
PCMSK1 |= (1 << buttonPins[i]);
}
interrupts();
sleep_cpu();
}
void beep(unsigned char speakerPin, int frequencyInHertz, long timeInMilliseconds) {
long delayAmount = 1000000 / frequencyInHertz;
long loopTime = (timeInMilliseconds * 1000) / (delayAmount * 2);
pinMode(speakerPin, OUTPUT);
for (long x = 0; x < loopTime; x++) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(delayAmount);
digitalWrite(speakerPin, LOW);
delayMicroseconds(delayAmount);
}
pinMode(speakerPin, INPUT);
}
void lightLedAndPlaySound(byte ledIndex) {
pinMode(buttonPins[ledIndex], OUTPUT);
digitalWrite(buttonPins[ledIndex], LOW);
beep(SPEAKER_PIN, gameTones[ledIndex], 300);
pinMode(buttonPins[ledIndex], INPUT_PULLUP);
}
void playSequence() {
for (int i = 0; i < gameIndex; i++) {
lightLedAndPlaySound(gameSequence[i]);
delay(50);
}
}
byte readButton() {
while (true) {
for (int i = 0; i < 4; i++) {
if (digitalRead(buttonPins[i]) == LOW) {
return i;
}
}
sleep();
}
}
void playButtonTone(byte buttonIndex) {
beep(SPEAKER_PIN, gameTones[buttonIndex], 150);
while (digitalRead(buttonPins[buttonIndex]) == LOW);
delay(50);
}
void gameOver() {
gameIndex = 0;
delay(200);
beep(SPEAKER_PIN, NOTE_DS5, 300);
beep(SPEAKER_PIN, NOTE_D5, 300);
beep(SPEAKER_PIN, NOTE_CS5, 300);
for (int i = 0; i < 200; i++) {
beep(SPEAKER_PIN, NOTE_C5 + (i % 20 - 10), 5);
}
delay(500);
}
void checkUserSequence() {
for (int i = 0; i < gameIndex; i++) {
byte expectedButton = gameSequence[i];
byte actualButton = readButton();
playButtonTone(actualButton);
if (expectedButton != actualButton) {
gameOver();
return;
}
}
}
void levelUp() {
beep(SPEAKER_PIN, NOTE_E4, 150);
beep(SPEAKER_PIN, NOTE_G4, 150);
beep(SPEAKER_PIN, NOTE_E5, 150);
beep(SPEAKER_PIN, NOTE_C5, 150);
beep(SPEAKER_PIN, NOTE_D5, 150);
beep(SPEAKER_PIN, NOTE_G5, 150);
}
void loop() {
if (gameIndex < MAX_GAME_LENGTH) {
gameSequence[gameIndex++] = random(0, 4);
playSequence();
checkUserSequence();
delay(300);
if (gameIndex > 0) {
levelUp();
delay(300);
}
}
}