We can use the tone()
function for the generation of square waves. However, it has some limitations
tone()
function generates frequency on only 1 pin at a time.So we will use Timer1 and Timer2 for the toggling of pins (i.e. generating the frequency).
void setup() {
cli(); // Disable interrupts during configuration
// Timer2 configuration for ~307 kHz on D11 (OC2A)
TCCR2A = (1 << WGM21) | (1 << COM2A0); // CTC mode, toggle OC2A on match
TCCR2B = (1 << CS20); // Prescaler = 1
OCR2A = 25; // Compare match value for ~307 kHz
// Timer1 configuration for ~570 kHz on D9 (OC1A)
TCCR1A = (1 << COM1A0); // Toggle OC1A on compare match
TCCR1B = (1 << WGM12) | (1 << CS10); // CTC mode, prescaler = 1
OCR1A = 13; // Compare match value for ~570 kHz
// Set pins as output
pinMode(9, OUTPUT);
pinMode(11, OUTPUT);
sei(); // Enable interrupts
}
void loop() {
while (true) {
//In this loop, the Microcontroller monitors and performs important tasks constantly.
}
}
WGM21
set): Timer2 resets when reached at OCR2A value. OC2A
(COM2A0
set): The pin automatically toggles.CS20
set): Timer2 runs at full speed (16 MHz).OCR2A
= 25: Generates 307 kHz.WGM12
set): Timer1 resets when reached at OCR1A value.OC1A
(COM1A0
set): Pin toggles on compare match.CS10
set): Runs at full 16 MHz.OCR1A
= 13: Generates 570 kHz.cli()
disables interrupts to ensure configuration stability.sei()
enables interrupts after configuration is complete.loop()
function is needed as everything runs in hardware.