Devices & Components
Arduino Uno Rev3
DC motor (generic)
7.4v Lipo Battery
9V battery (generic)
Battery Connector to DC Power Adapter
L298N Motor / Stepper Driver
Jumper wires (generic)
HC-05 Bluetooth Module
Software & Tools
MIT App Inventor 2
Project description
Code
Arduino UNO code to control 4 dc motors
arduino
You will need to upload this code to your Arduino.
1/* 2 * Control 4 DC motors with Smartphone via bluetooth 3 */ 4 5int motor1Pin1 = 4; 6int motor1Pin2 = 5; 7int enable1Pin = 3; 8int motor2Pin1 = 12; 9int motor2Pin2 = 13; 10int enable2Pin = 11; 11int state; 12int flag=0; 13int stateStop=0; 14void setup() { 15 // sets the pins as outputs: 16 pinMode(motor1Pin1, OUTPUT); 17 pinMode(motor1Pin2, OUTPUT); 18 pinMode(enable1Pin, OUTPUT); 19 pinMode(motor2Pin1, OUTPUT); 20 pinMode(motor2Pin2, OUTPUT); 21 pinMode(enable2Pin, OUTPUT); 22 // sets enable1Pin and enable2Pin high so that motor can turn on: 23 digitalWrite(enable1Pin, HIGH); 24 digitalWrite(enable2Pin, HIGH); 25 // initialize serial communication at 9600 bits per second: 26 Serial.begin(9600); 27} 28 29void loop() { 30 if(Serial.available() > 0){ 31 state = Serial.read(); 32 flag=0; 33 } 34 // if the state is 'F' the DC motor will go forward 35 if (state == 'F') { 36 digitalWrite(motor1Pin1, HIGH); 37 digitalWrite(motor1Pin2, LOW); 38 digitalWrite(motor2Pin1, LOW); 39 digitalWrite(motor2Pin2, HIGH); 40 if(flag == 0){ 41 Serial.println("Go Forward!"); 42 flag=1; 43 } 44 } 45 46 // if the state is 'R' the motor will turn left 47 else if (state == 'R') { 48 digitalWrite(motor1Pin1, HIGH); 49 digitalWrite(motor1Pin2, LOW); 50 digitalWrite(motor2Pin1, LOW); 51 digitalWrite(motor2Pin2, LOW); 52 if(flag == 0){ 53 Serial.println("Turn LEFT"); 54 flag=1; 55 } 56 delay(1000); 57 state=3; 58 stateStop=1; 59 } 60 // if the state is 'S' the motor will Stop 61 else if (state == 'S' || stateStop == 1) { 62 digitalWrite(motor1Pin1, LOW); 63 digitalWrite(motor1Pin2, LOW); 64 digitalWrite(motor2Pin1, LOW); 65 digitalWrite(motor2Pin2, LOW); 66 if(flag == 0){ 67 Serial.println("STOP!"); 68 flag=1; 69 } 70 stateStop=0; 71 } 72 // if the state is 'L' the motor will turn right 73 else if (state == 'L') { 74 digitalWrite(motor1Pin1, LOW); 75 digitalWrite(motor1Pin2, LOW); 76 digitalWrite(motor2Pin1, LOW); 77 digitalWrite(motor2Pin2, HIGH); 78 if(flag == 0){ 79 Serial.println("Turn RIGHT"); 80 flag=1; 81 } 82 delay(1000); 83 state=3; 84 stateStop=1; 85 } 86 // if the state is 'B' the motor will Reverse 87 else if (state == 'B') { 88 digitalWrite(motor1Pin1, LOW); 89 digitalWrite(motor1Pin2, HIGH); 90 digitalWrite(motor2Pin1, HIGH); 91 digitalWrite(motor2Pin2, LOW); 92 if(flag == 0){ 93 Serial.println("Reverse!"); 94 flag=1; 95 } 96 } 97 //For debugging purpose 98 Serial.println(state); 99}
Downloadable files
Circuit Diagram
Use this to wire up your l298n and arduino.
Circuit Diagram

Comments
Only logged in users can leave comments