Looptober24/04KarplusStrongFish/04KarplusStrongFish.ino

97 lines
2.0 KiB
C++

// Very basic Karplus-Strong
// based on this explanation http://sites.music.columbia.edu/cmc/MusicAndComputers/chapter4/04_09.php
#include <Adafruit_MCP4728.h>
#include <Wire.h>
Adafruit_MCP4728 mcp;
#define nsamp 256
#define dacmax 256
unsigned int phase;
unsigned int length;
unsigned int repeats;
int note = 0;
//int freqs[] = { 64, 56, 51, 48, 42, 38, 34, 32, 28, 25, 24, 21, 19, 17, 16 };
//int tune2[] = { 2, -1, -1, 2, -1, -1, 3, -1, 2, -1, -1, -1, 0, -1, -1, -1 };
//int tune2[] = { 2, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, 4, -1, -1, -1 };
int freqs[] = { 128, 112, 102, 96, 84, 76, 64, 56, 50, 48, 42, 38, 34, 32 };
int tune2[] = { 0, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1 };
byte waveform[nsamp];
int pd = 30;
void setup() {
cli();
//set timer1 interrupt at 1Hz
TCCR1A = 0;// set entire TCCR1A register to 0
TCCR1B = 0;// same for TCCR1B
TCNT1 = 0;//initialize counter value to 0
// set compare match register for 1hz increments
//OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
//OCR1A = 7812;// = (16*10^6) / (1*1024) - 1 (must be <65536)
OCR1A = 2000;
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS10 and CS12 bits for 1024 escaler
TCCR1B |= (1 << CS12) | (1 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei();
if (!mcp.begin(0x64)) {
while (1) {
delay(100);
}
}
randomSeed(analogRead(A0));
mcp.setSpeed(800000L);
phase=0;
note=0;
}
ISR(TIMER1_COMPA_vect){//timer1
if( tune2[note] > -1 ) {
length=freqs[tune2[note]];
for (int i=0; i<nsamp; ++i){
waveform[i]=random(256);
}
}
note++;
if( note > 15 ) {
note = 0;
}
pd = analogRead(A0) >> 4;
}
void loop() {
byte s1, s2;
int p0 = phase;
int p1 = phase - pd;
if( p1 < 0 ) {
p1 += length;
}
phase += 1;
if( phase >= length ) {
phase = 0;
}
s1 = waveform[p1];
s2 = waveform[p0];
waveform[p0] = ( s1 & s2 ) + ((s1 ^ s2) >> 1);
mcp.fastWrite(s1 << 4, 0, 0, 0);
}