Simple Sweep Generator


Not a very sophisticated one. Just to play with it for a short while.

/*
 * simple sweep generator
 */
const byte speakerPin = 9; // PWM pin OC1A
const byte ctrlPin = A5;
const word sampleRate = 44000;
const int N = 256;
byte samples[N + 1];
byte ocr2a;

void setup() {
  Serial.begin(9600);
  Serial.println(__FILE__);
  pinMode(speakerPin, OUTPUT);
  pinMode(ctrlPin, OUTPUT);
  for (byte i = 0; i <= N/4; i++) {
    byte b = 128 + 127 * sin(2 * PI * i / N);
    samples[i] = b;
    samples[N/2 - i] = b;
    samples[N/2 + i] = -b;
    samples[N - i] = -b;
  }
  for (int i = 0; i < N; i++) Serial.println(samples[i]);
  // Timer1:
  TCCR1A = 0x81;
  TCCR1B = 1;
  // Timer 2:
  TCCR2A =   2; // CTC mode
  TCCR2B =   2; // prescaler: 8
  byte PS =  8;
  ocr2a  = F_CPU / PS / sampleRate - 1; 
  OCR2A  = ocr2a;
  TIMSK2 =   2; // Output Compare A Match Interrupt Enable
}

void loop() {
  if (ocr2a-- == 0) ocr2a = 100;
  OCR2A = ocr2a;
  Serial.println(ocr2a);
  delay(100);
  }

ISR(TIMER2_COMPA_vect) {
  static byte w;
  OCR1A = samples[w++];
  if (w == 0) asm("sbi 6,5"); // toggle A5 to trigger the scope
}



contact: nji(at)gmx.de