80. Simultaneous Square Wave Generation

Using tone() function

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). 

Connection diagram

  • D9 → 570 kHz frequency
  • D11 → 307 kHz frequency
  • GND → GND

 

Code 

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.
  }
}

 

Code Explanation:

  1. Timer2 Setup (Pin 11, 307 kHz)
    • CTC Mode (WGM21 set): Timer2 resets when reached at OCR2A value.
    • Toggle Mode on OC2A (COM2A0 set): The pin automatically toggles.
    • Prescaler = 1 (CS20 set): Timer2 runs at full speed (16 MHz).
    • OCR2A = 25: Generates 307 kHz.
  2. Timer1 Setup (Pin 9, 570 kHz)
    • CTC Mode (WGM12 set): Timer1 resets when reached at OCR1A value.
    • Toggle Mode on OC1A (COM1A0 set): Pin toggles on compare match.
    • Prescaler = 1 (CS10 set): Runs at full 16 MHz.
    • OCR1A = 13: Generates 570 kHz.
  3. Interrupts and Efficiency
    • cli() disables interrupts to ensure configuration stability.
    • sei() enables interrupts after configuration is complete.
    • loop() function is needed as everything runs in hardware.

 

 

Output

 Hardware setup

 

 

DSO output

 

Video

 

 

 

Submit Your Solution

Note: Once submitted, your solution goes public, helping others learn from your approach!