Hello, I’m working on a robotics project and my servos are twitching and not working with this code. However, it works great with servo sweep’s code. Plus my ultrasonic sensor won’t make the servos go the other way, but I’m getting measurements. Could someone help me with my code?
[#include <AFMotor.h>
#include<Servo.h>
#include<SR04.h>
#define trigpin A0 // Trigger pin
#define echopin A1 // echo pin
float duration, distance;
Servo myservo1; // Left leg
Servo myservo2; // Right leg
int pos0 = 0;
int pos1= 100;
int pos2 = 90;
int pos3 = 80;
void setup() {
Serial.begin(9600);
myservo1.attach(9);
myservo2.attach(10);
myservo1.write(pos0);
myservo2.write(pos0);
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("cm");
delay(100);
myservo1.write(pos3);
delay(400);
myservo1.write(pos2);
delay(400);
myservo2.write(pos3);
delay(400);
myservo2.write(pos2);
delay(400);
if (distance <= 10)
{
Serial.print("distance is less than or equal to");
myservo1.write(pos1);
delay(400);
myservo1.write(pos2);
delay(400);
myservo2.write(pos1);
delay(400);
myservo2.write(pos2);
delay(400);
}
}
/code]