Unit 22: Proximity Sweep

 

 

 

Code:



#include 

// Pin definitions
const int trigPin = 9;
const int echoPin = 10;
const int buzzerPin = 11;
const int servoPin = 6;

// Timing variables
const long movementDelay = 10000; // 10 seconds of allowed movement
unsigned long startTime;

// Sensitivity control
const int numSamples = 5; // Number of samples to average
const int distanceThreshold = 50; // Distance threshold in cm

// Servo movement control
Servo myServo; // Create servo object
const int servoMin = 0;   // Minimum servo angle
const int servoMax = 180; // Maximum servo angle
const int servoStep = 2;  // Step size for the servo movement
int currentAngle = servoMin;
bool movingForward = true; // To control servo movement direction

void setup() {
  // Initialize pin modes
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(buzzerPin, OUTPUT);
  
  // Start with the buzzer off
  digitalWrite(buzzerPin, LOW);

  myServo.write(servoMax);
delay(1000);
myServo.write(servoMin);
  
  // Initialize servo
  myServo.attach(servoPin);
  myServo.write(servoMin); // Start at 0 degrees
  
  // Record the start time
  startTime = millis();
}

void loop() {
  // Allow movement for the first 10 seconds before starting the servo
  if (millis() - startTime > movementDelay) {
    moveServoWithSensor(); // Move the servo with the sensor attached
  }
  delay(500); // Small delay between readings
}
// Function to move the servo in an arc and read sensor data
void moveServoWithSensor() {
  long distance = getAverageDistance(); // Get averaged distance reading

  if (distance < distanceThreshold) { // If object is closer than threshold
    digitalWrite(buzzerPin, HIGH); // Sound the alarm
  } else {
    digitalWrite(buzzerPin, LOW); // No alarm
  }

  // Move the servo in an arc
  if (movingForward) {
    currentAngle += servoStep;
    if (currentAngle >= servoMax) {
      movingForward = false;
    }
  } else {
    currentAngle -= servoStep;
    if (currentAngle <= servoMin) {
      movingForward = true;
    }
  }
  myServo.write(currentAngle); // Move the servo to the new angle
  delay(20); // Small delay to slow down the servo movement
}
// Function to get averaged distance from multiple readings
long getAverageDistance() {
  long totalDistance = 0;

  for (int i = 0; i < numSamples; i++) {
    long duration, distance;

    // Send a pulse to trigger the sensor
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    // Read the echo pin and convert the time into distance
    duration = pulseIn(echoPin, HIGH);
    distance = (duration * 0.0343) / 2; // in cm

    totalDistance += distance;
    delay(50); // Small delay between samples
  }
  return totalDistance / numSamples; // Return the averaged distance
}


  

  

 

Notes: