# 2.13 Motor¶

## Overview¶

In this lesson, you will learn how to use Motor, the working principle of which is that the energized coil is forced to rotate in the magnetic field then the rotor of the motor rotates accordingly on which the pinion gear drives the engine flywheel to rotate.

## Fritzing Circuit¶

In this example, we use Power Supply Module to power the anode and cathode of breadboard. GND of Mega 2560 Board is connected to the cathode.

## Code¶

Note

• You can open the file `2.13_motor.ino` under the path of `sunfounder_vincent_kit_for_arduino\code\2.13_motor` directly.

• Or copy this code into Arduino IDE.

After uploading the codes to the Mega2560 board, you can select the rotating direction of motor by typing 「A」 or 「B」 in the serial monitor.

## Code Analysis¶

The motor can be driven by providing a voltage difference between the copper sheets at both sides of the motor. Therefore, you only need to write 0 for the voltage of one side of the copper sheet and 5V for the other side. Modify the written analog signal value to adjust the direction and speed.

```void clockwise(int Speed)
{
analogWrite(motor1A,0);
analogWrite(motor2A,Speed);
}

void anticlockwise(int Speed)
{
analogWrite(motor1A,Speed);
analogWrite(motor2A,0);
}
```

In this example, Serial.Read() is used to control the direction of motor.

When you type 'A' in serial monitor, there calls the clockwise (255) function to make the motor rotate with the speed of 255. Input 'B', and the motor will rotate in reverse direction.

```void loop() {
if (Serial.available() > 0) {
switch(incomingByte){
case 'A':
clockwise(255);
Serial.println("The motor rotate clockwise.");
break;
case 'B':
anticlockwise(255);
Serial.println("The motor rotate anticlockwise.");
break;
}
}
delay(3000);
stopMotor();
}
```