Is analogWrite(x,256) valid?

Status
Not open for further replies.

madgrizzle

Active member
I'm working on learning so I apologize if this is a stupid question.

The https://www.pjrc.com/teensy/td_pulse.html page says the following:

"The value is between 0 to 256, where the higher the value, the more time the signal remains high. 0 and 256 correspond to always low and always high. Values 1 to 255 pulse the pin, referred to in percentage terms as "duty cycle". A value of 128 is 50% duty cycle.

The https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/ page says the following:

"value: the duty cycle: between 0 (always off) and 255 (always on). Allowed data types: int"

I know enough about computers to know that when I see a 0 as a lower limit, usually the upper limit is 255. Is the 256 the correct value for Teensy for always high but 255 for an Arduino, or is the teensy page in error?

Thanks!
 
Conclusion: Teensyduino is smarter than Arduino.

Look at the source code of analogWrite() in the Teensyduino core files and you will see that analogWrite(255) will and can never be "always on" since the timer modulo value is 255, which corresponds to 256 ticks, zero including. Thus, the "on" time for analogWrite(255) will always be 255/256 only. That's why Teensyduino will do the following when you do a analogWrite(256) :
- stop the PWM
- disconnect the pin from the Timer
- connect the pin to the GPIO
- write a logical (and constant) HIGH to that pin

When you'll do another analogWrite with a value < 256 afterwards, Teensyduino will
- disconnect the pin from the GPIO
- connect the pin to the timer
- set the desired PWM value to the timer.

See pins_teensy.c from line 691
 
Thanks for the quick response! If I understand correctly, when porting code from an arduino to a teensy, I need to change analogWrite(x,255) to analogWrite(0,256) to get the same effect.. correct?
 
Yes.

BTW, I'm don't think that analogWrite(x,255) in Arduino does a true "always on". That's why Teensyduino improved that function. Thus, by writing 255, you should get the same, an "almost always on", on both, Arduino and Teensy. A true "always on" is guaranteed only on Teensy with writing 256.
 
Thanks. The code I'm porting eventually "detaches" motors after 2 seconds of idle so the 1/256 pwm duty cycle isn't likely noticed, but I'll bring it up to the community to investigate since everyone is currently using an arduino.
 
Status
Not open for further replies.
Back
Top