I can get LEDs to fade properly using PWM on pins 44-46 on the Mega2560 when I don't have a servo attached, but once I "attach" the servo in the code, then PWM pins 44-46 don't work for PWM. They can still work with digitalWrite, but not with analogWrite.
This is the code:
#include <Servo.h>
Servo myservo;
int led = 46;
void setup() {
myservo.attach(3);
pinMode(led, OUTPUT);
analogWrite(led, 60);
}
void loop() {}
If I comment out the "myservo.attach(3);" line, then PWM works for the LED pin. Otherwise the LED stays off. Why would PWM on pins 44-46 stop working once the servo is attached?
-
1Wanted to add: I just tested it on an earlier PWM pin (12), and the PWM worked fine even when the servo was attached. It seems that only 44-46 are having problems.Jerry– Jerry2015年07月13日 19:51:13 +00:00Commented Jul 13, 2015 at 19:51
1 Answer 1
Looks like the mega has some clever servo handling features. Servo control always uses a timer of some sort and can conflict with the pwm timer. The first 12 servos knock out pins 44,45,46 ...
For Arduino Mega it is a bit more difficult. The timer needed depends on the number of servos. Each timer can handle 12 servos. For the first 12 servos timer 5 will be used (losing PWM on Pin 44,45,46). For 24 Servos timer 5 and 1 will be used (losing PWM on Pin 11,12,44,45,46).. For 36 servos timer 5, 1 and 3 will be used (losing PWM on Pin 2,3,5,11,12,44,45,46).. For 48 servos all 16bit timers 5,1,3 and 4 will be used (losing all PWM pins).
-
Wow, great find!! Thanks so much for the help! I already had switched to using pins 11-13 for the PWM, but I was still interested in learning the answer.Jerry– Jerry2015年07月13日 22:12:09 +00:00Commented Jul 13, 2015 at 22:12