40 Hz Square wave with 8kHz tone

Hi @wdunne

Further to my last post. Thinking about it, it's possible to overcome the 25% truncated pulses at the beginning and end of the 8kHz burst by inverting the phase and frequency correct signal. This means setting the OCR1A register to 999 instead of 0 during the no-signal phase of the output:

// Set-up hadware PWM on the Arduino UNO at 8kHz on digital pin D9, gated by 12.5ms switch
unsigned long previousTime;

void setup() { 
  pinMode(9, OUTPUT);                         // Set digital pin 9 (D9) to an output
  TCCR1A = _BV(COM1A1) | _BV(COM1A0);         // Enable the PWM output on digital pin 9 with an inverted output
  TCCR1B = _BV(WGM13) | _BV(CS10);            // Set phase and frequency correct PWM and no prescaler on timer 1
  ICR1 = 999;                                 // Set the PWM frequency to 8kHz: 16MHz / (2 * 8000) - 1
  OCR1A = 500;                                // Set duty-cycle to 50%: (999 + 1) / 2 = 500
  previousTime = micros();                    // Intialise the previous time
}

void loop() {
  unsigned long currentTime = micros();       // Update the current time
  static bool toggle = false;                 // Define the toggle variable
  
  if (currentTime - previousTime >= 12500)    // Time 12.5ms intervals
  {
    OCR1A = toggle ? 500 : 999;               // Set timer1's duty-cycle to either 50% or 0%
    toggle = !toggle;                         // Flip the toggle
    previousTime = currentTime;               // Update the previous time
  }
}
1 Like