I'm trying to get some C code that runs on a PIC18F, working on an Arduino '328P. It uses an 8-bit timer, PWM, and a LUT to generate sine waves. I hope to get it going using Timer2 on a Nano.
The PIC code is from this blog post by Roman Black. I understand what the PIC code is doing, but I can't manage to translate the modes and flags into Nano-land.
The PIC is running at 8MHz, the Nano at 16MHz with no pre-scale. PIC uses a PWM period of 128, Nano uses 256. I've taken some liberties here with the PIC values but the spirit is the same.
const byte sin[64] = {...some values};
uint32_t wave;
uint32_t incr = 17179869; // for 1000Hz
PR2 = (128-1); // PWM period = 128
while(1) {
while(!PIR1.TMR2IF); // align to start of PWM cycle
PIR1.TMR2IF = 0;
wave += incr;
CCPR2L = sin[(wave >> 24) & 0x3F]; // load into PWM module
}
For completeness, the PIC data sheet is here
I have the following Nano setup, with the goal of Fast PWM, no pre-scale, output at pin 11 (the "B" channel of Timer2).
TCCR2A = bit(COM2A0)
| bit(COM2B1)
| bit(WGM21)
| bit(WGM20);
TCCR2B = bit(WGM22) | bit(CS20);
Generating the wave then looks like:
while (true) {
while ((TIMSK2 | bit(OCIE2B)) == 0) {}
TIMSK2 |= bit(OCIE2B);
wave += incr;
OCR2A = sinLUT[(wave >> 24) & 0x3f];
}
It doesn't generate anything like a sine wave at 1000Hz, so I'm clearly missing something. FWIW, I filter the output with 2.2K/100nf
EDIT: UPDATED
As requested, here's the latest setup. Output seems to glitch slightly, although I can't see where.
pinMode(4, OUTPUT); // for stable trigger
pinMode(3, OUTPUT); // timer2 output B
TIMSK2 |= bit(TOIE2); // enable TOV2 = timer2 overflow
TCCR2A = bit(COM2B1) // fast PWM, top = 0xFF
| bit(WGM20) // PWM Mode 3
| bit(WGM21);
TCCR2B = bit(CS20); // no prescale
Then:
ISR(TIMER2_OVF_vect) { // PWM cycle rate
static uint8_t div;
static uint32_t wave;
const unit32_t incr = 1024 * 64 * 65536 / 62500 // 1024 Hz
TIFR2 |= bit(TOV2); // clear the interrupt
if (div++ == 0) PORTD ^= bit(4); // scope trigger
wave += incr;
OCR2B = sinLUT[(wave >> 16) & 0x3f];
}