#include <Stepper.h>

const int trigPin = 9; // Trigger pin for HC-SR04
const int echoPin = 10; // Echo pin for HC-SR04

const int motorPin1 = 2; // IN1 for 28BYJ stepper motor
const int motorPin2 = 3; // IN2 for 28BYJ stepper motor
const int motorPin3 = 4; // IN3 for 28BYJ stepper motor
const int motorPin4 = 5; // IN4 for 28BYJ stepper motor

Stepper stepper(512, motorPin1, motorPin3, motorPin2, motorPin4); // 28BYJ has 512 steps per revolution

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  stepper.setSpeed(10); // Set the motor speed (adjust as needed)
}

void loop() {
  long duration, distance;

  // Trigger the HC-SR04 to measure distance
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Measure the echo time to calculate distance
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;

  Serial.print("Distance: ");
  Serial.println(distance);

  // If an obstacle is detected within a certain range, dispense food
  if (distance < 10) {
    dispenseFood();
    delay(1000); // Wait for stability, adjust as needed
  }
}

void dispenseFood() {
  // Rotate the stepper motor by 2 steps
  stepper.step(200);
  delay(1000); // Adjust delay based on your specific mechanism and requirements
  // Stop the stepper motor
  stepper.step(0);
}
