1

作者 by 超米 / 2024-09-12 / 暂无评论 / 62 个足迹

  void loop() {
  
    int angle = 0; // Initial angle for the servo.
    int i = 5; // Increment angle by this amount each loop.
    int num = 0; // Counter for alarm conditions.
  
    // Rotate the servo from 0 to 180 degrees.
    for (angle = 0; angle <= 180; angle += i) {
      num = report(angle);
      delay(100); // Delay to allow the servo to move smoothly.
    }
  
    // Rotate the servo back from 180 to 0 degrees.
    for (angle = 180; angle >= 0; angle -= i) {
      num = report(angle);
      delay(100); // Delay to allow the servo to move smoothly.
    }
  
    // If the system triggered an alarm, keep monitoring until the distance is safe.
    if (num == 1) {
      Serial.println("ALARM: Intruder too close, monitoring...");
      while (1) {
        angle = 90; // Point the sensor straight ahead.
        myservo.write(angle);
        int dis1_fun = distance();
        int v_fun = 0;
        int dis_minfun = abs(sin(angle * PI / 180) * dis1_fun);
        if ((v_fun > 20) && (dis_minfun <= 10)) {
          // Keep monitoring, object still too close.
          delay(100);
        } else {
          // Object is no longer a threat, stop alarm.
          digitalWrite(buzzpin, LOW);
          Serial.println("Safe distance restored.");
          break;
        }
      }
    }
    
    delay(500); // A delay before starting the next cycle to avoid continuous rapid firing.
  }

独特见解