Hello.
I have build a simple robot with two gearmotors and a ping sensor on top of a servo, but I am not sure how I should make the code if I want a servo to do a sweep when it detects an object infront of it. And perhaps store a value for when it is turned right and left, so it can decide weather it should go right/left or backwards.
I appreciate all answers very much ![]()
Thank you.
Here is the code i made for it to simply turn left if it detects an object.
const int pingPin = 3;
int ledPin = 5;
int motor1A = 10;
int motor1B = 11;
int enable1 = 7;
int motor2A = 8;
int motor2B = 9;
int enable2 = 6;
float dist = 0;
float Val;
void straight()
{
digitalWrite(enable1, HIGH);
digitalWrite(motor1A, HIGH);
digitalWrite(motor1B, LOW);
digitalWrite(enable2, HIGH);
digitalWrite(motor2A, HIGH);
digitalWrite(motor2B, LOW);
}
void turnLeft()
{
 digitalWrite(enable1, HIGH);
 digitalWrite(motor1A, LOW);
 digitalWrite(motor1B, HIGH);
 digitalWrite(enable2, HIGH);
 digitalWrite(motor2A, HIGH);
 digitalWrite(motor2B, LOW);
}Â
float distCalc()
{
 long duration, cm;
Â
 pinMode(pingPin, OUTPUT);
 digitalWrite(pingPin, LOW);
 delayMicroseconds(2);
 digitalWrite(pingPin, HIGH);
 delayMicroseconds(5);
 digitalWrite(pingPin, LOW);
Â
 pinMode(pingPin, INPUT);
 duration = pulseIn(pingPin, HIGH);
Â
 cm = microsecondsToCentimeters(duration);
}Â
 long microsecondsToCentimeters(long microseconds)
  {
   dist = (microseconds / 29 / 2);
   return dist;
  }
Â
void wall()
{
 if(dist < 35)
 {
  turnLeft();
  delay(100);
 }Â
Â
 else
 {
  straight();
 }Â
}Â Â
Â
Â
void led()
{
 if(dist > 35)
 {
  digitalWrite(ledPin, LOW);
  delay(100);
 }
 else
 {
  digitalWrite(ledPin, HIGH);
  delay(100);
 }
}
void setup()
{
 pinMode(ledPin, OUTPUT);
 pinMode(motor1A, OUTPUT);
 pinMode(motor1B, OUTPUT);
 pinMode(motor2A, OUTPUT);
 pinMode(motor2B, OUTPUT);
Â
Â
 straight();
Â
Â
Â
}
void loop()
{
 digitalWrite(pingPin, HIGH);
 distCalc();
 wall();
 led();
 delay(20);
}