Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Raspberry Pi
120 min
Share

How to control a DC motor with NPN transistor and Raspberry Pi 5 ?

A transistor is a semiconductor device that can be used as a switch, amplifier, or for other electronic functions. Transistor has three terminals for connection to an external circuit.

Project Video

Overview

In this tutorial, we will learn how to use a NPN transistor to operate a DC motor. It will provide the motor with the necessary power.

Getting the Items

Raspberry Pi 5 Single Board Computer
Get Item
2N2222 – NPN Transistor (3 pieces)
Get Item
Small DC motor RF-300
Get Item
1/4 Watt Resistor (20 Pack)
Get Item
Half-size Breadboard
Get Item
Jumper Wires – Male to Female (40 Pack)
Get Item

Steps

Wiring it Up

Connect the wires between the NPN transistor, the motor and the Raspberry pi 5 board, as shown in the image below.

Connections from the NPN transistor:


• NPN emitter pin → Raspberry Pi 5 GND pin


• NPN base pin (middle pin) → 4.7 KΩ resistor →  Raspberry Pi 5 pin 18


• NPN collector pin → Motor first wire


Connections from the motor:


• Motor first wire → NPN collector pin


• Motor second wire → Raspberry Pi 5 VCC pin (5V)

Coding

Now on your Raspberry Pi, click on the menu, then choose programming, then open the Thonny ide program.

Now copy that code into it, The function of this code is to turn the DC motor on and off for 5 second.

import gpiod

import time

MOTOR_PIN = 18  # GPIO pin number where the MOTOR is connected

# Open GPIO chip

chip = gpiod.Chip('gpiochip4')

# Get the GPIO line for the MOTOR

MOTOR_line = chip.get_line(MOTOR_PIN)

# Request exclusive access to the line and configure it as an output

MOTOR_line.request(consumer="MOTOR", type=gpiod.LINE_REQ_DIR_OUT)

try:

  while True:

      MOTOR_line.set_value(1)  # Turn on the MOTOR

      time.sleep(5)  # Wait for 1 second

      MOTOR_line.set_value(0)  # Turn off the MOTOR

      time.sleep(5)  # Wait for 1 second

finally:

  # Release the GPIO line and clean up resources on program exit

  MOTOR_line.release()

  chip.close()

Testing it Out

Now run the code, you will find that the Raspberry Pi 5 board turns on and off the DC motor for 5 second.

Resources

No items found.