Adding a DC motor to your project is easy! This demo shows how to control a Gikfun 1V-6V Type 130 Miniature DC Toy Motor with a Raspberry Pi Pico.
The raspberry pi pico is a microntroller recently released by the raspberry pi foundation that can be programmed in Python!
Here, we read the state of a button with input pin (14); when pushed, pin (15) is brought high for 1 second, lighting the LED and driving the gate of an IRLZ34 MOSFET.
Since the motor ground is attached to the drain, the motor power lead is attached to +5V (note, using separate 5V supply rather than power from USB/pico), and the transistor source attached to ground, activating the gate essentially puts 5V across the motor, powering it. The code brings the gate high and spins the motor for 1 second. A diode is used to protect the transistor when the motor is shut off. (-, cathode) end at drain, (+, anode) lead at +5V. The diode is needed as the motor is inductive; when the current flowing through the motor shuts off suddenly its magnetic field tries to resist this change by increasing the voltage at the transistor drain; the diode harmlessly shorts this release of magnetic energy.
Here is the circuit diagram:
Here is the code for the raspberry pi pico:
from machine import Pin | |
import time | |
led = Pin(15, Pin.OUT) | |
button = Pin(14, Pin.IN, Pin.PULL_DOWN) | |
while True: | |
if button.value(): | |
led.value(1) | |
time.sleep(1) | |
led.value(0) | |
else: | |
led.value(0) |