I need to obtain a PWM frequency of at least 125Khz. I plan to drive a pair of mosfets using this PWM as the driver signal. The below code gives 1Khz frequency. Can I just change the delay values to obtain a lower time period, and thereby a higher frequency?
void setup()
{
pinMode(13, OUTPUT);
}
void loop()
{
digitalWrite(13, HIGH);
delayMicroseconds(100); // Approximately 10% duty cycle @ 1KHz
digitalWrite(13, LOW);// can i change the delay to 1 and 9 for a totaL T=10micro sec and hence f=100khz?
delayMicroseconds(900);
}
Update: on looking up the answers provided i stumbled across a few tutorials. I used the code below and it resulted in 125Khz and 1.6 Mhz(measured with a CRO, not simulation). But the code was supposed to provide 250Khz and 8Mhz.
My requirement of 125Khz is satisfied, but just curious to know why the sketch not working as it should
2nd Sketch:
// A sketch that creates an 8MHz, 50% duty cycle PWM and a 250KHz,
// 6bit resolution PWM with varying duty cycle (changes every 5μs
// or about every period.
#include <avr/io.h>
#include <util/delay.h>
int main(void)
{
pinMode(3, OUTPUT); // output pin for OCR2B
pinMode(5, OUTPUT); // output pin for OCR0B
// Set up the 250KHz output (but cro measures only 125khz)
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(WGM22) | _BV(CS20);
OCR2A = 63;
OCR2B = 0;
// Set up the 8MHz output
TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM01) | _BV(WGM00);
TCCR0B = _BV(WGM02) | _BV(CS00);
OCR0A = 1;
OCR0B = 0;
// Make the 250KHz rolling
while (1) {
_delay_us(5);
if ( OCR2B < 63 )
OCR2B += 5;
else
OCR2B = 0;
} }