8 years, 10 months ago.

Negative Values

Is it really, that you take only the absolute value of e.g. seconds in the period- and pulsewidth-functions? Means, pwmpin.period(-1.0) is the same functionality than pwmpin.period(1.0), e.g.

Seems so, but I'm not sure. Best Regards and Thank you, Thomas

Question relating to:

The official Mbed 2 C/C++ SDK provides the software platform and libraries to build your applications.

how would you do negative time ?!!!

posted by Gary Z 11 Jan 2016

Hi Gary, This is easy done: Just call pwmpin = -0.5 or pwmpin.pulsewidth_us(-100) or something like that ... ;-) Since all arguments are signed, it is possible at least. Even if it seems to make no sense. . So, my question is "How do the related pwm-functions handle this 'faulty' input-value?" It would be possible, that they ignore the sign at all, or they use the absolute value instead, or maybe the function returns without any action at all, or ... Does anybody know? Best Regards, Thomas

posted by Thomas Eibel 11 Jan 2016

1 Answer

8 years, 10 months ago.

The answer is that it depends on the platform. Since you only seem to have the LPC11U24 that's the one I looked at.

Looking in the pwmout code for that device here all of the different ways of setting a period convert the time to us and then call pwmout_period_us(pwmout_t* obj, int us).

At that point it would still be possible to have a negative amount of time, I can't see anything in there to catch that situation. However the time in us is then converted into a number of clock cycles using

uint32_t period_ticks = (uint32_t)(((uint64_t)SystemCoreClock * (uint64_t)us) / (uint64_t)1000000);

Which casts the 32 bit signed number to a 64 bit unsigned number. That means that -1 will become about 66 minutes. The number of clock cycles for that time is calculated and then converted back into a 32 bit number which will reduce the period to 4 billion clock cycles or less.

In other words it's probably safe to say the behavior is undefined and you shouldn't use negative times.

When setting the duty cycle there is a check on the range, anything under 0 is set to 0, anything over 1 is set to 1. However that is in the platform specific code and so you shouldn't assume it for any platform.

Thank you both for your (civil & informative) answers - I was being tongue-in-cheek. Programmers know what they are looking for and tend to forget bad input from the program/user/sensors. There must be a balance between always checking the input range & type and error recovery - especially in small memory situations. Again - thank you gentlemen. Gary

posted by Gary Z 12 Jan 2016

Thanks for your detailed answer :-). Most of all for the link - I didn't find the source code by myself ... Best Regards, Thomas

posted by Thomas Eibel 13 Jan 2016