Reorganization of library structure to better match Arduino spec (#20)

Note, this will also require to you "uninstall and reinstall" the Arduino library due to the library file location changes.

Reviewed-on: https://git.pinkduck.xyz/awonak/libGravity/pulls/20
This commit is contained in:
2025-07-24 15:07:15 +00:00
parent c7a3277b5f
commit 65dde4d62e
19 changed files with 22 additions and 192 deletions

88
src/analog_input.h Normal file
View File

@ -0,0 +1,88 @@
/**
* @file analog_input.h
* @author Adam Wonak (https://github.com/awonak)
* @brief Class for interacting with analog inputs.
* @version 0.1
* @date 2025-05-23
*
* @copyright MIT - (c) 2025 - Adam Wonak - adam.wonak@gmail.com
*
*/
#ifndef ANALOG_INPUT_H
#define ANALOG_INPUT_H
const int MAX_INPUT = (1 << 10) - 1; // Max 10 bit analog read resolution.
// estimated default calibration value
const int CALIBRATED_LOW = -566;
const int CALIBRATED_HIGH = 512;
class AnalogInput {
public:
AnalogInput() {}
~AnalogInput() {}
/**
* Initializes a analog input object.
*
* @param pin gpio pin for the analog input.
*/
void Init(uint8_t pin) {
pinMode(pin, INPUT);
pin_ = pin;
}
/**
* Read the value of the analog input and set instance state.
*
*/
void Process() {
old_read_ = read_;
int raw = analogRead(pin_);
read_ = map(raw, 0, MAX_INPUT, low_, high_);
read_ = constrain(read_ - offset_, -512, 512);
if (inverted_) read_ = -read_;
}
// Set calibration values.
void AdjustCalibrationLow(int amount) { low_ += amount; }
void AdjustCalibrationHigh(int amount) { high_ += amount; }
void SetOffset(float percent) { offset_ = -(percent)*512; }
void SetAttenuation(float percent) {
low_ = abs(percent) * CALIBRATED_LOW;
high_ = abs(percent) * CALIBRATED_HIGH;
inverted_ = percent < 0;
}
/**
* Get the current value of the analog input within a range of +/-512.
*
* @return read value within a range of +/-512.
*
*/
inline int16_t Read() { return read_; }
/**
* Return the analog read value as voltage.
*
* @return A float representing the voltage (-5.0 to +5.0).
*
*/
inline float Voltage() { return ((read_ / 512.0) * 5.0); }
private:
uint8_t pin_;
int16_t read_;
uint16_t old_read_;
// calibration values.
int offset_ = 0;
int low_ = CALIBRATED_LOW;
int high_ = CALIBRATED_HIGH;
bool inverted_ = false;
};
#endif

116
src/button.h Normal file
View File

@ -0,0 +1,116 @@
/**
* @file button.h
* @author Adam Wonak (https://github.com/awonak)
* @brief Wrapper class for interacting with trigger / gate inputs.
* @version 0.1
* @date 2025-04-20
*
* @copyright MIT - (c) 2025 - Adam Wonak - adam.wonak@gmail.com
*
*/
#ifndef BUTTON_H
#define BUTTON_H
#include <Arduino.h>
const uint8_t DEBOUNCE_MS = 10;
const uint16_t LONG_PRESS_DURATION_MS = 750;
class Button {
protected:
typedef void (*CallbackFunction)(void);
public:
// Enum constants for active change in button state.
enum ButtonChange {
CHANGE_UNCHANGED,
CHANGE_PRESSED,
CHANGE_RELEASED,
CHANGE_RELEASED_LONG,
};
Button() {}
Button(int pin) { Init(pin); }
~Button() {}
/**
* Initializes a CV Input object.
*
* @param pin gpio pin for the cv output.
*/
void Init(uint8_t pin) {
pinMode(pin, INPUT_PULLUP);
pin_ = pin;
old_read_ = digitalRead(pin_);
}
/**
* Provide a handler function for executing when button is pressed.
*
* @param f Callback function to attach push behavior to this button.
*/
void AttachPressHandler(CallbackFunction f) {
on_press_ = f;
}
/**
* Provide a handler function for executing when button is pressed.
*
* @param f Callback function to attach push behavior to this button.
*/
void AttachLongPressHandler(CallbackFunction f) {
on_long_press_ = f;
}
/**
* Read the state of the cv input.
*/
void Process() {
int read = digitalRead(pin_);
bool debounced = (millis() - last_press_) > DEBOUNCE_MS;
bool pressed = read == 0 && old_read_ == 1 && debounced;
bool released = read == 1 && old_read_ == 0 && debounced;
// Determine current clock input state.
change_ = CHANGE_UNCHANGED;
if (pressed) {
change_ = CHANGE_PRESSED;
} else if (released) {
// Call appropriate button press handler upon release.
if (last_press_ + LONG_PRESS_DURATION_MS > millis()) {
change_ = CHANGE_RELEASED;
if (on_press_ != NULL) on_press_();
} else {
change_ = CHANGE_RELEASED_LONG;
if (on_long_press_ != NULL) on_long_press_();
}
}
// Update variables for next loop
last_press_ = (pressed || released) ? millis() : last_press_;
old_read_ = read;
}
/**
* Get the state change for the button.
*
* @return ButtonChange
*/
inline ButtonChange Change() { return change_; }
/**
* Current cv state represented as a bool.
*
* @return true if cv signal is high, false if cv signal is low
*/
inline bool On() { return digitalRead(pin_) == 0; }
private:
uint8_t pin_;
uint8_t old_read_ = 1;
unsigned long last_press_;
ButtonChange change_ = CHANGE_UNCHANGED;
CallbackFunction on_press_;
CallbackFunction on_long_press_;
};
#endif

191
src/clock.h Normal file
View File

@ -0,0 +1,191 @@
/**
* @file clock.h
* @author Adam Wonak (https://github.com/awonak)
* @brief Wrapper Class for clock timing functions.
* @version 0.1
* @date 2025-05-04
*
* @copyright MIT - (c) 2025 - Adam Wonak - adam.wonak@gmail.com
*
*/
#ifndef CLOCK_H
#define CLOCK_H
#include <NeoHWSerial.h>
#include "peripherials.h"
#include "uClock/uClock.h"
// MIDI clock, start, stop, and continue byte definitions - based on MIDI 1.0 Standards.
#define MIDI_CLOCK 0xF8
#define MIDI_START 0xFA
#define MIDI_STOP 0xFC
#define MIDI_CONTINUE 0xFB
typedef void (*ExtCallback)(void);
static ExtCallback extUserCallback = nullptr;
static void serialEventNoop(uint8_t msg, uint8_t status) {}
class Clock {
public:
static constexpr int DEFAULT_TEMPO = 120;
enum Source {
SOURCE_INTERNAL,
SOURCE_EXTERNAL_PPQN_24,
SOURCE_EXTERNAL_PPQN_4,
SOURCE_EXTERNAL_MIDI,
SOURCE_LAST,
};
enum Pulse {
PULSE_NONE,
PULSE_PPQN_1,
PULSE_PPQN_4,
PULSE_PPQN_24,
PULSE_LAST,
};
void Init() {
NeoSerial.begin(31250);
// Initialize the clock library
uClock.init();
uClock.setClockMode(uClock.INTERNAL_CLOCK);
uClock.setOutputPPQN(uClock.PPQN_96);
uClock.setTempo(DEFAULT_TEMPO);
// MIDI events.
uClock.setOnClockStart(sendMIDIStart);
uClock.setOnClockStop(sendMIDIStop);
uClock.setOnSync24(sendMIDIClock);
uClock.start();
}
// Handle external clock tick and call user callback when receiving clock trigger (PPQN_4, PPQN_24, or MIDI).
void AttachExtHandler(void (*callback)()) {
extUserCallback = callback;
attachInterrupt(digitalPinToInterrupt(EXT_PIN), callback, RISING);
}
// Internal PPQN96 callback for all clock timer operations.
void AttachIntHandler(void (*callback)(uint32_t)) {
uClock.setOnOutputPPQN(callback);
}
// Set the source of the clock mode.
void SetSource(Source source) {
bool was_playing = !IsPaused();
uClock.stop();
// If we are changing the source from MIDI, disable the serial interrupt handler.
if (source_ == SOURCE_EXTERNAL_MIDI) {
NeoSerial.attachInterrupt(serialEventNoop);
}
source_ = source;
switch (source) {
case SOURCE_INTERNAL:
uClock.setClockMode(uClock.INTERNAL_CLOCK);
break;
case SOURCE_EXTERNAL_PPQN_24:
uClock.setClockMode(uClock.EXTERNAL_CLOCK);
uClock.setInputPPQN(uClock.PPQN_24);
break;
case SOURCE_EXTERNAL_PPQN_4:
uClock.setClockMode(uClock.EXTERNAL_CLOCK);
uClock.setInputPPQN(uClock.PPQN_4);
break;
case SOURCE_EXTERNAL_MIDI:
uClock.setClockMode(uClock.EXTERNAL_CLOCK);
uClock.setInputPPQN(uClock.PPQN_24);
NeoSerial.attachInterrupt(onSerialEvent);
break;
}
if (was_playing) {
uClock.start();
}
}
// Return true if the current selected source is externl (PPQN_4, PPQN_24, or MIDI).
bool ExternalSource() {
return uClock.getClockMode() == uClock.EXTERNAL_CLOCK;
}
// Return true if the current selected source is the internal master clock.
bool InternalSource() {
return uClock.getClockMode() == uClock.INTERNAL_CLOCK;
}
// Returns the current BPM tempo.
int Tempo() {
return uClock.getTempo();
}
// Set the clock tempo to a int between 1 and 400.
void SetTempo(int tempo) {
return uClock.setTempo(tempo);
}
// Record an external clock tick received to process external/internal syncronization.
void Tick() {
uClock.clockMe();
}
// Start the internal clock.
void Start() {
uClock.start();
}
// Stop internal clock clock.
void Stop() {
uClock.stop();
}
// Reset all clock counters to 0.
void Reset() {
uClock.resetCounters();
}
// Returns true if the clock is not running.
bool IsPaused() {
return uClock.clock_state == uClock.PAUSED;
}
private:
Source source_ = SOURCE_INTERNAL;
static void onSerialEvent(uint8_t msg, uint8_t status) {
// Note: uClock start and stop will echo to MIDI.
switch (msg) {
case MIDI_CLOCK:
if (extUserCallback) {
extUserCallback();
}
break;
case MIDI_STOP:
uClock.stop();
sendMIDIStop();
break;
case MIDI_START:
case MIDI_CONTINUE:
uClock.start();
sendMIDIStart();
break;
}
}
static void sendMIDIStart() {
NeoSerial.write(MIDI_START);
}
static void sendMIDIStop() {
NeoSerial.write(MIDI_STOP);
}
static void sendMIDIClock(uint32_t tick) {
NeoSerial.write(MIDI_CLOCK);
}
};
#endif

94
src/digital_output.h Normal file
View File

@ -0,0 +1,94 @@
/**
* @file digital_output.h
* @author Adam Wonak (https://github.com/awonak)
* @brief Class for interacting with trigger / gate outputs.
* @version 0.1
* @date 2025-04-17
*
* @copyright MIT - (c) 2025 - Adam Wonak - adam.wonak@gmail.com
*
*/
#ifndef DIGITAL_OUTPUT_H
#define DIGITAL_OUTPUT_H
#include <Arduino.h>
const byte DEFAULT_TRIGGER_DURATION_MS = 5;
class DigitalOutput {
public:
/**
* Initializes an CV Output paired object.
*
* @param cv_pin gpio pin for the cv output
*/
void Init(uint8_t cv_pin) {
pinMode(cv_pin, OUTPUT); // Gate/Trigger Output
cv_pin_ = cv_pin;
trigger_duration_ = DEFAULT_TRIGGER_DURATION_MS;
}
/**
* Set the trigger duration in miliseconds.
*
* @param duration_ms trigger duration in miliseconds
*/
void SetTriggerDuration(uint8_t duration_ms) {
trigger_duration_ = duration_ms;
}
/**
* Turn the CV and LED on or off according to the input state.
*
* @param state Arduino digital HIGH or LOW values.
*/
inline void Update(uint8_t state) {
if (state == HIGH) High(); // Rising
if (state == LOW) Low(); // Falling
}
// Sets the cv output HIGH to about 5v.
inline void High() { update(HIGH); }
// Sets the cv output LOW to 0v.
inline void Low() { update(LOW); }
/**
* Begin a Trigger period for this output.
*/
inline void Trigger() {
update(HIGH);
last_triggered_ = millis();
}
/**
* Return a bool representing the on/off state of the output.
*/
inline void Process() {
// If trigger is HIGH and the trigger duration time has elapsed, set the output low.
if (on_ && (millis() - last_triggered_) >= trigger_duration_) {
update(LOW);
}
}
/**
* Return a bool representing the on/off state of the output.
*
* @return true if current cv state is high, false if current cv state is low
*/
inline bool On() { return on_; }
private:
unsigned long last_triggered_;
uint8_t trigger_duration_;
uint8_t cv_pin_;
uint8_t led_pin_;
bool on_;
void update(uint8_t state) {
digitalWrite(cv_pin_, state);
on_ = state == HIGH;
}
};
#endif

117
src/encoder.h Normal file
View File

@ -0,0 +1,117 @@
/**
* @file encoder_dir.h
* @author Adam Wonak (https://github.com/awonak)
* @brief Class for interacting with encoders.
* @version 0.1
* @date 2025-04-19
*
* @copyright MIT - (c) 2025 - Adam Wonak - adam.wonak@gmail.com
*
*/
#ifndef ENCODER_DIR_H
#define ENCODER_DIR_H
#include <RotaryEncoder.h>
#include "button.h"
#include "peripherials.h"
class Encoder {
protected:
typedef void (*CallbackFunction)(void);
typedef void (*RotateCallbackFunction)(int val);
CallbackFunction on_press;
RotateCallbackFunction on_press_rotate;
RotateCallbackFunction on_rotate;
int change;
public:
Encoder() : encoder_(ENCODER_PIN1, ENCODER_PIN2, RotaryEncoder::LatchMode::FOUR3),
button_(ENCODER_SW_PIN) {
_instance = this;
}
~Encoder() {}
// Set to true if the encoder read direction should be reversed.
void SetReverseDirection(bool reversed) {
reversed_ = reversed;
}
void AttachPressHandler(CallbackFunction f) {
on_press = f;
}
void AttachRotateHandler(RotateCallbackFunction f) {
on_rotate = f;
}
void AttachPressRotateHandler(RotateCallbackFunction f) {
on_press_rotate = f;
}
void Process() {
// Get encoder position change amount.
int encoder_rotated = _rotate_change() != 0;
bool button_pressed = button_.On();
button_.Process();
// Handle encoder position change and button press.
if (button_pressed && encoder_rotated) {
rotated_while_held_ = true;
if (on_press_rotate != NULL) on_press_rotate(change);
} else if (!button_pressed && encoder_rotated) {
if (on_rotate != NULL) on_rotate(change);
} else if (button_.Change() == Button::CHANGE_RELEASED && !rotated_while_held_) {
if (on_press != NULL) on_press();
}
// Reset rotate while held state.
if (button_.Change() == Button::CHANGE_RELEASED && rotated_while_held_) {
rotated_while_held_ = false;
}
}
static void isr() {
// If the instance has been created, call its tick() method.
if (_instance) {
_instance->encoder_.tick();
}
}
private:
static Encoder* _instance;
int previous_pos_;
bool rotated_while_held_;
bool reversed_ = false;
RotaryEncoder encoder_;
Button button_;
// Return the number of ticks change since last polled.
int _rotate_change() {
int position = encoder_.getPosition();
unsigned long ms = encoder_.getMillisBetweenRotations();
// Validation (TODO: add debounce check).
if (previous_pos_ == position) {
return 0;
}
// Update state variables.
change = position - previous_pos_;
previous_pos_ = position;
// Encoder rotate acceleration.
if (ms < 16) {
change *= 3;
} else if (ms < 32) {
change *= 2;
}
if (reversed_) {
change = -(change);
}
return change;
}
};
#endif

87
src/libGravity.cpp Normal file
View File

@ -0,0 +1,87 @@
/**
* @file libGravity.cpp
* @author Adam Wonak (https://github.com/awonak)
* @brief Library for building custom scripts for the Sitka Instruments Gravity module.
* @version 0.1
* @date 2025-04-19
*
* @copyright MIT - (c) 2025 - Adam Wonak - adam.wonak@gmail.com
*
*/
#include "libGravity.h"
// Initialize the static pointer for the EncoderDir class to null. We want to
// have a static pointer to decouple the ISR from the global gravity object.
Encoder* Encoder::_instance = nullptr;
void Gravity::Init() {
initClock();
initInputs();
initOutputs();
initDisplay();
}
void Gravity::initClock() {
clock.Init();
}
void Gravity::initInputs() {
shift_button.Init(SHIFT_BTN_PIN);
play_button.Init(PLAY_BTN_PIN);
cv1.Init(CV1_PIN);
cv2.Init(CV2_PIN);
// Pin Change Interrupts for Encoder.
// Thanks to https://dronebotworkshop.com/interrupts/
// Enable both PCIE2 Bit3 (Port D), and PCIE1 Bit2 (Port C).
PCICR |= B00000110;
// Select PCINT23 Bit4 = 1 (Pin D4)
PCMSK2 |= B00010000;
// Select PCINT11 Bit3 (Pin D17/A3)
PCMSK1 |= B00001000;
}
void Gravity::initOutputs() {
// Initialize each of the outputs with it's GPIO pins and probability.
outputs[0].Init(OUT_CH1);
outputs[1].Init(OUT_CH2);
outputs[2].Init(OUT_CH3);
outputs[3].Init(OUT_CH4);
outputs[4].Init(OUT_CH5);
outputs[5].Init(OUT_CH6);
// Expansion Pulse Output
pulse.Init(PULSE_OUT_PIN);
}
void Gravity::initDisplay() {
// OLED Display configuration.
display.begin();
}
void Gravity::Process() {
// Read peripherials for changes.
shift_button.Process();
play_button.Process();
encoder.Process();
cv1.Process();
cv2.Process();
// Update Output states.
for (int i; i < OUTPUT_COUNT; i++) {
outputs[i].Process();
}
}
// Pin Change Interrupt on Port D (D4).
ISR(PCINT2_vect) {
Encoder::isr();
};
// Pin Change Interrupt on Port C (D17/A3).
ISR(PCINT1_vect) {
Encoder::isr();
};
// Global instance
Gravity gravity;

62
src/libGravity.h Normal file
View File

@ -0,0 +1,62 @@
/**
* @file libGravity.h
* @author Adam Wonak (https://github.com/awonak)
* @brief Library for building custom scripts for the Sitka Instruments Gravity module.
* @version 0.1
* @date 2025-04-19
*
* @copyright MIT - (c) 2025 - Adam Wonak - adam.wonak@gmail.com
*
*/
#ifndef GRAVITY_H
#define GRAVITY_H
#include <Arduino.h>
#include <U8g2lib.h>
#include "analog_input.h"
#include "button.h"
#include "clock.h"
#include "digital_output.h"
#include "encoder.h"
#include "peripherials.h"
// Hardware abstraction wrapper for the Gravity module.
class Gravity {
public:
static const uint8_t OUTPUT_COUNT = 6;
// Constructor
Gravity()
: display(U8G2_R2, SCL, SDA, U8X8_PIN_NONE) {}
// Deconstructor
~Gravity() {}
// Initializes the Arduino, and Gravity hardware.
void Init();
// Polling check for state change of inputs and outputs.
void Process();
U8G2_SSD1306_128X64_NONAME_1_HW_I2C display; // OLED display object.
Clock clock; // Clock source wrapper.
DigitalOutput outputs[OUTPUT_COUNT]; // An array containing each Output object.
DigitalOutput pulse; // MIDI Expander module pulse output.
Encoder encoder; // Rotary encoder with button instance
Button shift_button;
Button play_button;
AnalogInput cv1;
AnalogInput cv2;
private:
void initClock();
void initDisplay();
void initInputs();
void initOutputs();
};
extern Gravity gravity;
#endif

43
src/peripherials.h Normal file
View File

@ -0,0 +1,43 @@
/**
* @file peripherials.h
* @author Adam Wonak (https://github.com/awonak)
* @brief Arduino pin definitions for the Sitka Instruments Gravity module.
* @version 0.1
* @date 2025-04-19
*
* @copyright MIT - (c) 2025 - Adam Wonak - adam.wonak@gmail.com
*
*/
#ifndef PERIPHERIALS_H
#define PERIPHERIALS_H
// OLED Display config
#define OLED_ADDRESS 0x3C
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// Peripheral input pins
#define ENCODER_PIN1 17 // A3
#define ENCODER_PIN2 4
#define ENCODER_SW_PIN 14 // A0
// Clock and CV Inputs
#define EXT_PIN 2
#define CV1_PIN A7
#define CV2_PIN A6
#define PULSE_OUT_PIN 3
// Button pins
#define SHIFT_BTN_PIN 12
#define PLAY_BTN_PIN 5
// Output Pins
#define OUT_CH1 7
#define OUT_CH2 8
#define OUT_CH3 10
#define OUT_CH4 6
#define OUT_CH5 9
#define OUT_CH6 11
#endif

View File

@ -0,0 +1,98 @@
/*!
* @file avr.h
* Project BPM clock generator for Arduino
* @brief A Library to implement BPM clock tick calls using hardware interruption. Supported and tested on AVR boards(ATmega168/328, ATmega16u4/32u4 and ATmega2560) and ARM boards(RPI2040, Teensy, Seedstudio XIAO M0 and ESP32)
* @version 2.2.1
* @author Romulo Silva
* @date 10/06/2017
* @license MIT - (c) 2024 - Romulo Silva - contact@midilab.co
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <Arduino.h>
#define ATOMIC(X) noInterrupts(); X; interrupts();
// want a different avr clock support?
// TODO: we should do this using macro guards for avrs different clocks freqeuncy setup at compile time
#define AVR_CLOCK_FREQ 16000000
// forward declaration of uClockHandler
void uClockHandler();
// AVR ISR Entrypoint
ISR(TIMER1_COMPA_vect)
{
uClockHandler();
}
void initTimer(uint32_t init_clock)
{
ATOMIC(
// 16bits Timer1 init
// begin at 120bpm (48.0007680122882 Hz)
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 48.0007680122882 Hz increments
OCR1A = 41665; // = 16000000 / (8 * 48.0007680122882) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS12, CS11 and CS10 bits for 8 prescaler
TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
)
}
void setTimer(uint32_t us_interval)
{
float tick_hertz_interval = 1/((float)us_interval/1000000);
uint32_t ocr;
uint8_t tccr = 0;
// 16bits avr timer setup
if ((ocr = AVR_CLOCK_FREQ / ( tick_hertz_interval * 1 )) < 65535) {
// Set CS12, CS11 and CS10 bits for 1 prescaler
tccr |= (0 << CS12) | (0 << CS11) | (1 << CS10);
} else if ((ocr = AVR_CLOCK_FREQ / ( tick_hertz_interval * 8 )) < 65535) {
// Set CS12, CS11 and CS10 bits for 8 prescaler
tccr |= (0 << CS12) | (1 << CS11) | (0 << CS10);
} else if ((ocr = AVR_CLOCK_FREQ / ( tick_hertz_interval * 64 )) < 65535) {
// Set CS12, CS11 and CS10 bits for 64 prescaler
tccr |= (0 << CS12) | (1 << CS11) | (1 << CS10);
} else if ((ocr = AVR_CLOCK_FREQ / ( tick_hertz_interval * 256 )) < 65535) {
// Set CS12, CS11 and CS10 bits for 256 prescaler
tccr |= (1 << CS12) | (0 << CS11) | (0 << CS10);
} else if ((ocr = AVR_CLOCK_FREQ / ( tick_hertz_interval * 1024 )) < 65535) {
// Set CS12, CS11 and CS10 bits for 1024 prescaler
tccr |= (1 << CS12) | (0 << CS11) | (1 << CS10);
} else {
// tempo not achiavable
return;
}
ATOMIC(
TCCR1B = 0;
OCR1A = ocr-1;
TCCR1B |= (1 << WGM12);
TCCR1B |= tccr;
)
}

415
src/uClock/uClock.cpp Executable file
View File

@ -0,0 +1,415 @@
/*!
* @file uClock.cpp
* Project BPM clock generator for Arduino
* @brief A Library to implement BPM clock tick calls using hardware interruption. Supported and tested on AVR boards(ATmega168/328, ATmega16u4/32u4 and ATmega2560) and ARM boards(RPI2040, Teensy, Seedstudio XIAO M0 and ESP32)
* @version 2.2.1
* @author Romulo Silva
* @date 10/06/2017
* @license MIT - (c) 2024 - Romulo Silva - contact@midilab.co
*
* 2025-06-30 - https://github.com/awonak/uClock/tree/picoClock
* Modified by awonak to remove all unused sync callback
* methods and associated variables to dramatically reduce
* memory usage.
* See: https://github.com/midilab/uClock/issues/58
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "uClock.h"
#include "platforms/avr.h"
//
// Platform specific timer setup/control
//
// initTimer(uint32_t us_interval) and setTimer(uint32_t us_interval)
// are called from architecture specific module included at the
// header of this file
void uclockInitTimer()
{
// begin at 120bpm
initTimer(uClock.bpmToMicroSeconds(120.00));
}
void setTimerTempo(float bpm)
{
setTimer(uClock.bpmToMicroSeconds(bpm));
}
namespace umodular { namespace clock {
static inline uint32_t phase_mult(uint32_t val)
{
return (val * PHASE_FACTOR) >> 8;
}
static inline uint32_t clock_diff(uint32_t old_clock, uint32_t new_clock)
{
if (new_clock >= old_clock) {
return new_clock - old_clock;
} else {
return new_clock + (4294967295 - old_clock);
}
}
uClockClass::uClockClass()
{
tempo = 120;
start_timer = 0;
last_interval = 0;
sync_interval = 0;
clock_state = PAUSED;
clock_mode = INTERNAL_CLOCK;
resetCounters();
onOutputPPQNCallback = nullptr;
onSync24Callback = nullptr;
onClockStartCallback = nullptr;
onClockStopCallback = nullptr;
// initialize reference data
calculateReferencedata();
}
void uClockClass::init()
{
if (ext_interval_buffer == nullptr)
setExtIntervalBuffer(1);
uclockInitTimer();
// first interval calculus
setTempo(tempo);
}
uint32_t uClockClass::bpmToMicroSeconds(float bpm)
{
return (60000000.0f / (float)output_ppqn / bpm);
}
void uClockClass::calculateReferencedata()
{
mod_clock_ref = output_ppqn / input_ppqn;
mod_sync24_ref = output_ppqn / PPQN_24;
}
void uClockClass::setOutputPPQN(PPQNResolution resolution)
{
// dont allow PPQN lower than PPQN_4 for output clock (to avoid problems with mod_step_ref)
if (resolution < PPQN_4)
return;
ATOMIC(
output_ppqn = resolution;
calculateReferencedata();
)
}
void uClockClass::setInputPPQN(PPQNResolution resolution)
{
ATOMIC(
input_ppqn = resolution;
calculateReferencedata();
)
}
void uClockClass::start()
{
resetCounters();
start_timer = millis();
if (onClockStartCallback) {
onClockStartCallback();
}
if (clock_mode == INTERNAL_CLOCK) {
clock_state = STARTED;
} else {
clock_state = STARTING;
}
}
void uClockClass::stop()
{
clock_state = PAUSED;
start_timer = 0;
resetCounters();
if (onClockStopCallback) {
onClockStopCallback();
}
}
void uClockClass::pause()
{
if (clock_mode == INTERNAL_CLOCK) {
if (clock_state == PAUSED) {
start();
} else {
stop();
}
}
}
void uClockClass::setTempo(float bpm)
{
if (clock_mode == EXTERNAL_CLOCK) {
return;
}
if (bpm < MIN_BPM || bpm > MAX_BPM) {
return;
}
ATOMIC(
tempo = bpm
)
setTimerTempo(bpm);
}
float uClockClass::getTempo()
{
if (clock_mode == EXTERNAL_CLOCK) {
uint32_t acc = 0;
// wait the buffer to get full
if (ext_interval_buffer[ext_interval_buffer_size-1] == 0) {
return tempo;
}
for (uint8_t i=0; i < ext_interval_buffer_size; i++) {
acc += ext_interval_buffer[i];
}
if (acc != 0) {
return constrainBpm(freqToBpm(acc / ext_interval_buffer_size));
}
}
return tempo;
}
// for software timer implementation(fallback for no board support)
void uClockClass::run() {}
float inline uClockClass::freqToBpm(uint32_t freq)
{
return 60000000.0f / (float)(freq * input_ppqn);
}
float inline uClockClass::constrainBpm(float bpm)
{
return (bpm < MIN_BPM) ? MIN_BPM : ( bpm > MAX_BPM ? MAX_BPM : bpm );
}
void uClockClass::setClockMode(ClockMode tempo_mode)
{
clock_mode = tempo_mode;
}
uClockClass::ClockMode uClockClass::getClockMode()
{
return clock_mode;
}
void uClockClass::clockMe()
{
if (clock_mode == EXTERNAL_CLOCK) {
ATOMIC(
handleExternalClock()
)
}
}
void uClockClass::setExtIntervalBuffer(uint8_t buffer_size)
{
if (ext_interval_buffer != nullptr)
return;
// alloc once and forever policy
ext_interval_buffer_size = buffer_size;
ext_interval_buffer = (uint32_t*) malloc( sizeof(uint32_t) * ext_interval_buffer_size );
}
void uClockClass::resetCounters()
{
tick = 0;
int_clock_tick = 0;
mod_clock_counter = 0;
mod_sync24_counter = 0;
sync24_tick = 0;
ext_clock_tick = 0;
ext_clock_us = 0;
ext_interval_idx = 0;
for (uint8_t i=0; i < ext_interval_buffer_size; i++) {
ext_interval_buffer[i] = 0;
}
}
void uClockClass::handleExternalClock()
{
switch (clock_state) {
case PAUSED:
break;
case STARTING:
clock_state = STARTED;
ext_clock_us = micros();
break;
case STARTED:
uint32_t now_clock_us = micros();
last_interval = clock_diff(ext_clock_us, now_clock_us);
ext_clock_us = now_clock_us;
// external clock tick me!
ext_clock_tick++;
// accumulate interval incomming ticks data for getTempo() smooth reads on slave clock_mode
if(++ext_interval_idx >= ext_interval_buffer_size) {
ext_interval_idx = 0;
}
ext_interval_buffer[ext_interval_idx] = last_interval;
if (ext_clock_tick == 1) {
ext_interval = last_interval;
} else {
ext_interval = (((uint32_t)ext_interval * (uint32_t)PLL_X) + (uint32_t)(256 - PLL_X) * (uint32_t)last_interval) >> 8;
}
break;
}
}
void uClockClass::handleTimerInt()
{
// track main input clock counter
if (mod_clock_counter == mod_clock_ref)
mod_clock_counter = 0;
// process sync signals first please...
if (mod_clock_counter == 0) {
if (clock_mode == EXTERNAL_CLOCK) {
// sync tick position with external tick clock
if ((int_clock_tick < ext_clock_tick) || (int_clock_tick > (ext_clock_tick + 1))) {
int_clock_tick = ext_clock_tick;
tick = int_clock_tick * mod_clock_ref;
mod_clock_counter = tick % mod_clock_ref;
}
uint32_t counter = ext_interval;
uint32_t now_clock_us = micros();
sync_interval = clock_diff(ext_clock_us, now_clock_us);
if (int_clock_tick <= ext_clock_tick) {
counter -= phase_mult(sync_interval);
} else {
if (counter > sync_interval) {
counter += phase_mult(counter - sync_interval);
}
}
// update internal clock timer frequency
float bpm = constrainBpm(freqToBpm(counter));
if (bpm != tempo) {
tempo = bpm;
setTimerTempo(bpm);
}
}
// internal clock tick me!
++int_clock_tick;
}
++mod_clock_counter;
// Sync24 callback
if (onSync24Callback) {
if (mod_sync24_counter == mod_sync24_ref)
mod_sync24_counter = 0;
if (mod_sync24_counter == 0) {
onSync24Callback(sync24_tick);
++sync24_tick;
}
++mod_sync24_counter;
}
// main PPQNCallback
if (onOutputPPQNCallback) {
onOutputPPQNCallback(tick);
++tick;
}
}
// elapsed time support
uint8_t uClockClass::getNumberOfSeconds(uint32_t time)
{
if ( time == 0 ) {
return time;
}
return ((_millis - time) / 1000) % SECS_PER_MIN;
}
uint8_t uClockClass::getNumberOfMinutes(uint32_t time)
{
if ( time == 0 ) {
return time;
}
return (((_millis - time) / 1000) / SECS_PER_MIN) % SECS_PER_MIN;
}
uint8_t uClockClass::getNumberOfHours(uint32_t time)
{
if ( time == 0 ) {
return time;
}
return (((_millis - time) / 1000) % SECS_PER_DAY) / SECS_PER_HOUR;
}
uint8_t uClockClass::getNumberOfDays(uint32_t time)
{
if ( time == 0 ) {
return time;
}
return ((_millis - time) / 1000) / SECS_PER_DAY;
}
uint32_t uClockClass::getNowTimer()
{
return _millis;
}
uint32_t uClockClass::getPlayTime()
{
return start_timer;
}
} } // end namespace umodular::clock
umodular::clock::uClockClass uClock;
volatile uint32_t _millis = 0;
//
// TIMER HANDLER
//
void uClockHandler()
{
// global timer counter
_millis = millis();
if (uClock.clock_state == uClock.STARTED) {
uClock.handleTimerInt();
}
}

186
src/uClock/uClock.h Executable file
View File

@ -0,0 +1,186 @@
/*!
* @file uClock.h
* Project BPM clock generator for Arduino
* @brief A Library to implement BPM clock tick calls using hardware interruption. Supported and tested on AVR boards(ATmega168/328, ATmega16u4/32u4 and ATmega2560) and ARM boards(RPI2040, Teensy, Seedstudio XIAO M0 and ESP32)
* @version 2.2.1
* @author Romulo Silva
* @date 10/06/2017
* @license MIT - (c) 2024 - Romulo Silva - contact@midilab.co
*
* 2025-06-30 - https://github.com/awonak/uClock/tree/picoClock
* Modified by awonak to remove all unused sync callback
* methods and associated variables to dramatically reduce
* memory usage.
* See: https://github.com/midilab/uClock/issues/58
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef __U_CLOCK_H__
#define __U_CLOCK_H__
#include <Arduino.h>
#include <inttypes.h>
namespace umodular { namespace clock {
#define MIN_BPM 1
#define MAX_BPM 400
#define PHASE_FACTOR 16
#define PLL_X 220
#define SECS_PER_MIN (60UL)
#define SECS_PER_HOUR (3600UL)
#define SECS_PER_DAY (SECS_PER_HOUR * 24L)
class uClockClass {
public:
enum ClockMode {
INTERNAL_CLOCK = 0,
EXTERNAL_CLOCK
};
enum ClockState {
PAUSED = 0,
STARTING,
STARTED
};
enum PPQNResolution {
PPQN_1 = 1,
PPQN_2 = 2,
PPQN_4 = 4,
PPQN_8 = 8,
PPQN_12 = 12,
PPQN_24 = 24,
PPQN_48 = 48,
PPQN_96 = 96,
PPQN_384 = 384,
PPQN_480 = 480,
PPQN_960 = 960
};
ClockState clock_state;
uClockClass();
void setOnOutputPPQN(void (*callback)(uint32_t tick)) {
onOutputPPQNCallback = callback;
}
void setOnSync24(void (*callback)(uint32_t tick)) {
onSync24Callback = callback;
}
void setOnClockStart(void (*callback)()) {
onClockStartCallback = callback;
}
void setOnClockStop(void (*callback)()) {
onClockStopCallback = callback;
}
void init();
void setOutputPPQN(PPQNResolution resolution);
void setInputPPQN(PPQNResolution resolution);
void handleTimerInt();
void handleExternalClock();
void resetCounters();
// external class control
void start();
void stop();
void pause();
void setTempo(float bpm);
float getTempo();
// for software timer implementation(fallback for no board support)
void run();
// external timming control
void setClockMode(ClockMode tempo_mode);
ClockMode getClockMode();
void clockMe();
// for smooth slave tempo calculate display you should raise the
// buffer_size of ext_interval_buffer in between 64 to 128. 254 max size.
// note: this doesn't impact on sync time, only display time getTempo()
// if you dont want to use it, it is default set it to 1 for memory save
void setExtIntervalBuffer(uint8_t buffer_size);
// elapsed time support
uint8_t getNumberOfSeconds(uint32_t time);
uint8_t getNumberOfMinutes(uint32_t time);
uint8_t getNumberOfHours(uint32_t time);
uint8_t getNumberOfDays(uint32_t time);
uint32_t getNowTimer();
uint32_t getPlayTime();
uint32_t bpmToMicroSeconds(float bpm);
private:
float inline freqToBpm(uint32_t freq);
float inline constrainBpm(float bpm);
void calculateReferencedata();
void (*onOutputPPQNCallback)(uint32_t tick);
void (*onSync24Callback)(uint32_t tick);
void (*onClockStartCallback)();
void (*onClockStopCallback)();
// clock input/output control
PPQNResolution output_ppqn = PPQN_96;
PPQNResolution input_ppqn = PPQN_24;
// output and internal counters, ticks and references
uint32_t tick;
uint32_t int_clock_tick;
uint8_t mod_clock_counter;
uint16_t mod_clock_ref;
uint8_t mod_sync24_counter;
uint16_t mod_sync24_ref;
uint32_t sync24_tick;
// external clock control
volatile uint32_t ext_clock_us;
volatile uint32_t ext_clock_tick;
volatile uint32_t ext_interval;
uint32_t last_interval;
uint32_t sync_interval;
float tempo;
uint32_t start_timer;
ClockMode clock_mode;
volatile uint32_t * ext_interval_buffer = nullptr;
uint8_t ext_interval_buffer_size;
uint16_t ext_interval_idx;
};
} } // end namespace umodular::clock
extern umodular::clock::uClockClass uClock;
extern "C" {
extern volatile uint32_t _millis;
}
#endif /* __U_CLOCK_H__ */