fbpx

4.4 Coding


 

Steps to do coding in Arduino IDE

1. Open Arduino IDE and start writing the code.

Complete Code:

In our project, we used 3 ldr, so connect the 3 ldr’s one in front of the robot, others in left and right. check whether the project or 3 ldr’s are working correctly. To check, close 2 ldr and see if other ldr show higher value or the other 2 closed ldr’s show less value.When the light falls on any LDR then the that LDR will vary from the other two and so as per the condition our car will run.

Code as shown below:

int input1leftmotor=10;

int input2leftmotor=9;

int input3rightmotor=8;

int input4rightmotor=7;

int ldr1center=A0;

int ldr2left=A1;

int ldr3right=A2;

void setup() {

pinMode(input1leftmotor, OUTPUT);

pinMode(input2leftmotor, OUTPUT);

pinMode(input3rightmotor, OUTPUT);

pinMode(input4rightmotor, OUTPUT);

pinMode(ldr1center, INPUT);

pinMode(ldr2left, INPUT);

pinMode(ldr3right, INPUT);

delay(2000);

Serial.begin(9600);

}

void loop() {

int value1=analogRead(ldr1center);

int value2=analogRead(ldr2left);

int value3=analogRead(ldr3right);

if (value1>value2&&value1>value3) {

straight();

delay(1000);

Serial.println(“straight”);

}

else if (value2>value1&&value2>value3) {

left();

Serial.println(“left”);

delay(600);

}

else if (value3>value1&&value3>value2) {

right();

delay(600);

Serial.println(“right”);

}

}

void straight(){

digitalWrite(input1leftmotor,HIGH);

digitalWrite(input2leftmotor,LOW);

digitalWrite(input3rightmotor,HIGH);

digitalWrite(input4rightmotor,LOW);

}

void left(){

digitalWrite(input1leftmotor,LOW);

digitalWrite(input2leftmotor,LOW);

digitalWrite(input3rightmotor,HIGH);

digitalWrite(input4rightmotor,LOW);

}

void right(){

digitalWrite(input1leftmotor,HIGH);

digitalWrite(input2leftmotor,LOW);

digitalWrite(input3rightmotor,LOW);

digitalWrite(input4rightmotor,LOW);

}

Note: All lines written in “// ” are comments which will not run with the code that is just to understand the statements written in the code.