Arduino robot (Pi-bot) doing a light sensor run - Arduino code included

192 views · Published 16 November 2017 · 0:41 · Indexed 8 November 2026

Channel: Engel Universe · 2017 · Science & Technology

Watch on YouTube

It has 3 light sensors in the front and this code was written for the left and right one. When it senses dark it turns away from it. Here is the Arduino code that we used to program it:

/*
Line following using one sensor. We will be using the center sensor.
This is a basic wiggler algorithm.
*/

const int Line1 = 7;     // Left Line Sensor
//const int Line2 = 8;     // Center Line Sensor
const int Line3 = 10;     // Right Line Sensor

const int In1 = 3;      // In1
const int In2 = 5;      // In2
const int In3 = 6;     // In3
const int In4 = 11;     // In4
int speed1;
int speed2;
const int fast=100;
const int slow=0;
  int L1;
  //int L2;
  int L3;

void setup() 
{
  // initialize the pins
  pinMode(In1, OUTPUT);
  pinMode(In2, OUTPUT);
  pinMode(In3, OUTPUT);
  pinMode(In4, OUTPUT); 
  pinMode(Line1, INPUT); 
  //pinMode(Line2, INPUT); 
  pinMode(Line3, INPUT); 
  Serial.begin(9600);
  }

void loop()
{

    L1 = digitalRead(Line1);
    //L2 = digitalRead(Line2);
    L3 = digitalRead(Line3);
    Serial.print(L1);
    Serial.print(", ");
   // Serial.print(L2);
   // Serial.print(", ");
    Serial.println(L3); 
    
    if (L1 == 0 & L3 ==0 )
    {
      //Left and Right sensors see white
      //This means black line is in between the two sensors
      //Go forward
      speed1=fast;
      speed2=fast;
      forward(speed1, speed2);
    }
    else if (L1 == 0 & L3 == 1)
    {
      //Left sees white and right sess black
      //Turn right
      speed1=slow;
      speed2=fast;
      forward(speed1, speed2);
     }
     else if (L1 == 1 & L3 ==0)
     {
     //Left sess black and right sees white
     //Turn right
     speed1 = fast;
     speed2 = slow;
     forward(speed1, speed2);
     }
     else if (L1 == 1 & L3 == 1)
     {
      // both sensors see black. End of the course
      //Stop now
      stopNow();
     }
  
    
}

void forward (int speed1, int speed2)
{
analogWrite(In4, 0);
analogWrite(In3, speed1);
analogWrite(In2, 0);
analogWrite(In1, speed2);
return;
}
void stopNow()
{
  analogWrite(In4, 0); 
  analogWrite(In3, 0); 
  analogWrite(In2, 0); 
  analogWrite(In1, 0);
  return;
}

More from this channel