Page 190 - Making things move_ DIY mechanisms for inventors, hobbyists, and artists
P. 190
168 Making Things Move
void loop()
{
if (digitalRead(switchPin) == HIGH) //if switch is on (HIGH)...
{
for (int i=0; i <= 255; i++) //ramp up speed slowly
{
analogWrite(transistorPin, i); //send value of i to transistorPin
delay(10);
}
delay(500); //wait half a second
for (int j = 255; j >= 1; j--) //ramp down speed slowly
{
analogWrite(transistorPin, j);
delay(10);
}
delay(500); //wait half a second
} //end if
else if (digitalRead(switchPin) == LOW) // if switch is off (LOW)...
{
digitalWrite(transistorPin, LOW); // turn motor off (LOW)
}
} //end loop
10. When the switch is turned on, the motor should start spinning slowly, speed up,
and then slow back down. This cycle will repeat until you turn the switch off.
Arduino Extensions
If you want robust speed and/or direction control, you might want to check out
ready-made modules that interface with your Arduino and do the hard work for you.
These modules can make your life easy by incorporating many of the things in the
“Helpful Tips and Tricks for Motor Control” section later in this chapter. You’ll pay for
this convenience, but sometimes it’s worth it. For example, SparkFun’s ROB-09670 is a
motor driver that has an H-bridge already in it, along with other conveniences like
direction-indicating LEDs. SparkFun also sells a Digital PWM Motor Speed Controller
(ROB-09668), which can control the speed of your motor with PWM without
sacrificing torque. Adafruit Industries (www.adafruit.com) sells a Motor/Stepper/Servo
Shield for Arduino that can make things even easier. All you do is plug the shield in on