Can any one use arduino MEGA 2560 to generate PWM of 400 HZ and have a duty

Can any one use arduino MEGA 2560 to generate PWM of 400 HZ and have a duty cycle same as INPUT.

Plz suggest how to generate 400Hz PWM signal.

int pwm_output=10; int k; int x=0; int y=0; static double duty;

static double freq; static double timeperiod;

static long ONTime = 0;

static long OFFTime = 0;

static long tempPulse;

void setup() { // put your setup code here, to run once: pinMode(9,INPUT); pinMode(pwm_output,OUTPUT); TCCR2B = (TCCR2B & 0b11111000) | 0x05; Serial.begin(9600); }

void loop() { // put your main code here, to run repeatedly:

ONTime = 0;

OFFTime = 0;

tempPulse = pulseIn(9,HIGH);


ONTime = tempPulse;


tempPulse = pulseIn(9,LOW);


OFFTime = tempPulse;


Serial.println(ONTime); Serial.println(OFFTime); freq = ((double) 1000000)/(double (ONTime+OFFTime)); Serial.println(freq); duty = (100*(ONTime/(double (OFFTime+ONTime)))); k= duty*2.55; analogWrite(10,k);


I have not studied the Atmega 2560 datasheet in the last week or so and I can't remember what is the range of frequencies that its "native" PWM can produce. If 400Hz is in the range then it should be straigtforward.

If it is not, and because 400Hz is very slow, you could do it with a succession of digitalWrite()s.

What is the input signal? Give us all the information about the project.


The default PWM frequency on Timer2 is 490 Hz, in Mode 1 (PWM, Phase Correct) using a prescaler of 64 with a 255 top value. These default intitial values are defined in wiring.c.

 TCCR2B = (TCCR2B & 0b11111000) | 0x05;

Your code has changed the prescaler from 64 to 128, which will result in 245 Hz period.

If you truely need 400Hz (and not 490Hz) you will need to make use of the data sheet for the ATmega 2560. Download a copy of it for reference.

For 400Hz PWM on Timer2 you will want prescaler 128, and PWM mode 5(phase correct PWM to OCRA top). You will use OCRA = 156 as top value. That should give a period = 156 x2 x 128 x .0625 = 2.496 ms = 400Hz.

You will only get PWM output on pin 9 of the timer with duty cycle values controlled by OCRB. If you use analogWrite() instead of directly working with OCRB, then you will not be able to use a value greater than OCRA - 1 = 155 for the duty cycle.