PWM manipulation

Hi all,

Without going into any detail as this is just something that crossed my mind tonight.

Straight forward question, with hopefully a straight forward answer.....

How would I go about adding a 100ms interval into a PWM? For example, my PWM frequency is 10kHz at 50% duty cycle. Every 100ms I want the duty to jump to 70% for 50ms and then back to 50% for the following 50ms.

This isn’t tied to any project, I’m just wondering if it’s easily achievable in code?

Thanks

Regular PWM is about 490/980Hz and using analogWrite sets the duty cycle between 0 and 100% with values 0 thru 255. Normally to get a 50% duty cycle you would write 128 to the pin and 179 for 70%.

To cycle between the two you could perform a simple test and use a 2 state switch:

enum {fifty, seventy} state;
if((millis() - last_switch) >= 50)
{
    last_switch = millis();
    switch(state)
    {
        case fifty:
            analogWrite(pin,128);
            state = seventy;
            break;
        case seventy:
            analogWrite(pin,179(;
            state = fifty;
            break;
    }
}

As you have adjusted the PWM freq to 10K, the values to achieve 50/70% would also need to reflect your changes.

Interesting, thank you DKWatson.

Thinking ahead id probably use a lower PWM frequency of 3kHz. But that’s irrelevant of what I’m trying to achieve.

On further thought, I’d lower my intervals to 14ms with a duty cycle deviation of 5% above and below 50% duty (128bits). For example....

7ms @ 122 bits
7ms @ 134 bits

I could achieve the above using the switch statement posted by DKWatson above.

Out of curiosity, what other methods are available of achieving this?

Thanks

Google Secrets of Arduino PWM

Bit beyond me but I’ll keep researching.

What? Google or the article?

Lol. The article

If you want to change the frequency, you're going to have to come to terms with direct port addressing. I'm unaware of any library that provides for that.