Skip to content

Instantly share code, notes, and snippets.

@brennon
Created February 5, 2012 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brennon/1742859 to your computer and use it in GitHub Desktop.
Save brennon/1742859 to your computer and use it in GitHub Desktop.
// Interrupt service routine called to generate PWM compare values
ISR(TIMER1_COMPA_vect) {
// unsigned long == 32-bit
unsigned long sine_0, sine_1;
// These are the two ADC 'readings'. I've added a check that ensures that each remains >= 1023.
unsigned long reading_0 = (unsigned long) adc_readings[0] > 1023 ? 1023: (unsigned long) adc_readings[0];
unsigned long reading_1 = (unsigned long) adc_readings[1] > 1023 ? 1023: (unsigned long) adc_readings[1];
// These are the two samples from the wavetable. Also added checks that ensure that each remain >= 255.
unsigned long wave_0 = (unsigned long) pgm_read_byte(&sinewave_data[sample_0]) > 255 ? 255 : (unsigned long) pgm_read_byte(&sinewave_data[sample_0]);
unsigned long wave_1 = (unsigned long) pgm_read_byte(&sinewave_data[sample_1]) > 255 ? 255 : (unsigned long) pgm_read_byte(&sinewave_data[sample_1]);
// Generate sine wave for each channel.
sine_0 = reading_0 * wave_0;
sine_1 = reading_1 * wave_1;
// Sum sine waves and update compare register. Have tried shifting further. This produces no output.
OCR2A = (sine_0 + sine_1) >> 11;
// These both work, however, so I'm clearly having an overflow issue:
// OCR2A = sine_0 >> 10;
// OCR2A = sine_1 >> 10;
}
// Tested with this in another program:
void setup() {
// Force maximum value for mock ADC readings.
unsigned long reading_0 = 1023;
unsigned long reading_1 = 1023;
// Force maximum value for mock wavetable readings.
unsigned long wave_0 = 255;
unsigned long wave_1 = 255;
// Multiply those.
unsigned long sine_0 = reading_0 * wave_0;
unsigned long sine_1 = reading_1 * wave_1;
// Look at sums both as unsigned longs and as chars.
unsigned long compare_ul = (sine_0 + sine_1) >> 11;
unsigned char compare_char = (sine_0 + sine_1) >> 11;
// Printing out all of the above confirms that the arithmetic is NOT overflowing. I get 254 for both
// compare_ul and compare_char, as expected.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment