Hello kind helper!
I'm not that experienced in using a while loop and I think this is the part where my code fails.
I am trying to control two linear actuators with a three pin ultrasonic sensor. The actuators (without position indicator) are connected to a motor controller. What I am trying to accomplish, is when an object comes within a 5 cm range of the sensor, the motors will activate for 100 milliseconds, stop and hold their position until the sensor detects that the object is >= 5 cm's. When this happens the motors should go back to their original position.
What I am struggling with now is that the motors aren't returning to their original position after the sensor detects an object that is >= 5 cm's. I think this problem is caused by the way I update the ultrasonic sensor input in the while loop.
I hope you can help me!
int enA = 5;
int enB = 3;
const int in1 = 8;
const int in2 = 7;
const int in3 = 4;
const int in4 = 2;
const int pingPin = 12;
long previousMillis = 0;
long interval = 1000;
long time;
long startTime = 0;
//change ultrasonic sensor signal to distance
long microsecondsToCentimeters(long microseconds) {
return microseconds / 29 / 2;
}
void setup() {
// initialize serial communication:
Serial.begin(9600);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enA, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
}
}
void loop() {
// Variabele cm
long duration, cm;
time = millis();
// Activate
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
// Signal read
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
// to cm
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
//send pulse
if (cm < 5) {
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
analogWrite(enA, 255);
analogWrite(enB, 255);
delay(100);
//keep position
while (cm < 5){
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
analogWrite(enA, 255);
analogWrite(enB, 255);
cm = microsecondsToCentimeters(duration);
}
}
//Back to original position
if (cm > 5){
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
analogWrite(enA, 255);
analogWrite(enB, 255);
}
}