Looptober24/27CloudII/27CloudII.ino

146 lines
2.8 KiB
Arduino
Raw Normal View History

2024-10-26 07:16:45 +00:00
// Better sequencer which uses interrupts
#include <Adafruit_MCP4728.h>
#include <Wire.h>
Adafruit_MCP4728 mcp;
float tuning[37];
float voltrange = 4.85; // measured this, probably not accurate
float octave = 4096.0 / voltrange; // number of DAC steps in an octave
// melody
// int pitch[] = { 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
// -1, -1, -1, -1, -1, -1, -1, -1,-1, -1, -1, -1,2, -1, -1, -1, };
// int dur[] = { 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, };
// hi hat
int pitch[] = { 1, -1, 3, -1, 4, -1, 5, -1, };
int note = 0;
int phrase = 8;
int grains_n = 12;
int grainc = 0;
int grainsize = 20;
int s;
int bpm = 9000;
float beat_s = 60.0 / (float)bpm;
float note_s = beat_s * grains_n;
float beat_m = 1000.0 * beat_s;
bool noteon = false;
int beat = false;
long notestart, notedur, barstart;
int target, slew;
float decay = 0.1;
void setup() {
Serial.begin(115200);
float freq = (float)bpm / 60.0;
int ocr = round(16000000.0 / (1024.0 * freq )) - 1;
Serial.println(ocr);
if( ocr < 65536 ) {
cli();
TCCR1A = 0;// set entire TCCR1A register to 0
TCCR1B = 0;// same for TCCR1B
TCNT1 = 0;//initialize counter value to 0
OCR1A = ocr; //ocr;
// 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();
} else {
Serial.println("BPM out of range");
}
if (!mcp.begin(0x64)) {
while (1) {
delay(100);
}
}
// randomSeed(analogRead(A0));
mcp.setSpeed(800000L);
make_tuning(12);
note=0;
notestart=millis();
}
void make_tuning(int edo) {
float n0 = 0;
float edof = (float)edo;
for( int i = 0; i < 37; i++ ) {
tuning[i] = round(n0 + octave * (float)i / edof);
}
}
ISR(TIMER1_COMPA_vect){ // called once every beat
beat = true;
}
bool play_grain(int dur) {
return true;
// return random(0, 1000) > (float)dur * decay;
}
void loop() {
int now = millis();
if( beat ) {
beat = false;
noteOn(pitch[s], now - notestart);
grainc++;
if( grainc > grains_n ) {
grainc = 0;
s += 1;
if( s == phrase ) {
s = 0;
notestart = now;
}
grainc = 0;
Serial.println(s);
}
} else {
if( noteon && now - notestart > grainsize ) {
noteOff();
}
}
}
void noteOn(int note, int dur) {
Serial.println("noteOn");
if( note > -1 && play_grain(dur) ) {
mcp.setChannelValue(MCP4728_CHANNEL_A, tuning[note]);
mcp.setChannelValue(MCP4728_CHANNEL_B, 4095);
noteon = true;
}
}
void noteOff() {
mcp.setChannelValue(MCP4728_CHANNEL_B, 0);
noteon = false;
Serial.println("noteOff");
}