Saturday, 29 February 2020

Arduino based Car controlled/programmed by Android



Components:
1. Arduino Uno
2. HC-05 bluetooth
3. L293D shield
4. Android phone
5. Connecting wires

Do connections as shown below,



Arduino Code:

#include<SoftwareSerial.h>
#define m1_p 10
#define m1_n 11
#define m2_p 12
#define m2_n 13
#define TxD 9
#define RxD 8
String str = "0";
SoftwareSerial bluetoothSerial(RxD, TxD);

void setup() {
  pinMode(m1_p, OUTPUT);
  pinMode(m1_n, OUTPUT);
  pinMode(m2_p, OUTPUT);
  pinMode(m2_n, OUTPUT);
  bluetoothSerial.begin(38400);
  Serial.begin(9600); // Default communication rate of the Bluetooth module
}
void loop() {
  if(bluetoothSerial.available() > 0){ // Checks whether data is comming from the serial port
    str = bluetoothSerial.readString(); // Reads the data from the serial port
    //Serial.println("123");
   worker(str);
 }



void worker(String str) {
  for(int i=0;i<str.length();i=i+2){
    char action = str[i+1];
    int timing = int(str[i]- '0');
 //   Serial.println(timing);
//    Serial.println(action);
//    Serial.println(timing);
//    Serial.println(i);
    if(action=='F') {
      //put motor functions here
  //    Serial.println("front");
      motor(1,0,1,0,timing);
    }
    else if(action=='B') {
   //   Serial.println("back");
      motor(0,1,0,1,timing);
    }
     else if(action=='L') {
   //   Serial.println("left");
      motor(1,0,0,1,timing);
    }
     else if(action=='R') {
   //   Serial.println("right");
      motor(0,1,1,0,timing);
    }
     else if(action=='(') {
  //    Serial.println("loop");
      int j=0;
      int rec_e=str.indexOf(')');
      String sub = str.substring(i+2,rec_e);
      
      while(j<timing) {
   //     Serial.println(sub);
        worker(sub);
        j=j+1;
      }
      i=i+rec_e-2;
    }
    else if(action=='S') {
   //   Serial.println("stop");
       motor(0,0,0,0,timing);
    }
  }
}

void motor(int p1, int n1, int p2, int n2,int timing) {
  if(timing == 0) {
    digitalWrite(m1_p,p1);
    digitalWrite(m1_n,n1);
    digitalWrite(m2_p,p2);
    digitalWrite(m2_n,n2);
  }
  else {
    digitalWrite(m1_p,p1);
    digitalWrite(m1_n,n1);
    digitalWrite(m2_p,p2);
    digitalWrite(m2_n,n2);
    delay(timing*1000);
    digitalWrite(m1_p,0);
    digitalWrite(m1_n,0);
    digitalWrite(m2_p,0);
    digitalWrite(m2_n,0);
   }
}


Android APK:  link
Make sure you pair the bluetooth before opening the app, the bluetooth module name must be "HC-05" and baud rate should be 38400 in order to make this app work with arduino/bluetooth.

To know how to configure Bluetooth check here

No comments:

Post a Comment