Controlling a motor is one of the most exciting things you can do with your Raspberry Pi. Motors are power-hungry components. They often require more power than the 3V3 your Raspberry can provide. That’s the reason we will connect the motor to a external power source (battery). You can use the same techniques described in this tutorial to work with any component, which requires external power source.
Building the Circuit
Before we can do anything we have to hook it all together. For this tutorial you will need
- a DC motor
- external power supply (battery) – you may need a different voltage according to your motor
- Darlington Array chip (ULN2003) – I will give you more details on this later in this tutorial
- a couple of wires
Look at the diagram below. It shows how to build the circuit.
Darlington Array Chip
The ULN2003 is seven pairs of transistors that allows us to switch a higher voltage with the 3V3 from a GPIO port in a safe way. We can use a standard transistor instead, but why should we bother when the ULN2003 can be ordered for less than 0.20$ and can control 7 motors at the same time.
Another important thing about ULN2003 is, that it protects your Raspberry GPIO ports from the voltage spike that can occur when an inductive load (a relay, solenoid, motor etc.) is switched off.
Controlling the Motor
We will use a software PWM to control the motor speed. If you want to know more about PWM please read my previous tutorial Raspberry Pi Dim LED with PWM and Java. We will use the Pi4j API to write our speed controlling program in Java. If you want to know how to install, configure and run projects with Pi4j please refer to this tutorial.
For more detail: Raspberry Pi Control Motor Speed