Skip to content

Instantly share code, notes, and snippets.

@tecteun
Created February 1, 2021 23:07
Show Gist options
  • Save tecteun/a99becfc98d405aa70267cb4de99aed9 to your computer and use it in GitHub Desktop.
Save tecteun/a99becfc98d405aa70267cb4de99aed9 to your computer and use it in GitHub Desktop.
DIY Arduino Eurorack clock divider / multiplier using interrupt
// Timer library, https://github.com/dniklaus/wiring-timer,
// add it by using the Arduino IDE Library Manager (search for wiring-timer)
#include <Timer.h>
// LcdKeypad, https://github.com/dniklaus/arduino-display-lcdkeypad,
// add it by using the Arduino IDE Library Manager (search for arduino-display-lcdkeypad)
#include <LcdKeypad.h>
LcdKeypad* myLcdKeypad = 0;
const byte interruptPin = 2;
unsigned long time = NULL;
unsigned long time_1x = NULL;
unsigned long time_2x = NULL;
unsigned long time_diff = NULL;
unsigned long tickcount = 0;
unsigned long bpm = 0;
void setup() {
// Timer0 is already used for millis() - we'll just interrupt somewhere
// in the middle and call the "Compare A" function below
OCR0A = 0xAF;
TIMSK0 |= _BV(OCIE0A);
Serial.begin(115200);
pinMode(interruptPin, INPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(A0, INPUT);
attachInterrupt(digitalPinToInterrupt(interruptPin), tick, FALLING);
myLcdKeypad = new LcdKeypad(); // instantiate an object of the LcdKeypad class, using default parameters
myLcdKeypad->setCursor(0, 0); // position the cursor at beginning of the first line
myLcdKeypad->setBacklight(1);
}
void tick() {
tickcount++;
unsigned long currentTime = millis();
if(time != NULL)
{
time_diff = currentTime - time;
}
time_1x = time = currentTime;
time_2x = time_1x + floor(time_diff / 2);
}
// Interrupt is called once a millisecond,
SIGNAL(TIMER0_COMPA_vect)
{
digitalWrite(12, LOW);
digitalWrite(13, LOW);
unsigned long currentMillis = millis();
if(time_1x != NULL)
{
if(tickcount % 2 == 0){
digitalWrite(13, HIGH);
}
bpm = floor(15000 / time_diff);
//Serial.print("clone ");
//Serial.print(30000 / time_diff);
// Serial.print("bpm ");
// Serial.println(time_1x);
time_1x = NULL;
digitalWrite(12, HIGH);
}
if(time_2x != NULL && currentMillis >= time_2x) {
//Serial.print("extra ");
//Serial.print(30000 / time_diff);
// Serial.print("bpm ");
// Serial.println(currentMillis);
time_2x = NULL;
digitalWrite(12, HIGH);
}
}
void loop() {
myLcdKeypad->setCursor(0, 0); // position the cursor at beginning of the first line
myLcdKeypad->print("BPM:"); // print a Value label on the first line of the display
myLcdKeypad->setCursor(5, 0);
myLcdKeypad->print(bpm); // print a Value label on the first line of the display
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment