I am using a PA-18 Linear Actuator, Arduino uno, MD10C R3, and an ultrasonic sensor. Currently the code works when moving the linear actuator forward and backwards but it does not stop at the distance I want it to. Can anyone help fix this to only move forward 30 inches and backward 30 inches when the ultrasonic sensor is triggered?
const int motorPowerPin = 3; // power pin of MD
const int motorDirectionPin = 4; // direction pin of MD
const int trigPin = 10; // trigger pin of ultrasonic sensor
const int echoPin = 11; // echo pin of ultrasonic sensor
const int maxDistance = 100; // Max distance for the ultrasonic sensor
int triggerCount = 0;
void setup() {
pinMode(motorPowerPin, OUTPUT);
pinMode(motorDirectionPin, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Stop the motor initially
digitalWrite(motorPowerPin, LOW);
}
void loop() {
// Measure distance with the ultrasonic sensor
int distance = getDistance();
// Check if the distance is less than a threshold (detecting an object)
if (distance < maxDistance) {
if (triggerCount == 0) {
// First trigger - Move forward 30 inches
moveLinearActuator(30);
triggerCount++;
} else if (triggerCount == 1) {
// Second trigger - Move backward 30 inches
moveLinearActuator(-30);
triggerCount++;
}
}
}
int getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
return pulseIn(echoPin, HIGH) * 0.034 / 2;
}
void moveLinearActuator(int distance) {
if (distance > 0) {
// Set the motor direction for forward
digitalWrite(motorDirectionPin, HIGH);
} else {
// Set the motor direction for backward
digitalWrite(motorDirectionPin, LOW);
distance = -distance; // Make distance positive for the motor control
}
// Turn on the motor
digitalWrite(motorPowerPin, HIGH);
// Move the linear actuator for the specified distance
delay(distance * 100);
// Turn off the motor
digitalWrite(motorPowerPin, LOW);
analogWrite(powerPin, 255);
}