I am trying to control a Servo motor and a DC motor at the same time using my Arduino Uno from the serial monitor. I have set it up so that if I type a value between 100 and 255 (the motor only functions from 100 up), the motor goes to that speed, And when I enter a value between 500 and 620 the servo goes to the respective position between 40 and 160 degrees (I only need that range of motion). They both work perfectly when run on separate codes but when I upload the full code with both, the following happens:
the servo works fine, but the motor only switches on when I put it on full speed. At 255, it runs perfectly, but at 254 it stops. The speed control works perfectly when the servo is not mentioned in the code. I have attached a diagram of how it is setup. the only difference from the diagram is the fact that i am running the DC motor off the 3.3V power of the arduino.
Here is the code for the motor on its own:
int motorControlPin = 10;
void setup() {
pinMode(motorControlPin, OUTPUT);
Serial.begin(9600);
Serial.println("Enter a Value between 0-255 to set the speed of the motor");
}
void loop()
{
if (Serial.available())
{
int speed = Serial.parseInt();
analogWrite(motorControlPin, speed);
}
}
and here is the code for the servo and the motor:
int motorControlPin = 10;
#include <Servo.h>
int servoPos = 0;
int num = 0;
int speed = 0;
Servo servo1;
void setup() {
pinMode(motorControlPin, OUTPUT);
servo1.attach(9);
Serial.begin(9600);
}
void loop() {
if (Serial.available()){
num = Serial.parseInt();
}
if (num >= 500 && num <= 620){
servoPos = (num - 460);
servo1.write(servoPos);
}
if (num >= 100 && num <= 255){
speed = num;
analogWrite(motorControlPin, speed);
}
if (num == 0){
speed = num;
analogWrite(motorControlPin, speed);
}
}
