Arduino car

Ok I have this arduino powered autonomis car. It uses a Sharp proximity sensor. It runs well when it does not sense anyting but when i put my hand near it sometimes is turns but other times it stops and the motor moves a tiny bit and then it stops. 

Here is a video ..... http://www.youtube.com/watch?v=qrxh59XDGT8&feature=youtu.be

Side comments

when it stops the tx and rx lights on the arduino are flashing (simmilar to when it finds an object). After a while (a minute or two... or sometimes never - have to restart it) when it continues going strait it stops blinking.

 

this is my code

 

int d1a=13;

int d2a= 12;

int s1= 10;

int d1b=11;

int d2b=8;

int sb=9;

int sensorPin = 5;

void setup () {  

 

  pinMode (d1a, OUTPUT);

  pinMode (d2a, OUTPUT);

  pinMode (s1, OUTPUT);

  pinMode (d1b, OUTPUT);

  pinMode (d2b, OUTPUT);

  pinMode (sb, OUTPUT);

}

void loop () {

  int val= analogRead (sensorPin);

 

    if (val > 520) {

     analogWrite (s1, 255);

digitalWrite (d1a , HIGH);

digitalWrite (d2a, LOW);

analogWrite (sb, 255);

digitalWrite (d1b , HIGH);

digitalWrite (d2b, LOW);

delay (1500);

      analogWrite (s1, 190);

digitalWrite (d1a , HIGH);

digitalWrite (d2a, LOW);

analogWrite (sb, 190);

digitalWrite (d1b , LOW);

digitalWrite (d2b, HIGH);

  delay (1000);

 

    }

    else {

        analogWrite (s1, 200);

digitalWrite (d1a ,LOW);

digitalWrite (d2a, HIGH);

analogWrite (sb, 200);

digitalWrite (d1b , LOW);

digitalWrite (d2b, HIGH);

    }

}

another suggestion

If you would put your motor commands in functions, you code would be easier to read.

Instead of your if (val > 520) { … }

You could:

if (val > 520) {
   reverse(255);
   delay(1500);
   right(190);
   delay(1000);
}

Now outside of the closed brace ‘}’ of the loop() function you add:

void reverse(int speed) {
    analogWrite (s1, speed);
    digitalWrite (d1a , HIGH);
    digitalWrite (d2a, LOW);
    analogWrite (sb, speed);
    digitalWrite (d1b , HIGH);
    digitalWrite (d2b, LOW);
}

make functions for forward, right, and, left. Now when anyone looks at your code, they can immediately see what is supposed to be happening instead of getting bogged down in the low level pin read and writes. :) 

**Didnt know about that **

That is cool tanks bird