#include <Stepper.h>
// Define the pins for the sensors, LEDs, and buttons
const int trigPin1 = 2;
const int echoPin1 = 3;
const int trigPin2 = 4;
const int echoPin2 = 5;
const int pinkLEDPin = 6;
const int blueLEDPin = 7;
const int stepPin = 8; // Step pin for the stepper motor
const int dirPin = 9; // Direction pin for the stepper motor
const int buttonOnPin = 10; // Button to toggle the stepper motor on
const int buttonOffPin = 11; // Button to stop the stepper motor
const int stepsPerRevolution = 200; // Adjust this value based on your stepper motor
// Initialize the stepper library
Stepper stepper(stepsPerRevolution, dirPin, stepPin);
// State of the stepper motor
bool motorRunning = false;
void setup() {
// Initialize the LED pins as outputs
pinMode(pinkLEDPin, OUTPUT);
pinMode(blueLEDPin, OUTPUT);
// Initialize button pins as inputs with internal pull-up resistors enabled
pinMode(buttonOnPin, INPUT_PULLUP);
pinMode(buttonOffPin, INPUT_PULLUP);
// Initialize the HC-SR04 sensor pins
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
// Setup stepper motor
stepper.setSpeed(60); // Set the speed to 60 RPM
}
void loop() {
long distance1 = measureDistance(trigPin1, echoPin1);
long distance2 = measureDistance(trigPin2, echoPin2);
// Define the threshold distance for sensor detection
const int thresholdDistance = 30; // distance in centimeters
// Sensor1 detection actions
if (distance1 <= thresholdDistance) {
digitalWrite(pinkLEDPin, HIGH);
digitalWrite(blueLEDPin, HIGH);
delay(3000); // Blue LED on for 3 seconds
digitalWrite(blueLEDPin, LOW);
}
// Sensor2 detection actions
if (distance2 <= thresholdDistance) {
digitalWrite(pinkLEDPin, LOW);
}
// Toggle the state of the motor with the ON button
static bool lastOnButtonState = HIGH;
bool currentOnButtonState = digitalRead(buttonOnPin);
if (currentOnButtonState == LOW && lastOnButtonState == HIGH) {
motorRunning = !motorRunning;
}
lastOnButtonState = currentOnButtonState;
// Check if motor should be running
if (motorRunning) {
stepper.step(stepsPerRevolution / 4); // Steps a quarter revolution
}
// Stop the motor with the OFF button
if (digitalRead(buttonOffPin) == LOW) {
motorRunning = false;
}
}
// Function to measure distance using HC-SR04
long measureDistance(int trigPin, int echoPin) {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
return duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and return)
}