A simple PWM beep using timers 1 and 2

I am writing a simple beep function.
Yes, I know I can do this using the Arduino tone() function, but I'm trying to implement
this beep function using low-level timer control.

In the following code, timer 2 generates a periodic interrupt which calculates the amplitude of the beep sine wave and timer 1 generates the beep PWM waveform.

As written, it does not work, so I am asking for help. What am I missing?

typedef void (*func_t)(void);
volatile func_t func_ptr;

void beep(uint8_t sw) {
if (sw == ON) {
// turn on
func_ptr = beep_isr;
TCCR1A |= (1 << COM1A1);
TIMSK2 |= (1 << OCIE2A);
} else {
// turn off
TCCR1A &= ~(1 << COM1A1);
TIMSK2 &= ~(1 << OCIE2A);

// beep interrupt handler
void beep_isr() {
minsky(); // calculate sine value msin
OCR1AL = (msin >> ((16-cwvol) >> 1)) + 128;

// timer2 interrupt handler

Code tags.
The rest of your code.

Welcome to the forums. Please read this and then edit your post to include code tags and the entire sketch.

How to get the best out of this forum - Using Arduino / Installation & Troubleshooting - Arduino Forum

My question is about timer operation. I hope enough code there to understand how I am trying to control the timers.

You are missing setup() and loop().
You are missing declarations for 'ON', 'T2OCRX', 'msin', 'cwvol', and the minsky() function.

Looks OK to me, assuming all of the missing code is perfect and your wiring is correct.

Thanks John, I got it working. And you are right, the code I posted worked fine. The problem I was having was in a different area. Process of elimination. Marking this issue as closed.

Still missing the code tags.

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