The main point of this post is to show how to use the Arduino Motor Shield. Our robot design was based around using this shield and it's definitely a great shield to have if you plan on making any small robots with DC motors.
For this example we'll need just a few things:
Arduino Motor Shield
9 Volt Battery (Optional) with snap connector. You can use power directly from USB if you wanted.
For now, connect the battery snap to the Vin and GND screw terminal. And connect the positive and negative lead of the motor to the + and - of the A channel.
If you look on the digital pins on the motor shield, it says which pins are used for what. For example, Pin 12 is used to control the direction of Channel A and Pin 3 is used to control the speed of Channel A. Pin 9 is used as a brake for Channel A, but we won't be using that too much today. If you look you can see the other pins for Channel B, but I'm only using one motor for this demonstration.
Below is some example code I wrote.
At the top of the program I'm declaring variable names for the pins I'm using just to make it have more readability. In the setup() I'm telling the Arduino that the three control pins are all outputs. And in the loop() I'm telling the Arduino what to do with each pin.
The reason we do digitalWrite(brake, LOW) is because we want to tell the Arduino to disable the brake, that way the motor will be able to spin.
Next is analogWrite(pwm, 125). We use analogWrite because the Arduino is expecting a PWM signal that will change the duty cycle on the output. That way we can control the speed of the motor. When using analogWrite your second parameter is going to be a value between 0 and 255. With 0 being the slowest (off) and 255 being full speed.
When we use digitalWrite(dir, HIGH) what's basically happening is that we're telling what direction we want the motor to spin. Depending on your motor and how you have it wired, setting it HIGH will turn it one direction, and setting it LOW will turn in the opposite direction. This is useful for turning your robot, or so you can have different functions for forward and reverse.
You can find code for this post on my GitHub at github.com/jacobantoun. I'll have more examples in there, and code from previous projects I've done. I show an example of using a function to make it a little easier to control the motor on my GitHub also.
Now here's a video of the motor running at 25% speed, then jumping up to 50%, then 75%, then full speed. I didn't pick a very good color of tape to see the different speeds spinning, but you can definitely hear it!