Infrared Barrier: Modulating a 38kHz carrier at 1kHz with an Arduino Nano Every

I recently received a request from a reader of my Far Inside The Arduino: Nano Every Supplement. He needed to create a 38kHz carrier modulated at 1kHz for a project he was building with the Arduino Nano Every and was thwarted by available code for the Uno which would not compile on the Nano Every. Naturally, it was caused by the totally different Timer/Counters in the ATmega4809.

It was possible to get what he wanted by combining two example programs in the book. By his suggestion, I am posting my response to his request and the solution code here for others having this issue.

 I ended up using Timer/Counters TCB0 and TCB1 which the Arduino library only uses for AnalogWrite (PWM) on pins 6 and 3. The signal output in this case will be on 6 only and all other functionality is undisturbed.
I started out with the TCB_PWM example which configures TCB0 for a fast 8-bit PWM. It was modified so that it uses systemclock/2 (8MHz) as the clock source, and sets the period to be 8000000L/38000L ticks with the pulse width set to half that to get a 50% duty cycle. The duty cycle can be changed programmatically by altering the TCB0.CCMPH register.
Then I incorporated parts of the TCB_INT example modified to use TCB1. It’s used in Periodic Interrupt mode and configures for an interrupt every 500µs, which will give a modulation frequency of 1kHz. The interrupt routine toggles the TCB0 output on and off.  

The code is:

void setup() {
  // Make D6 an output pin, so when we disable the TCB0 
  // output the pin is still driven
  pinMode(6, OUTPUT);
  
  // We use TCBO to generate the output. Note that you can change the duty cycle
  // by varying TCB0.CCMPH. It is just the proportion of the period, 
  // set in TCB0.CCMPL.
  TCB0.CTRLA = 0; // Turn off channel for configuring
  TCB0.CTRLB = 0x17; // output enabled, PWM mode
  TCB0.CCMPL = 8000000L/38000L - 1; // Set period as close to 
                                    // giving 38kHz as we can achieve
  TCB0.CCMPH = (8000000L/38000L)/2; // 50% duty cycle
  TCB0.CTRLA = 3; // Enable and use system clock/2

  // We use TCB1 to modulate. It runs in Periodic Interrupt Mode 
  // (see example TCB_INT).
  // Code from TCB_INT example incorporated here in setup and the ISR.
  TCB1.CTRLA = 0; // Turn off channel for configuring
  TCB1.CTRLB = 0x0; // Periodic Interrupt Mode
  TCB1.CCMP = 7999; // 8000 clocks per period, 500us
  TCB1.INTCTRL = 1; // Enable interrupts
  TCB1.CTRLA = 1; // Enable and use system clock
}

ISR(TCB1_INT_vect) {
  TCB0.CTRLB ^= 0x10; // Toggle the TCB0 output enable bit
  TCB1.INTFLAGS = 1; // Clear the interrupt
}

void loop() {
}