DEV Community

Kyle Trahan
Kyle Trahan

Posted on

DC motor Arduino

Last week I got some distance sensors to start working on the problem of "what happens when my robot runs into an obstacle". I got a basic sensor working that printed out the distances that were being recorded. This week I took it a small step forward and added a DC motor to the mix.

I worked out a pretty simple solution for now that will cause a motor to turn on based off something being within 5cm of the sensor. Since I already had the code from before to determine the distance. It was as simple as adding the pin the motor is connected to and then making a conditional statement about what distance the motor should turn on/off at.

First we declare our variable for the pin we are connected to:

int motorPin = 6;
Enter fullscreen mode Exit fullscreen mode

It looks like this inside the setup():

pinMode(motorPin, OUTPUT);
Enter fullscreen mode Exit fullscreen mode

and this in the loop():

if ( distance <= 5 ) {
    digitalWrite( motorPin, HIGH ); 
 } else {
    digitalWrite( motorPin, LOW );
 }
Enter fullscreen mode Exit fullscreen mode

After completing that test I noticed that the motor seemed to be going really fast and that didn't seem like a very good way to turn around. So I did a little bit more digging and found that you can control the speed of the motor. So I made a small tweak to the code:

if ( distance <= 5 ) {
   analogWrite( motorPin, 100 ); 
} else {
   digitalWrite( motorPin, LOW );
}
Enter fullscreen mode Exit fullscreen mode

This will just set the speed of the motor to a specific speed instead of running at its fastest speed by default.

On a bigger scale I would have to do some programming to turn one set of wheels on in one direction while the other side goes in the opposite direction. At least as of now that will be my plan, but I am still contemplating between making a four or three wheeled little robot friend!

Top comments (0)