Using timer0 on Attiny85 to generate 38Khz pulse

Hi,

I found the below code in Attiny 45 38khz flash - Microcontrollers - Arduino Forum by dc42.
However, the code uses Timer1 on PB1 to generate the required pulse.

For me, I have a customized board where PB1 is already tied to another task and only PB0 and PB2 are free. Can some help me understand how to port this to use timer0? I am not familiar with timers and not able to understand.

void setup()
{
  PORTB = 0;
  DDRB =  0b00000010;		// set PB1 (= OCR1A) to be an output
}

// Set the frequency that we will get on pin OCR1A but don't turn it on
void setFrequency(uint16_t freq)
{
 uint32_t requiredDivisor = (F_CPU/2)/(uint32_t)freq;

 uint16_t prescalerVal = 1;
 uint8_t prescalerBits = 1;
 while ((requiredDivisor + prescalerVal/2)/prescalerVal > 256)
 {
   ++prescalerBits;
   prescalerVal <<= 1;
 }
 
 uint8_t top = ((requiredDivisor + (prescalerVal/2))/prescalerVal) - 1;
 TCCR1 = (1 << CTC1) | prescalerBits;
 GTCCR = 0;
 OCR1C = top;
}

// Turn the frequency on
void on()
{
 TCNT1 = 0;
 TCCR1 |= (1 << COM1A0);
}

// Turn the frequency off and turn off the IR LED.
// We let the counter continue running, we just turn off the OCR1A pin.
void off()
{
 TCCR1 &= ~(1 << COM1A0);
}

Thanks for any help.

Generating that output relies on being able to use the hardware output compare module - it can generate output on PB1 or PB4.

It cannot generate output on PB0 or PB2.

I am not familiar with timers and not able to understand.

It should not be difficult to use Timer0 to generate a 38 kHz signal, but if you don't want to learn how to use the timers, consider posting on the Gigs and Collaborations forum section.

You may be asked to pay for the help.

DrAzzy:
Generating that output relies on being able to use the hardware output compare module - it can generate output on PB1 or PB4.

It cannot generate output on PB0 or PB2.

Can we not use timer 0 to generate output on PB0?

Seems possible at first glance, but nope - Prescaler calculations will be different, as timer0 doesn't have as many choices, but you don't need to prescale for 38kHz... But you need to set the TOP, and the only modes that let you do that use OCR0A to set TOP... so you can only use channel B of Timer0 for PWM... which is on PB1, too!

It is possible to generate 38kHz with 50% duty even on PB0: you set OCR0A to get compare match every 1/(2*38) ms, use a mode that has OCR0A as TOP and use the setting that toggles OC0A at compare match.

EDIT: PB0 is also /OC1A which may probably be used by some trick to generate the carrier too.

PB2 is clock input/output of USI. IIRC it could be used too generate 50% duty waveform as a "clock".