Загрузка данных


#include <Servo.h>

const int TRIG_PIN = 9;
const int ECHO_PIN = 10;
const int SERVO_PIN = 11;
const int BUZZER_PIN = 8;

const int ALARM_DISTANCE = 40; // Дистанция срабатывания в см

Servo radarServo;

// Функция замера дистанции
int getDistance() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Таймаут 25 мс (~4 метра максимум)
  long duration = pulseIn(ECHO_PIN, HIGH, 25000);
  if (duration == 0) return 999; // Если эхо не вернулось
  
  return duration * 0.0343 / 2;
}

// Проверка расстояния и управление звуком
void checkAlarm() {
  int distance = getDistance();
  
  if (distance > 0 && distance <= ALARM_DISTANCE) {
    tone(BUZZER_PIN, 1000); // Сигнал 1000 Гц при обнаружении
  } else {
    noTone(BUZZER_PIN);
  }
}

void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(BUZZER_PIN, OUTPUT);

  radarServo.attach(SERVO_PIN);
  radarServo.write(0);
  delay(500);
}

void loop() {
  // Сканирование от 0° до 180°
  for (int pos = 0; pos <= 180; pos += 2) {
    radarServo.write(pos);
    checkAlarm();
    delay(25);
  }

  // Обратный ход от 180° до 0°
  for (int pos = 180; pos >= 0; pos -= 2) {
    radarServo.write(pos);
    checkAlarm();
    delay(25);
  }
}