Search This Blog

Monday, December 21, 2015

Hooking up SainSmart Motor Shield, Ultrasonic Range Finder with Arduino to Control my Chassis.

Its been long since the last post on the series, a lot has changed since then.

Motors to Motor Shield


I had problems with the right motor shield to use, however i finally settled with the sain smart motor shield, which has its library called AFMotor with a guide at the link on how to set it up.
Once you install in your arduino IDE, all is left is to connect it to your arduino like this:

and then first import the library with some few definitions.

#include 
#define MAX_SPEED 120
#define MIN_SPEED 95

You speed can vary, so make sure you experiment with various speed.
In my case i have 4 motors i want to control, so i hooked up the front motors to M1 and M2 respectively and the back to M3 and M4, then declare the motor instances like this:

 AF_DCMotor motorlf(1);
 AF_DCMotor motorrf(2);
 AF_DCMotor motorlb(3);
 AF_DCMotor motorrb(4);


after this, you will need to put this code in your setup. Setting the speed

   motorlf.setSpeed(MIN_SPEED);
   motorrf.setSpeed(MIN_SPEED);
   motorlb.setSpeed(SLOW_SPEED);
   motorrb.setSpeed(SLOW_SPEED);


then for each motor you can use for example
 motorlf.run(FORWARD);
 motorrf.run(BACKWARD);

The rest is basic programming. Also take not that if you want to turn right, you can set the left wheel to run forward and the right wheel to run backward, the converse for turning left.

Ultrasonic Range Finder


For the sensor, hook up the VCC to arduino board 5v, Gnd to Gnd, Trig to pin 12, echo to pin 13 like in the image above, you can see the 2 wires running into the board at both ends.
Then also define this in your code
 #define trig  12 
 #define echo 13 

and in setup add
   pinMode (trig,OUTPUT);
   pinMode (echo,INPUT);
  // initialize serial communication:
   Serial.begin(9600);  

then in your loop
   digitalWrite(trig, LOW);
   delayMicroseconds(2);
   digitalWrite(trig, HIGH);
   delayMicroseconds(10);
   digitalWrite(trig, LOW);
   duration = pulseIn(echo, HIGH);
   cm = (duration / 2) / 29.1;
    if(cm > 25){

     move_forward();

   }else{
    
     turn_right();
     delay(300);
    
   }

So what this basically does is it sets a low pulse for about 2 microseconds to ensure a clean high pulse for a longer period, set back to low and reads the echo using pulseIn. Thats the duration. You can see the calculation to CM in the code above.
Finally our robot looks like this

Upload your code and start your bot. Anytime it encounters an obstacle less than 25 cm, it turns right, from this you can make even more sophisticated computations.
Check out my Youtube video for detailed explanation. Earn free bitcoin