DIY Robots

Edge Avoiding Bot

Code Section:

   const int lm1 = 2; //Left Motor
   const int lm2 = 3; 
   const int rm1 = 4; // Right Motor
   const int rm2 = 5;

   int trigpin=9;      // Initializing Ultrasonic's trigger pin
   int echopin=8;      // Initializing Ultrasonic's Echo pin
   int dist=0,time=0;  

 void setup()
 {
  pinMode(lm1, OUTPUT); // Setting all the motor pins as OUTPUT
  pinMode(lm2, OUTPUT);
  pinMode(rm1, OUTPUT);
  pinMode(rm2, OUTPUT);
  Serial.begin(9600);  // Begin serial monitor to note down the threshold clearance of table surface
  pinMode(trigpin,OUTPUT); 
  pinMode(echopin,INPUT); 
}

void loop()
{ 
  
  digitalWrite(trigpin,LOW);
  delayMicroseconds(5);
  digitalWrite(trigpin,HIGH);
  delayMicroseconds(5);
  digitalWrite(trigpin,LOW);
  time = pulseIn (echopin,HIGH);
  dist= time/29/2;
  Serial.print(dist);
  Serial.print(" cm"); 
 Serial.println(" \t");
   
  if(dist>4 )
  {
    go_back();
    delay(1000);
    go_left();
    delay(1000);
    go_straight();  
  }
  else
  {
    
    go_straight();
  }
}

void go_straight()
{
  digitalWrite(lm1,HIGH);
  digitalWrite(lm2,LOW);
  digitalWrite(rm1,LOW);
  digitalWrite(rm2,HIGH);
}
void go_back()
{
  digitalWrite(lm1,LOW);
  digitalWrite(lm2,HIGH);
  digitalWrite(rm1,HIGH);
  digitalWrite(rm2,LOW);
}

void go_left()
{
  digitalWrite(lm1,LOW);
  digitalWrite(lm2,LOW);
  digitalWrite(rm1,HIGH);
  digitalWrite(rm2,LOW);
}

/*void go_right()
{
  digitalWrite(lm1,HIGH);
  digitalWrite(lm2,LOW);
  digitalWrite(rm1,LOW);
  digitalWrite(rm2,LOW);
 }
 
*/

 

 

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
Close