Skip to content

Instantly share code, notes, and snippets.

@kindohm
Created December 19, 2023 02:31
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 kindohm/415c991b2517b7bc1c085c20942676f3 to your computer and use it in GitHub Desktop.
Save kindohm/415c991b2517b7bc1c085c20942676f3 to your computer and use it in GitHub Desktop.
arduino micro midi clock with pot
#define MIDI_CLOCK 0xF8
#define MIDI_CLOCK_PIN 1
// Define the MIDI baud rate
#define MIDI_BAUD_RATE 31250
unsigned long previousMicros = 0;
unsigned long intervalBetweenTempoChanges = 2000; // 2 seconds in microseconds
unsigned long lastTempoChangeTime = 0;
unsigned long MICROSECONDS_PER_CLOCK = 30000;
unsigned long mils = 0;
const int potentiometerPin = A0;
int previousPotValue = 0;
void setup() {
pinMode(MIDI_CLOCK_PIN, OUTPUT);
Serial.begin(MIDI_BAUD_RATE);
Serial1.begin(MIDI_BAUD_RATE);
}
void loop() {
// Get the current time in microseconds
unsigned long currentMicros = micros();
// Check if the specified interval has passed
if (currentMicros - previousMicros >= MICROSECONDS_PER_CLOCK) {
int potValue = analogRead(potentiometerPin);
if (potValue != previousPotValue) {
changeTempo(potValue);
previousPotValue = potValue;
}
// Send MIDI clock message at the specified interval
sendMidiClock();
previousMicros = currentMicros;
}
}
void changeTempo(int val) {
// Update the previous potentiometer value
MICROSECONDS_PER_CLOCK = scaleValue(val, 0, 1023, 45000, 6000);
Serial.print("Potentiometer Value: ");
Serial.println(val);
Serial.println(MICROSECONDS_PER_CLOCK);
}
unsigned long scaleValue(unsigned long inputValue, unsigned long fromLow, unsigned long fromHigh, unsigned long toLow, long unsigned toHigh) {
// Ensure the input value is within the input range
inputValue = constrain(inputValue, fromLow, fromHigh);
Serial.println("constrainted:");
Serial.println(inputValue);
// Map the input value from the input range to the output range
long scaledValue = map(inputValue, fromLow, fromHigh, toLow, toHigh);
return scaledValue;
}
void sendMidiClock() {
// Send the MIDI clock message on the default Serial TX pin (pin 1)
Serial1.write(MIDI_CLOCK);
}
void randomizeTempo() {
MICROSECONDS_PER_CLOCK = random(7000, 50000); // Adjust the range as needed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment