This is a problem specific to the Photon 2 because this code worked fine on the Argon.
I have students build a rotating fan with a servo and a DC motor. I have confirmed that the servo code works by itself and the DC motor code works by itself. However, when I combine the two and use millis() to control the servo rotation, the servo freezes and makes a grinding sound. However, when I use delay() of millis(), everything works fine.
Here is the code with millis() that causes the servo to freeze
const int AIN1 = D3;
const int AIN2 = D4;
const int PWMA = A5;
const int PIN_SERVO = A2;
Servo fanServo;
int servoAngle = 90;
unsigned long prevMillis = 0;
bool isAngleIncreasing = true;
void loop() {
analogWrite(PWMA, 255);
digitalWrite(AIN1, HIGH);
digitalWrite(AIN2, LOW);
unsigned long currMillis = millis();
if (currMillis - prevMillis > 1000) {
prevMillis = currMillis;
if (isAngleIncreasing == true) {
servoAngle += 5;
} else {
servoAngle -= 5;
}
if (servoAngle >= 165) {
isAngleIncreasing = false;
} else if (servoAngle <= 15) {
isAngleIncreasing = true;
}
fanServo.write(servoAngle);
}
}
and here is the same code using delay() that works fine
const int AIN1 = D3;
const int AIN2 = D4;
const int PWMA = A5;
const int PIN_SERVO = A2;
Servo fanServo;
int servoAngle = 90;
unsigned long prevMillis = 0;
bool isAngleIncreasing = true;
void loop() {
analogWrite(PWMA, 255);
digitalWrite(AIN1, HIGH);
digitalWrite(AIN2, LOW);
if (isAngleIncreasing == true) {
servoAngle += 5;
} else {
servoAngle -= 5;
}
if (servoAngle >= 165) {
isAngleIncreasing = false;
} else if (servoAngle <= 15) {
isAngleIncreasing = true;
}
fanServo.write(servoAngle);
delay(200);
}
Thanks for your response, @peekay123 . That makes sense but was actually by design. I simplified the code I posted here because in my origianl I was using a potentiometer to control the DC motor speed and I wanted that to happen responsively where as servo rotation would happen once per second. Here was the actual code
I think the problem is that the RTL872x uses a single PWM timer, which is also used for Servo.
The problem is likely that PWM has a default frequency of 500 Hz but Servo is 50 Hz. When you set analogWrite PWM, it's changing the frequency used by servo from 50 to 500 Hz, which would explain the behavior you are seeing.
The solution is probably to use the three parameter version of analogWrite and set to third parameter to 50 for motor speed, if that is compatible with your motor.