I written a code for a motor car and written basic functions like go_forward()
, go_backward()
, turn_left()
, turn_right()
and stop()
. all functions are working properly in the loop()
function.
but when I added the code lines for servo motor:
#include <Servo.h>
Servo servo = Servo();
void setup() {
servo.attach(A5);
}
only one wheel of the vehicle works.
the full code:
#include <Servo.h>
Servo servo = Servo();
int EnA = 3;
int In1 = 4;
int In2 = 5;
int EnB = 9;
int In3 = 12;
int In4 = 13;
void setup() {
servo.attach(A5);
//turn moter A
pinMode(EnA, OUTPUT);
pinMode(In1, OUTPUT);
pinMode(In2, OUTPUT);
//turn moter B
pinMode(EnB, OUTPUT);
pinMode(In3, OUTPUT);
pinMode(In4, OUTPUT);
analogWrite(EnA, 150);
//lowest - 100 highest - 200
analogWrite(EnB, 150);
//servo.write(150);
//Serial.begin(9600);
}
void loop() {
// In1 -> HIGH & In2 -> LOW ---- backward
go_forward();
//char c = Serial.read();
//Serial.println(c);
//delay(1000);
//if (c == '1'){
// digitalWrite(13, HIGH);
//}
//if (c == '2'){
// digitalWrite(13, LOW);
//}
}
void go_forward(){
// In1 -> HIGH & In2 -> LOW ---- backward
digitalWrite(In1, HIGH);
digitalWrite(In2, LOW);
digitalWrite(In3, LOW);
digitalWrite(In4, HIGH);
}
void go_backward(){
// In1 -> HIGH & In2 -> LOW ---- backward
digitalWrite(In1, LOW);
digitalWrite(In2, HIGH);
digitalWrite(In3, HIGH);
digitalWrite(In4, LOW);
}
void stop(){
// In1 -> HIGH & In2 -> LOW ---- backward
digitalWrite(In1, LOW);
digitalWrite(In2, LOW);
digitalWrite(In3, LOW);
digitalWrite(In4, LOW);
}
void turn_left(){
// In1 -> HIGH & In2 -> LOW ---- backward
digitalWrite(In1, LOW);
digitalWrite(In2, HIGH);
digitalWrite(In3, LOW);
digitalWrite(In4, HIGH);
}
void turn_right(){
// In1 -> HIGH & In2 -> LOW ---- backward
digitalWrite(In1, HIGH);
digitalWrite(In2, LOW);
digitalWrite(In3, HIGH);
digitalWrite(In4,LOW);
}
I just change the attach pin to 3(PWM digital pin and more other pins) but still same... and double checked that I've connected wires properly... and all are ok...
From the manual:
The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega. On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins. On the Mega, up to 12 servos can be used without interfering with PWM functionality; use of 12 to 23 motors will disable PWM on pins 11 and 12.
You're using pin 9 for motor B.
Please read manuals. They exist for good reasons.