Help with simple PWM

hello everyone, I modified a simple PWM code where the user can define freq and dutycycle. see code below. It does not work. I think it is something to with the delayMicroseconds command. I put in a number for the delayMicroseconds command and it works fine. But when I put in the timeOn variable it does not work.

Any suggestions would be appreciated Thankyou

// pwm where user defines output freq and duty cyle int dutyCycle=0.20; //user defined int outFreq=.002000; //user defined in megahertz int period=1/outFreq; int timeOn=dutyCycle*period; int timeOff=period-timeOn;

void setup() { pinMode(8,OUTPUT);


void loop() { digitalWrite(8,HIGH);

delayMicroseconds(timeOn); //time the led is on.


delayMicroseconds(timeOff); }

int outFreq=.002000; //user defined  in megahertz

This is always 0 (zero). You cannot use integers and calculate with floating points.

But when I put in the timeOn variable it does not work.

Sure it does. It just doesn't do what you want.

int dutyCycle=0.20; //user defined
int outFreq=.002000; //user defined  in megahertz

So, dutyCycle is 0, as is outFreq.

int period=1/outFreq;

Umm. It's really not a good idea to divide by 0.

int timeOn=dutyCycle*period;
int timeOff=period-timeOn;

So, timeOn is 0 times infinity, or 0. The timeOff is infinity minus 0, or infinity.

loop() then turns the pin on for 0 milliseconds, turns it off, and then takes a bit of time to end the function.

Is that not what you wanted?

Hello I wrote the following code for PWM but it isnt running. I am trying to get a PWM output at pin 11 and 3. I want a frequency of 100HZ.
I used Fout=Fclock/(2prescalerICR1) to calculate ICR1 value.
I used Dutycyle=OCRA1+1/timerMaxcount to calculate value for OCRA1.
Any help would be appreciated. Thanks

void setup()
pinMode(11, OUTPUT);

//set value of TCCR2A

//set values of TCCR2B

//set output freq by setting ICR
//setting to 40.96 gives fout of 100hz
//set dutycycle by setting OCRA

void loop()


Please do not cross-post. This wastes time and resources as people attempt to answer your question on multiple threads.

Threads merged.

Read this before posting a programming question

Please edit your post, select the code, and put it between [code][/code] tags.

You can do that by hitting the # button above the posting area.

  • Moderator