Files
GravityFW/Software/Gravity/Gravity.ino
2025-04-03 21:31:11 +03:00

584 lines
18 KiB
C++

#include <Wire.h>
#include <RotaryEncoder.h>
#include <FlexiTimer2.h>
#include <EEPROM.h>
#include <U8g2lib.h>
#include <avr/wdt.h>
#include <NeoHWSerial.h>
#include "config.h"
#include "fonts.h"
#define VERSION "V:1.2A2"
uint8_t memCode = '0'; //Change to different letter if you changed the data structure
uint16_t CV1Calibration = 512;
uint16_t CV2Calibration = 512;
bool showDone = false;
const int subDivs[] = { -24, -12, -8, -6, -4, -3, -2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 16, 24, 32, 64, 128 }; //positive - divide, negative - multiply, 0 - off
uint8_t bpm = 130;
uint8_t bpmModulationChannel = 200; //0 - CV1, 1 - CV2, 255 - OFF
uint8_t bpmModulationRange = 0;
enum modes {Clock, Random, Sequencer, Swing, Gate};
struct channel {
enum modes mode : 3; //mv: 7. 0 - CLK, 1 - RND, 2 - SEQ, 3 - SWING, 4 - Gate
uint8_t subDiv : 5; //mv: 31
uint8_t random : 4; //mv: 15
uint8_t seqPattern : 5;
uint8_t CV1Target : 3; //0 - Off, 1 - Subdiv, 2 - RND, 3 - SeqPattern
uint8_t CV2Target : 3;
uint8_t swing : 3;
uint8_t offset : 7; //mv: 127
uint8_t gate : 7;
bool isMute : 1;
};
channel channels[7] = { //array of channel settings
{ 0, 7, 0, 0, 0, 0, 0, 0, 1, 0 },
{ 0, 7, 0, 0, 0, 0, 0, 0, 1, 0 },
{ 0, 7, 0, 0, 0, 0, 0, 0, 1, 0 },
{ 0, 7, 0, 0, 0, 0, 0, 0, 1, 0 },
{ 0, 7, 0, 0, 0, 0, 0, 0, 1, 0 },
{ 0, 7, 0, 0, 0, 0, 0, 0, 1, 0 },
{ 0, 7, 0, 0, 0, 0, 0, 0, 1, 0 }
};
struct sequence {
uint32_t sequence;
uint8_t length : 5 ; //don't forget to add 1 where needed, values 0 - 31
};
sequence sequences[] {
{0b000000000000000001001000100010001, 15},
{0b000000000000000000000100000010000, 11},
{0b000000000000000000001001001001001, 6},
{0b000000000000000001100110011001100, 20},
{0b000000000000000001110111011101110, 30},
{0b000000000000000000101010001010100, 31},
{0b000000000000000000111111111011111, 15},
{0b000000000000000001101101110110011, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15},
{0b000000000000000000000000000000000, 15}
};
uint8_t currentStep[7] = {0};
int8_t stepNumSelected = 0;
uint8_t patternToEdit;
unsigned int channelPulseCount[7];
unsigned int channelPulsesPerCycle[7];
uint8_t sixteenthPulseCount = 0;
int playingModes[7]; // should be renamed to currentSubdivs or something. Updated from channels object on beat and with applied CV modulation
int playingModesOld[7];
uint16_t pulsePeriod;
bool isPlaying;// = false; // replace with some flags like uint8_t status where 1xxxxxx isPlaying, x1xxxxx isRecording etc
bool isRecording = false;
bool recordToNextStep = false;
bool MIDIClockReceived = false;
uint16_t tickCount = 0;
uint16_t pulseCount = 0;
uint8_t masterClockMode = 0; // 0 - internal, 1 - external 24ppqn, 2 - MIDI
uint8_t extClockPPQN = 0; // 0 - 24, 1 - 4 (1/16)
uint8_t extraChannel = 0; // 0 - off, 1 - pulse out = 7th channel
uint32_t lastExtPulseTime = 0;
uint32_t newExtPulseTime = 0;
bool needPulseReset[] = { true, true, true, true, true, true, true }; //to optimise, can be switched to uint8_t
uint16_t gateLengthTime[] = {0, 0, 0, 0, 0, 0, 0};
uint16_t gateCountDown[7];
bool stepIsOdd = 1;
uint8_t displayTab = 0;
bool insideTab = false;
uint8_t menuItem = 0;
bool menuItemSelected = false;
uint8_t lastMenuItem = 3;
uint8_t displayScreen = 0; //0 - main, 1 - sequencer, 2 - settings
int16_t CV1Input = 0;
int16_t CV2Input = 0;
bool playBtnPushed = false;
bool shiftBtnPushed = false;
bool encBtnPushed;
int encPositionOld = 0;
uint8_t encDirectionOld = 0;
uint32_t encPressedTime;
uint32_t encReleasedTime;
uint32_t playPressedTime;
uint32_t playReleasedTime;
uint32_t shiftPressedTime;
uint32_t shiftReleasedTime;
int extResetCountdown;
int extTriggerCount;
//uint32_t lastInteractionTime; // used for display timeout
U8G2_SSD1306_128X64_NONAME_2_HW_I2C u8g2(U8G2_R2, SCL, SDA, U8X8_PIN_NONE);
RotaryEncoder encoder(ENC_D1_PIN, ENC_D2_PIN, RotaryEncoder::LatchMode::TWO03);
String version;
void setup() {
version = F(VERSION);
NeoSerial.begin(31250);
NeoSerial.attachInterrupt(receiveMIDI);
pinMode(ENC_BTN_PIN, INPUT_PULLUP);
pinMode(START_STOP_BTN_PIN, INPUT_PULLUP);
pinMode(SHIFT_BTN_PIN, INPUT_PULLUP);
pinMode(EXT_INPUT_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(EXT_INPUT_PIN), externalClock, FALLING);
for (uint8_t i = 0; i < 6; i++) {
pinMode(outsPins[i], OUTPUT);
}
pinMode(clockOutPin, OUTPUT);
loadState();
u8g2.begin();
checkScreenRotation();
updateScreen();
calculateCycles();
calculateBPMTiming();
resetClocks();
FlexiTimer2::set(1, 1.0 / 10000, clock); // 1.0/1000 = 1ms period
FlexiTimer2::start();
}
void loop() {
if (masterClockMode == 1 && extClockPPQN == 1) {
calculateBPMTiming();
}
checkInputs();
}
void sendMIDIClock() {
NeoSerial.write(0xF8);
}
void sendMIDIStart() {
NeoSerial.write(0xFA);
}
void sendMIDIStop() {
NeoSerial.write(0xFC);
}
void receiveMIDI( uint8_t msg, uint8_t status ) {
if (masterClockMode == 2) {
if (msg == 0xF8) { //Clock tick
MIDIClockReceived = true;
} else if (msg == 0xFC) { //stop
isPlaying = false;
} else if (msg == 0xFA || msg == 0xFB) { //start and continue
isPlaying = true;
}
}
}
void clock() {
if (isPlaying) {
// Action on each pulse
if (tickCount == 0) {
sendTriggers();
if (!extraChannel) {
digitalWrite(clockOutPin, HIGH);
}
sendMIDIClock();
}
//this part gets the Pulse and Ticks ticking
//it's placed after the triggers to avoid problems on the start (when pulseCount==0)
tickCount++;
if (masterClockMode == 0) {
if (tickCount >= pulsePeriod) {
tickCount = 0;
if (pulseCount < (PPQN - 1)) { //-1 is here to avoid extra IF to reset to 0
pulseCount++;
} else {
pulseCount = 0;
}
if (bpmModulationRange != 0) {
calculateBPMTiming();
for (uint8_t i; i < 7; i++) {
if (channels[i].mode == Gate) {
calculateGate(i);
}
}
}
}
}
if (masterClockMode == 1 && extClockPPQN == 1) {
if (tickCount >= pulsePeriod && pulseCount < (PPQN - 1)) { // ((6 * (extTriggerCount + 1)) - 1)) { //this formula puts it out of sync, so there's PPQN-1 for now
tickCount = 0;
pulseCount++;
}
}
if (masterClockMode == 2 && MIDIClockReceived) {
tickCount = 0; //to make things happen in the main clock function
if (pulseCount < (PPQN - 1)) {
pulseCount++;
} else {
pulseCount = 0;
}
MIDIClockReceived = false;
}
// pull low all outputs after set pulse length
for (uint8_t i = 0; i < 7; i++) {
if (channels[i].mode != Gate && tickCount >= PULSE_LENGTH) { //everything but gate mode
digitalWrite(outsPins[i], LOW);
} else if (channels[i].mode == Gate && tickCount >= gateCountDown[i]) { //gate mode gateLengthTime[i] < pulsePeriod
digitalWrite(outsPins[i], LOW);
gateCountDown[i] = gateLengthTime[i];
} else if (channels[i].mode == Gate && gateCountDown[i] > pulsePeriod && tickCount == 0) {
gateCountDown[i] = gateCountDown[i] - pulsePeriod;
}
}
}
}
void externalClock() {
lastExtPulseTime = newExtPulseTime;
newExtPulseTime = millis();
if (masterClockMode == 1 && extClockPPQN == 0) { // EXT 24ppqn
if (!isPlaying) {
isPlaying = true;
}
//reset cycles if there were no pulses for a while
if ((newExtPulseTime - lastExtPulseTime) > 125) { //125ms is 20bpm
resetClocks();
}
tickCount = 0; //to make things happen in the main clock function
if (pulseCount < (PPQN - 1)) {
pulseCount++;
} else {
pulseCount = 0;
}
} else if (masterClockMode == 1 && extClockPPQN == 1) { //EXT 1/16
if (!isPlaying) {
isPlaying = true;
}
if ((newExtPulseTime - lastExtPulseTime) > 750) {
resetClocks();
extResetCountdown = 0;
extTriggerCount = 0;
}
if (extTriggerCount == 0) { //happens on beat
pulseCount = 0;
tickCount = 0;
}
if (extTriggerCount < 3) {
extTriggerCount++;
} else {
extTriggerCount = 0;
}
if (extResetCountdown < 4) { //reset on the second beat (5th pulse), so that BPM is already calculated correctly
extResetCountdown++;
} else if (extResetCountdown == 4) {
resetClocks();
extResetCountdown++; //to get out of the loop
}
}
}
void sendTriggers() { //rename to onPulse or something
for (uint8_t i = 0; i < (extraChannel ? 7 : 6); i++) {
if (playingModes[i] != subDivs[channels[i].subDiv] && playingModesOld[i] != playingModes[i]) {
needPulseReset[i] = true;
playingModesOld[i] = playingModes[i];
}
}
//16th notes for sequencer and swing
if (sixteenthPulseCount == 0) {
stepIsOdd = !stepIsOdd;
for (uint8_t i = 0; i < (extraChannel ? 7 : 6); i++) {
//pattern modulation
int seqMod = 0;
uint8_t seqPattern;
if (channels[i].CV2Target == 3) {
seqMod = map(CV2Input, -1, 1024, -8, 8); //-1 and 1024 are to try to make the last step not at max value (should make the range from -7 to +7)
} else if (channels[i].CV1Target == 3) {
seqMod = map(CV1Input, -1, 1024, -8, 8);
}
if (channels[i].seqPattern < 8 && channels[i].seqPattern + seqMod >= 8) {
seqPattern = 7;
} else if (channels[i].seqPattern < 8 && channels[i].seqPattern + seqMod < 0) {
seqPattern = 0;
} else if (channels[i].seqPattern >= 8 && channels[i].seqPattern + seqMod < 8) {
seqPattern = 8;
} else if (channels[i].seqPattern >= 8 && channels[i].seqPattern + seqMod >= 16) {
seqPattern = 15;
} else {
seqPattern = channels[i].seqPattern + seqMod;
}
bool currentStepValue = bitRead(sequences[channels[i].seqPattern].sequence, currentStep[i]);
if (channels[i].mode == Sequencer && currentStepValue && !channels[i].isMute) {
digitalWrite(outsPins[i], HIGH);
}
}
}
if (sixteenthPulseCount < (PPQN / 4) - 1) {
sixteenthPulseCount++;
if (sixteenthPulseCount > 3) { //quantization. might need fine-tuning
recordToNextStep = true;
}
} else {
sixteenthPulseCount = 0;
for (uint8_t i; i < 7; i++) {
if (channels[i].mode == Sequencer && currentStep[i] < sequences[channels[i].seqPattern].length) {
currentStep[i] ++;
} else {
currentStep[i] = 0;
}
}
recordToNextStep = false;
}
//switching modes on the beat and resetting channel clock
if (pulseCount == 0) {
calculateCycles();
for (uint8_t i = 0; i < (extraChannel ? 7 : 6); i++) {
if (needPulseReset[i] == true) {
channelPulseCount[i] = 0;
needPulseReset[i] = false;
}
if (channels[i].mode == Gate) {
calculateGate(i);
}
}
}
//multiplier
for (uint8_t i = 0; i < (extraChannel ? 7 : 6); i++) {
//RND modulation
uint8_t randMod = 0;
if (channels[i].CV1Target == 2) {
randMod = randMod + CV1Input;
}
if (channels[i].CV2Target == 2) {
randMod = randMod + CV2Input;
}
if (channels[i].CV1Target == 2 || channels[i].CV2Target == 2) {
randMod = map(randMod, 0, 1023, -5, +5);
}
uint8_t randAmount = channels[i].random + randMod;
if (randAmount > 100) {
randAmount = 0;
} else if (randAmount > 10) {
randAmount = 10;
}
if (!channels[i].isMute) {
if ((channels[i].mode == Swing && channelPulseCount[i] == 0 && stepIsOdd == 0)
|| (channels[i].mode == Swing && channelPulseCount[i] == channels[i].swing && stepIsOdd == 1) //swing
) {
digitalWrite(outsPins[i], HIGH);
}
if ((channels[i].mode == Clock && channelPulseCount[i] == channels[i].offset) //CLK with offset
|| (channels[i].mode == Random && channelPulseCount[i] == 0 && (random(10) + 1) > randAmount) //RND
|| (channels[i].mode == Gate && channelPulseCount[i] == 0) //Gate
) {
digitalWrite(outsPins[i], HIGH);
}
}
if (channelPulseCount[i] < channelPulsesPerCycle[i]) {
channelPulseCount[i]++;
} else {
channelPulseCount[i] = 0;
}
}
}
void calculateCycles() {
for (uint8_t i = 0; i < (extraChannel ? 7 : 6); i++) {
int mod = 0; //subdiv modulation happens here
if (channels[i].CV1Target == 1) {
mod = map(CV1Input, -1, 1024, -5, 5);
} else if (channels[i].CV2Target == 1) {
mod = map(CV2Input, -1, 1024, -5, 5);
}
playingModes[i] = subDivs[channels[i].subDiv - mod]; //subtracting because the innitial array is backwards
if (channels[i].mode == Sequencer || channels[i].mode == Swing) { //Sequencer and swing plays 1/16th
channelPulsesPerCycle[i] = (PPQN / 4) - 1;
} else if (playingModes[i] > 0) {
channelPulsesPerCycle[i] = (playingModes[i] * PPQN) - 1;
} else if (playingModes[i] < 0) {
channelPulsesPerCycle[i] = (PPQN / abs(playingModes[i])) - 1;
}
}
}
void calculateGate(uint8_t channel) {
//if (subDivs[channels[channel].subDiv] > 0) {
gateLengthTime[channel] = ((channelPulsesPerCycle[channel] + 1) * (pulsePeriod + 1) / 100) * channels[channel].gate;
gateCountDown[channel] = gateLengthTime[channel];
//}
}
void calculateBPMTiming() {
int mod = 0;
if (masterClockMode == 0) { //Internal clock
if (bpmModulationRange != 0 && bpmModulationChannel == 0) {
mod = map(CV1Input, 0, 1023, bpmModulationRange * -10, bpmModulationRange * 10);
} else if (bpmModulationRange != 0 && bpmModulationChannel == 1) {
mod = map(CV2Input, 0, 1023, bpmModulationRange * -10, bpmModulationRange * 10);
}
uint8_t calcbpm = bpm + mod;
if (calcbpm > MAXBPM) { calcbpm = MAXBPM; };
pulsePeriod = 600000 / (calcbpm * PPQN); // 600000.0 / ((float)(calcbpm * PPQN)) - floats eat up ~2% of program memory, but are they more precise? need to measure
} else if (masterClockMode == 1 && extClockPPQN == 1) { //for ext 1/16 clock
pulsePeriod = (newExtPulseTime - lastExtPulseTime) * 10 / 6;
}
}
void resetClocks() {
for (uint8_t i = 0; i < (extraChannel ? 7 : 6); i++) {
channelPulseCount[i] = 0;
digitalWrite(outsPins[i], LOW); //to avoid stuck leds
}
pulseCount = 0;
tickCount = 0;
sixteenthPulseCount = 0;
for (uint8_t i; i < 7; i++) {
currentStep[i] = 0;
}
stepIsOdd = 1;
}
void saveState() {
uint16_t addr = 0;
EEPROM.put(addr, bpm);
addr = addr + sizeof(bpm);
EEPROM.put(addr, bpmModulationChannel);
addr = addr + sizeof(bpmModulationChannel);
EEPROM.put(addr, bpmModulationRange);
addr = addr + sizeof(bpmModulationRange);
EEPROM.put(addr, masterClockMode);
addr = addr + sizeof(masterClockMode);
EEPROM.put(addr, channels);
addr = addr + sizeof(channels);
EEPROM.put(addr, sequences);
addr = addr + sizeof(sequences);
EEPROM.put(addr, CV1Calibration);
addr = addr + sizeof(CV1Calibration);
EEPROM.put(addr, CV2Calibration);
addr = addr + sizeof(CV2Calibration);
EEPROM.put(addr, rotateScreen);
addr = addr + sizeof(rotateScreen);
EEPROM.put(addr, extClockPPQN);
addr = addr + sizeof(extClockPPQN);
EEPROM.put(addr, reverseEnc);
addr = addr + sizeof(reverseEnc);
EEPROM.put(addr, extraChannel);
}
void loadState() { //optimisation: try to make an abstraction that can take an array (of pointers?) of settings to be loaded/saved
//check last bit in eeprom to know if the correct settings were stored
if (EEPROM.read(1023) == memCode) {
uint16_t addr = 0;
EEPROM.get(addr, bpm);
addr = addr + sizeof(bpm);
EEPROM.get(addr, bpmModulationChannel);
addr = addr + sizeof(bpmModulationChannel);
EEPROM.get(addr, bpmModulationRange);
addr = addr + sizeof(bpmModulationRange);
EEPROM.get(addr, masterClockMode);
addr = addr + sizeof(masterClockMode);
EEPROM.get(addr, channels);
addr = addr + sizeof(channels);
EEPROM.get(addr, sequences);
addr = addr + sizeof(sequences);
EEPROM.get(addr, CV1Calibration);
addr = addr + sizeof(CV1Calibration);
EEPROM.get(addr, CV2Calibration);
addr = addr + sizeof(CV2Calibration);
EEPROM.get(addr, rotateScreen);
addr = addr + sizeof(rotateScreen);
EEPROM.get(addr, extClockPPQN);
addr = addr + sizeof(extClockPPQN);
EEPROM.get(addr, reverseEnc);
addr = addr + sizeof(reverseEnc);
EEPROM.get(addr, extraChannel);
} else {
saveState(); //write default values to EEPROM
EEPROM.write(1023, memCode);
}
}
void reboot() {
wdt_enable(WDTO_15MS); //reboot after 15ms
while(true);
}
void calibrateCVs() {
CV1Calibration = analogRead(ANALOGUE_INPUT_1_PIN);
CV2Calibration = analogRead(ANALOGUE_INPUT_2_PIN);
saveState();
showDone = true;
updateScreen();
}
void checkScreenRotation() {
if (rotateScreen) {
u8g2.setDisplayRotation(U8G2_R0);
} else {
u8g2.setDisplayRotation(U8G2_R2);
}
}