I need to obtain a PWM frequency of at least 125 kHz. I plan to drive a pair of MOSFETs using this PWM as the driver signal. The below code gives a 1 kHz 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=10 µsec and hence f = 100 kHz?
delayMicroseconds(900);
}
Update
On looking up the answers provided, I stumbled across a few tutorials. I used the code below and it resulted in 125 kHz and 1.6 MHz (measured with a CRO, not simulation). But the code was supposed to provide 250 kHz and 8 MHz.
My requirement of 125 kHz is satisfied, but I am just curious to know why the sketch not working as it should.
Second sketch:
// A sketch that creates an 8 MHz, 50% duty cycle PWM and a 250 kHz,
// 6-bit 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 250 kHz output (but cro measures only 125 kHz)
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(WGM22) | _BV(CS20);
OCR2A = 63;
OCR2B = 0;
// Set up the 8 MHz output
TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM01) | _BV(WGM00);
TCCR0B = _BV(WGM02) | _BV(CS00);
OCR0A = 1;
OCR0B = 0;
// Make the 250 kHz rolling
while (1) {
_delay_us(5);
if (OCR2B < 63)
OCR2B += 5;
else
OCR2B = 0;
}
}