analogWrite problem when fading an LED

Good day

I’m having trouble fading an LED in and out. I intend to use a for loop to increment and decrement an analog value from 0 to 255 with a delay between each cycle of the for loops. This method only works when nothing is inside the void setup() function. If anything is inside the setup then only 255 and 0 work as analog values and as a result the LED simply flashes every now and then. I intend to do various other things with the final project and I will need to use the setup function to initialize a bunch of things like serial comms… any way around this? (just ignore the constants that I’m not using yet)

Fade_problem.ino (787 Bytes)

You have no pinMode call for the LedPin.

As far as i know this isn't needed for analogWrite but I'll try it thanks

Okay I tried it, still doesnt work... This is what i tried:

void setup(){
pinMode(ledPin, OUTPUT);
}

I removed the headServo.attach() and then it worked... this is the culprit. Is the servo library messing up the code? Note that when I removed the pinMode it still worked as it should when removing everything in the setup function.

If using the Servo library, it disables PWM for pins 9 & 10 on a UNO, Nano, ProMini and other Arduinos that use the Mega328 chip.

And yes you don't need to set pin mode for analogWrite()

The servo library uses a hardware timer to do its job. I'll guess that it's using the same one as analogWrite. I think that there are servo libraries that use a different timer. I see references from years ago to this one for example: ServoTimer2.