Hardware Reference
In-Depth Information
ControllingMotorSpeedwithPWM
First up, you can use a program very similar to the one you used to adjust LED
brightness of your nightlight in Chapter 3 to adjust the speed of your motor. By
sending varying duty-cycle signals to the transistor, the current flow through
the motor rapidly starts and stops resulting in a change in velocity. Try out the
program in Listing 4-1 to repeatedly ramp the motor speed up and down.
Listing 4-1: Automatic Speed Control—motor.ino
//Simple Motor Speed Control Program
const int MOTOR=9; //Motor on Digital Pin 9
void setup()
{
pinMode (MOTOR, OUTPUT);
}
void loop()
{
for (int i=0; i<256; i++)
{
analogWrite(MOTOR, i);
delay(10);
}
delay(2000);
for (int i=255; i>=0; i--)
{
analogWrite(MOTOR, i);
delay(10);
}
delay(2000);
}
If everything is hooked up correctly, this code should slowly ramp the motor
speed up, then back down again in a loop. Using these techniques, you could
easily make a simple roving robot.
Next up, you can combine your new knowledge of DC motors with your
knowledge of analog sensors. Using a potentiometer, you can manually adjust
the motor speed. To begin, add a potentiometer to analog pin 0, as shown in
Figure 4-4. Note that you must connect the 5V pin from the Arduino to the
power rail on the breadboard if you want to connect the potentiometer to that
row on the board.
Search WWH ::




Custom Search