Edit frequency code for internal crystal 8khz

Hey Guys, I've had this code for a while to send a 38khz signal to a proximity sensor (tsop and emitter pair). It works fine but I want to do some breadboard tests of the 328PU running on internal crystal at 8khz.
How could I edit the code to work at this lower frequency and still output 38khz.

Thanks.

volatile byte pulse = 0;

ISR(TIMER2_COMPB_vect){  
    pulse++;
  if(pulse >= 8) { 
    pulse =0;
    TCCR2A ^= _BV(COM2B1); 
  }
}

void setIrModOutput(){  
  pinMode(3, OUTPUT);
  TCCR2A = _BV(COM2B1) | _BV(WGM21) | _BV(WGM20); 
  TCCR2B = _BV(WGM22) | _BV(CS22);
  OCR2A = 51; // defines the frequency 51 = 38.4 KHz, 54 = 36.2 KHz, 58 = 34 KHz, 62 = 32 KHz
  OCR2B = 26;  
  TCCR2B = TCCR2B & 0b00111000 | 0x2; 
}

void setup(){
  setIrModOutput();
  TIMSK2 = _BV(OCIE2B); 
}

void loop(){
}

In general, when you switch from 16 MHz to 8 MHz you need to cut these values in half.

Did you mean 8MHz?

Also, it's not an internal crystal. It's an internal oscillator, which won't be as stable or accurate as a crystal.

Thanks John. I went with 0CR2A =26; and OCR2A = 13; and that seems to do it.
Another quick question. I've noticed that this modulated output ( and this is not related to my frequency request) only measures
1.3V is that typical. I don't have a lot of experience with square waves.

Yea I meant 8mhz, good catch. I appreciate the crystal is more reliable.
It's all about the testing.

Did you forget to set the output pins to OUTPUT?

Hey John, no I couldn't forget, the pinmode 3 OUTPUT is stipulated in the same code I posted here. When I measure that Arduino pin 3 it reads roughly 1.3V. It still powers the emitter fine but I was thinking of adding a second emitter which is why I asked.

How did you measure that? A DMM reading may not be reliable. You need an oscilloscope to be sure what is really going on. For example is the signal a true square wave (50% duty cycle). If the duty cycle is around 25%, that might explain the voltage reading from your DMM.

I used a multimeter. Do you know where duty cycle is represented in the code above.

As I understand it, OCR2B sets the duty cycle, and for 50% duty cycle it should be half the value of OCR2A, which you seem to be doing. But I know from experience that setting these timers up can be tricky. If some of the control register bits are not set correctly, the timer can be in a different mode than intended, and then OCR2A and OCR2B have slightly different effects. Checking the output with a scope would confirm the actual frequency, voltage and duty cycle which would tell you if the timer setup is wrong or your DMM isn't able to measure it accurately, or even if the pin is damaged or faulty.

Thanks PaulRB, appreciated.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.