Bird
0
0
Arduinoprogramming~5 mins

DC motor with transistor driver in Arduino

Choose your learning style9 modes available
Introduction

We use a transistor to control a DC motor because the motor needs more power than the Arduino can provide directly. The transistor acts like a switch that turns the motor on and off safely.

When you want to turn a DC motor on or off using an Arduino.
When the motor needs more current than the Arduino pin can supply.
When you want to control the motor speed using PWM signals.
When you want to protect your Arduino from high current damage.
When building simple robots or fans controlled by Arduino.
Syntax
Arduino
int motorPin = 9;  // Arduino pin connected to transistor base

void setup() {
  pinMode(motorPin, OUTPUT);  // Set pin as output
}

void loop() {
  digitalWrite(motorPin, HIGH);  // Turn motor ON
  delay(1000);                   // Wait 1 second
  digitalWrite(motorPin, LOW);   // Turn motor OFF
  delay(1000);                   // Wait 1 second
}

The transistor base is connected to an Arduino digital pin through a resistor.

Use a diode across the motor terminals to protect from voltage spikes.

Examples
Simple ON/OFF control of the motor using digital signals.
Arduino
digitalWrite(motorPin, HIGH);  // Motor ON

digitalWrite(motorPin, LOW);   // Motor OFF
Use PWM to control motor speed by changing the signal's duty cycle.
Arduino
analogWrite(motorPin, 128);  // Motor runs at half speed (PWM)
Always set the pin mode to OUTPUT to control the transistor properly.
Arduino
pinMode(motorPin, OUTPUT);  // Set pin as output before controlling motor
Sample Program

This program turns the motor on for 2 seconds, then off for 2 seconds, repeatedly. The transistor acts as a switch controlled by the Arduino pin.

Arduino
int motorPin = 9;  // Pin connected to transistor base

void setup() {
  pinMode(motorPin, OUTPUT);  // Set motorPin as output
}

void loop() {
  digitalWrite(motorPin, HIGH);  // Turn motor ON
  delay(2000);                   // Run motor for 2 seconds
  digitalWrite(motorPin, LOW);   // Turn motor OFF
  delay(2000);                   // Wait for 2 seconds
}
OutputSuccess
Important Notes

Always connect a diode (called a flyback diode) across the motor terminals to protect the transistor from voltage spikes.

Use a resistor (around 1k ohm) between Arduino pin and transistor base to limit current.

Make sure your transistor can handle the motor's current.

Summary

A transistor lets Arduino safely control a DC motor by acting as a switch.

Use digitalWrite to turn the motor on or off through the transistor.

Protect your circuit with a diode and resistor for safe operation.