Note
Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.
Why Join?
Expert Support: Solve post-sale issues and technical challenges with help from our community and team.
Learn & Share: Exchange tips and tutorials to enhance your skills.
Exclusive Previews: Get early access to new product announcements and sneak peeks.
Special Discounts: Enjoy exclusive discounts on our newest products.
Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.
š Ready to explore and create with us? Click [here] and join today!
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.
Components Requiredļ
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.
Schematic Diagramļ
Codeļ
Note
You can open the file
2.13_motor.inounder the path ofsunfounder_vincent_kit_for_arduino\code\2.13_motordirectly.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) {
int incomingByte = Serial.read();
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();
}
Phenomenon Pictureļ