const int carRed = 2;
const int carYellow = 3;
const int carGreen = 4;
const int pedRed = 5;
const int pedGreen = 6;
const int buzzer = 7;
const int dataPin = 8;
const int clockPin = 9;
const int latchPin = 10;
// 7-сегментные коды (Common Anode)
const byte digits[10] = {
0B11000000, // 0
0B11111001, // 1
0B10100100, // 2
0B10110000, // 3
0B10011001, // 4
0B10010010, // 5
0B10000010, // 6
0B11111000, // 7
0B10000000, // 8
0B10010000 // 9
};
unsigned long previousMillis = 0;
int countdown = 0;
bool blinkState = false;
void setup() {
pinMode(carRed, OUTPUT);
pinMode(carYellow, OUTPUT);
pinMode(carGreen, OUTPUT);
pinMode(pedRed, OUTPUT);
pinMode(pedGreen, OUTPUT);
pinMode(buzzer, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(latchPin, OUTPUT);
digitalWrite(carRed, HIGH);
digitalWrite(pedRed, HIGH);
}
void loop() {
phase1(); // 9s Красный (авто) - Зеленый (пешеходы)
phase2(); // 3s Красный+Желтый (авто) - Мигающий зеленый
phase3(); // 9s Зеленый (авто) - Красный (пешеходы)
phase4(); // 3s Желтый (авто) - Красный (пешеходы)
}
void phase1() {
setLights(HIGH, LOW, LOW, LOW, HIGH);
runPhase(9, 9000);
}
void phase2() {
setLights(HIGH, HIGH, LOW, LOW, HIGH); // Красный+Желтый (авто) - Зеленый (пешеходы)
blinkGreen(3, 3000); // Мигающий зеленый (пешеходы) в течение 3 секунд
}
void phase3() {
setLights(LOW, LOW, HIGH, HIGH, LOW);
runPhase(9, 9000);
}
void phase4() {
setLights(LOW, HIGH, LOW, HIGH, LOW);
runPhase(3, 3000); //Добавил таймер и обратный отсчет в фазу 4
}
void runPhase(int startCount, unsigned long duration) {
unsigned long start = millis();
countdown = startCount;
previousMillis = start;
while (millis() - start < duration) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= 1000) {
previousMillis = currentMillis;
if (countdown >= 0) {
updateDisplay(countdown);
soundAlert(countdown);
countdown--;
}
}
}
}
void blinkGreen(int blinks, unsigned long duration) {
unsigned long blinkInterval = duration / (blinks * 2); // Рассчитываем длительность одного мигания (вкл/выкл)
unsigned long start = millis();
while (millis() - start < duration) {
digitalWrite(pedGreen, HIGH);
delay(blinkInterval);
digitalWrite(pedGreen, LOW);
delay(blinkInterval);
}
}
void setLights(bool carR, bool carY, bool carG, bool pedR, bool pedG) {
digitalWrite(carRed, carR);
digitalWrite(carYellow, carY);
digitalWrite(carGreen, carG);
digitalWrite(pedRed, pedR);
digitalWrite(pedGreen, pedG);
}
void updateDisplay(int num) {
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, digits[num]); // Corrected: Use num directly
digitalWrite(latchPin, HIGH);
}
void soundAlert(int cnt) {
int freq = map(cnt, 0, 9, 2000, 500);
int dur = map(cnt, 0, 9, 50, 200);
tone(buzzer, freq, dur);
delay(50);
noTone(buzzer);
}