fbpx

5.4 Coding

 


Steps to do coding in Arduino IDE

1. Open Arduino IDE and write the code.

Complete Code:

In the code, we are reading data from the bluetooth and using the data we set the conditions to move the car.

  • data=1, then the car will move forward.
  • data=2, then the car will move backward.
  • data=3, then the car will move in left direction.
  • data=4, then the car will move in right direction.
  • and if there is any other data then the car will not move.

Code as mentioned below:

int m1=9;
int m2=10;
int m3=11;
int m4=12;

char data=0;
void setup()
{

Serial.begin(9600);
pinMode(m1,OUTPUT);
pinMode(m2,OUTPUT);
pinMode(m3,OUTPUT);
pinMode(m4,OUTPUT);

}

void loop()

{
if(Serial.available()>0)
{
data=Serial.read();
Serial.println(data);

if( data ==’1′)//forward

{

digitalWrite(m1,HIGH);
digitalWrite(m2,LOW);
digitalWrite(m3,HIGH);
digitalWrite(m4,LOW);
}

else if(data == ‘2’)//backward
{
digitalWrite(m1,LOW);
digitalWrite(m2,HIGH);
digitalWrite(m3,LOW);
digitalWrite(m4,HIGH);
}

else if(data == ‘3’)//left
{

digitalWrite(m1,LOW);
digitalWrite(m2,HIGH);
digitalWrite(m3,HIGH);
digitalWrite(m4,LOW);

}

else if(data ==’4′)//right
{
digitalWrite(m3,LOW);
digitalWrite(m4,HIGH);
digitalWrite(m1,HIGH);
digitalWrite(m2,LOW);

}
else//stop
{

digitalWrite(m1,LOW);
digitalWrite(m2,LOW);
digitalWrite(m3,LOW);
digitalWrite(m4,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.