#include <SoftwareSerial.h>
#include <AFMotor.h>
#include <Servo.h>
SoftwareSerial BTSerial(2, 3);
// DC motor on M2
AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
// DC hobby servo
Servo servo1;
#define ActionTime 3000
void setup() {
BTSerial.begin(9600); // set up Serial library at 9600 bps
Serial.begin(9600);
motor1.setSpeed(250);
motor2.setSpeed(250);
servo1.attach(9);
servo1.write(0);
// turn on servo
}
void Go_Forward() {
motor1.run(FORWARD);
motor2.run(RELEASE);
delay(20);
}
void Stop_Release() {
motor1.run(RELEASE);
motor2.run(RELEASE);
delay(20);
}
void Go_Backward() {
motor1.run(BACKWARD);
motor2.run(RELEASE);
delay(20);
}
void Go_Down() {
motor1.run(RELEASE);
motor2.run(FORWARD);
delay(20);
}
void Go_Up() {
motor1.run(RELEASE);
motor2.run(BACKWARD);
delay(20);
}
void Go_Right() {
servo1.write(45);
delay(20);
}
void Go_Left() {
servo1.write(-45);
delay(20);
}
void loop() {
if (BTSerial.available()) {
char cmd = (char) BTSerial.read();
Serial.println(cmd);
if ( cmd == 'F') {
Go_Forward();
} else if (cmd == 'B') {
Go_Backward();
} else if (cmd == 'S') {
Stop_Release();
} else if (cmd == 'L') {
Go_Down();
} else if (cmd == 'R') {
Go_Up();
} else if (cmd == 'A') {
servo1.write(45);
delay(20);
} else if (cmd == 'D') {
servo1.write(-45);
delay(20);
}
}
}
If coded as above, the dc motor works properly and the servo motor rotates infinitely. I am currently controlling it using a Bluetooth app. What is the problem?
servo1.write(0); delay(2000);
servo1.write(90); delay(2000);
servo1.write(180); delay(2000);
Write the above on the loop door and check which angle stops.
I know it usually stops at 90 degrees
I used a negative number like -45 degrees, so I decided that 0 degrees was still. (It depends on the library..)