Arduino motor and ultrasonic

Hello, I recently bought an Arduino kit for the first time and I wanted to do a project with my friend,
a Carnivorous plant specifically. But sometimes the motor goes a bit then stops then goes to its original position instead of going 120 degrees then staying in that position for 5 seconds and then going back to the original position. Here is the code:

#include <Servo.h>
int servoPin=10;
int echoPin=9;
int trigPin=8;
Servo myServo;
long distance;
long duration;
void setup(){
  Serial.begin(9600);
  myServo.attach (servoPin);
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);
}
void loop (){
 digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   distance = duration* 0.034 / 2;
   Serial.print("Distance: ");
  Serial.println(distance);
  myServo.write(80);
  delay(100);
 if(distance <=4 && distance !=0) {
     myServo.write(120);
     Serial.print(distance);
     delay(5000); 
  }
  
}

Did you ever write separate test sketches for the ultrasonic and the servo, to see which one is creating the problem?

What do the serial debug prints in your program tell you, when you run it? Do the values differ when the undesirable behaviour happens?

I only tried for the ultrasensor and the values differ when the strange behavior happens for example:
Normally:Distance: 2
2Distance: 48
Strange:Distance: 4
4Distance: 0
I'm a beginner this is my first time using Arduino software so I may not understand every term

The way you've structured your serial debug prints, makes it difficult to troubleshoot. I suggest a more verbose print out. Keep different events on different lines and label everything.

It's a little odd to tell the servo to go to 80 a tenth of a second before you tell it to go to 120. If you use the 'else' feature of the 'if' statement you can avoid jerking the servo.

  if (distance <=4 && distance != 0) 
  {
     myServo.write(120);
     Serial.print(distance);
     delay(5000); 
  }
  else
  {
    myServo.write(80);
    delay(100);
  }

Thank you, that was the problem, now it's working without any issues.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.