I think I got it this time. You want a standard 38 KHz pulse, which itself turns on and off at 500 Hz with a duty cycle controlled by a pot? This seems to do it:
// Example of modulating a 38 KHz carrier frequency at 500 Hz with a variable duty cycle
// Author: Nick Gammon
// Date: 24 September 2012
const byte POTENTIOMETER = A0;
const byte LED = 9; // Timer 1 "A" output: OC1A
// 16 MHz clock divided by 500 Hz frequency desired (allowing for prescaler of 128)
const long timer2_OCR2A_Setting = 16000000L / 500L / 128L;
ISR (PCINT2_vect)
{
// if pin 3 now high, turn on toggling of OC1A on compare
if (PIND & _BV (3))
{
TCCR1A |= _BV (COM1A0) ; // Toggle OC1A on Compare Match
}
else
{
TCCR1A &= ~_BV (COM1A0) ; // DO NOT Toggle OC1A on Compare Match
digitalWrite (LED, LOW); // ensure off
} // end of if
} // end of PCINT2_vect
void setup() {
pinMode (LED, OUTPUT);
pinMode (3, OUTPUT); // OC2B
// set up Timer 1 - gives us 38.095 KHz
TCCR1A = 0;
TCCR1B = _BV(WGM12) | _BV (CS10); // CTC, No prescaler
OCR1A = (16000000L / 38000L / 2) - 1; // zero relative
// Timer 2 - gives us our 1 mS counting interval
// 16 MHz clock (62.5 nS per tick) - prescaled by 128
// counter increments every 8 uS.
// So we count 250 of them, giving exactly 2000 uS (2 mS period = 500 Hz frequency)
TCCR2A = _BV (WGM20) | _BV (WGM21) | _BV (COM2B1); // Fast PWM mode
TCCR2B = _BV (WGM22) | _BV (CS20) | _BV (CS22) ; // prescaler of 128
OCR2A = timer2_OCR2A_Setting - 1; // count up to 250 (zero relative!!!!)
// pin change interrupt
PCMSK2 |= _BV (PCINT19); // want pin 3
PCIFR |= _BV (PCIF2); // clear any outstanding interrupts
PCICR |= _BV (PCIE2); // enable pin change interrupts for D0 to D7
} // end of setup
void loop()
{
// alter Timer 2 duty cycle in accordance with pot reading
OCR2B = (((long) (analogRead (POTENTIOMETER) + 1) * timer2_OCR2A_Setting) / 1024L) - 1;
// other stuff here
} // end of loop
Results:
I am outputting 38 Khz on pin 9 (output of timer 1 "A" side) and turning that on and off with a pin-change interrupt. The interrupt is generated by timer 2 "B" side which is the output of a fast PWM 500 Hz timer where the duty cycle is variable by the potentiometer input.
You can see from the image when pin 3 (timer 2) goes on and off (in this case with a 24.8% duty cycle) and that the 38 KHz signal on pin 9 is switched on and off corresponding to that.