I wanted to check a bit about how analogWrite() actually works. I understand that it sets up PWM timers on any of pins 3,5,6,9,10 or 11 and that these are off for a proportion of a period and on for another proportion. When this switching occurs is determined by the analog level (out of 255) and also affected by whether fast, phase correct or some other PWM mode is used. It also acts differently on different pins, especially 5 and 6 which share a clock with millis() and delay() and run at, by default, twice the PWM frequency of the others.
What happens though if you call analogWrite(SamePin,SameAnalogVal); at very great frequency though? Does each call to it restart the PWM timing cycle, such that if the cycle were only halfway through after the first analogWrite happened then the cycle would be restarted by the next analogWrite(SamePin, SameAnalogVal); ? Or would the code which makes up the analogWrite() function recognise that it had been called twice in quick succession on the same pin with the same analog output value and effectively ignore this econd call and just let the first one's PWM cycles keep running?
I'm not sure whether, upon calling analogWrite() the pin initially is low or high, but if for the point of this argument we assume it is low and we have a duty cycle of maybe 25% high (64/255) then for the first 75% of a cycle it will be low. If analogWrite with the same pin and analog value got called again before 50% of the cycle had completed, and then kept being called with a time between calls of approximately half the period of the PWM cycle, would it keep the pin low and restart the cycle each time, hence never letting the pin get to the high 25% at the end of it's PWM cycle? if infact PWm pins are initially high when the cycle starts then this pin would spend 25% of the cycle high, followed by another 25% low but then at that point would calling analogWrite() again send the pin high again, hence giving a 50% (analog 128/255) duty cycle even though you had specified 25%?
Some of this could be mitigated by putting use of analogWrite (for a specific pin to reduce the amount of typing I do in this post) , assuming you will for various reasons be calling it very often, into function such as:
byte OldVal=0; //global variable
void AlternativeAnalogWrite(byte Val){
if(Val != OldVal){
analogWrite(PIN, Val);
OldVal=Val;
}else{
//do nothing
}
}
But is use of such a function actually needed?
What about in cases where a different analog value was supplied in subsequent uses of analogWrite? Such a function as above couldn't protect you unless analoWrite itself contains protections to ensure that giving it a new value doesn't immediately restart the PWM cycle counter?
P.S. if it helps you simplify your answers you can ignore pins 5 and 6 and just discuss 3,9,10 and 11 as, due to the way 5 and 6 can alter the millis() and delay() functions I tend to stick to the 3,11 and 9,10 pairs of PWM pins when designing things.
Thanks