Buzzer not working at required frequency

Thread Starter

sarvanan

Joined Aug 8, 2016
45
Hi,

I am working on PIC16LF1939. I have implemented Piezo buzzer but when I check the frequency is not at required 2.7khz. What could be the reason?
Here is my settings.

#define Piezo_freq 2700
#define _XTAL_FREQ 16000000
CCP2CON = 0x0C; /// PWM Mode
T2CON = 0x06; /// Enable TMR2 with pre-scaler = 16

PR2 = (uint8_t) (((_XTAL_FREQ) / (Piezo_freq * 4 * PIEZO_TMR2_PRESCALER)) - 1);

I always get 2.0 KHz with above values. What value needs to be changed to get 2.7 khz.

Thanks & regards,
Sarvanan.
 

JohnInTX

Joined Jun 26, 2012
4,787
At first glance your setup looks OK, prescaler is 16 and your formula for PR2 yields 92 decimal (if rounded, 91 if truncated) which should give a frequency of 2688Hz or 2717Hz respectively. You don't say what the duty cycle should be but for 50% I get 186 counts which puts 2Eh into PRxL and '10' into CCPxCON<5,4>.

My first check would be to examine PR2, PR1L and CCPxCON to see that the formula has calculated PR2 correctly. To see, run the code in MPLAB simulator and set a breakpoint after init then examine the registers or look at the disassembly listing.

Good luck!
 
Last edited:

AlbertHall

Joined Jun 4, 2014
12,345
The other thing to check is that the actual oscillator frequency is really 16MHz. The output frequency will scale with the oscillator frequency.
 

dannyf

Joined Sep 13, 2015
2,197
What value needs to be changed to get 2.7 khz.
the debugging for this like this should start with 1) is the crystal really 16Mhz? 2) is there overflow in the math, for each element? 3) are the control registers set right? 4) are there offset? ...

pay attention to integer promotion and your answer is right there, somewhere, :)
 

Thread Starter

sarvanan

Joined Aug 8, 2016
45
Hi All,

Thanks. Its an overflow in the math. Manual calculation comes to 91.59. But Software calculates as 126.
If i assign value as 91, it works perfectly.

Thanks & regards,
Sarvanan.
 

dannyf

Joined Sep 13, 2015
2,197
Its an overflow in the math.
the important thing in cases like this is to understand why there is an overflow so you can prevent it in the future. integer promotion, being one of the simplest concept, is also one that even experienced programmers have trouble grasping.

But Software calculates as 126.
126 + 256 = 382 = 383-1 -> that number ("383") should ring a bell here, if you are an expert in integer promotion.
 
Top