# 12.1 DC Motor

The DC gear motor to be used is of 3\~5V, which looks as:

![DC Motor](https://2341898987-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCFDbcteyTR3tQSs-5x%2F-LDJKrwCgJEh9d6V-Nae%2F-LCFETtjJxZrPWxcJMO9%2Fmotor-DC.jpg?generation=1527202195421838\&alt=media)

In order to estimate the race car's speed, we also provide a speed encoder for each DC motor.

![DC Motor + Speed Encoder](https://2341898987-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCFDbcteyTR3tQSs-5x%2F-LCFE4dCRQBMq1ajywfh%2F-LCFETtz6f1zwYJo2UhM%2Fmotor-DC%2Bspeed-encoder.jpg?generation=1526059628070744\&alt=media)

Clearly, two welding spots come with the DC motor, which we need to weld out the electrical wires manually.

![DC Motor with Soldered Wire](https://2341898987-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCFDbcteyTR3tQSs-5x%2F-LCFE4dCRQBMq1ajywfh%2F-LCFETuCQ5TeLjq9PLnG%2Fmotor-DC%2Bsoldered.jpg?generation=1526059628049200\&alt=media)

## Hardware Wiring

![DC Motor](https://2341898987-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LCFDbcteyTR3tQSs-5x%2F-LCFE4dCRQBMq1ajywfh%2F-LCFETuek6zX-Bd--zYx%2F001_dcmotor.jpg?generation=1526059628816907\&alt=media)

## Sketch

The code can be found at [Examples\_Arduino - adafruit - \_001\_DCMotor - \_001\_DCMotor.ino](https://github.com/LongerVisionRobot/Examples_Arduino/blob/master/adafruit/_001_DCMotor/_001_DCMotor.ino) You can also refer to Adafruit's official website at [https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/overview](https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/overview).

```
/*
/*
Adafruit Arduino - Lesson 13. DC Motor
*/

int motorPin = 3;

void setup() 
{ 
  pinMode(motorPin, OUTPUT);
  Serial.begin(9600);
  while (! Serial);
  Serial.println("Speed 0 to 255");
} 

void loop() 
{ 
  if (Serial.available())
  {
    int speed = Serial.parseInt();
    if (speed >= 0 && speed <= 255)
    {
      analogWrite(motorPin, speed);
    }
  }
}
```

## Note

We will use 4 **L298N** DC motors in our race car. Please refer to [**Chapter 15.1 - 4-Wheel Driven Using 4 DC Motors**](../15_assembling/01_4wheel_dcmotor_driven) for more details.
