/********* Pleasedontcode.com **********
Pleasedontcode thanks you for automatic code generation! Enjoy your code!
- Terms and Conditions:
You have a non-exclusive, revocable, worldwide, royalty-free license
for personal and commercial use. Attribution is optional; modifications
are allowed, but you're responsible for code maintenance. We're not
liable for any loss or damage. For full terms,
please visit pleasedontcode.com/termsandconditions.
- Project: "Random MIDI Button"
- Source Code compiled for: Arduino Nano
- Source Code created on: 2024-01-02 20:40:18
********* Pleasedontcode.com **********/
/****** SYSTEM REQUIREMENTS *****/
/****** SYSTEM REQUIREMENT 1 *****/
/* Use the midi library to create a simple midi */
/* controller that plays a random note on the press */
/* if the button. When the button. Is pressed again, */
/* send a note off message for the already played */
/* note and play another random note. Add a timeout */
/* after 5s */
/****** END SYSTEM REQUIREMENTS *****/
/****** DEFINITION OF LIBRARIES *****/
#include
#include
#include
/****** FUNCTION PROTOTYPES *****/
void setup();
void loop();
void handleButtonPress();
/***** DEFINITION OF DIGITAL INPUT PINS *****/
const uint8_t button1_PushButton_PIN_D2 = 2;
/****** DEFINITION OF LIBRARY CLASS INSTANCES*****/
EasyButton button1(button1_PushButton_PIN_D2);
MIDI_CREATE_DEFAULT_INSTANCE();
// MIDI note range
const int MIDI_NOTE_MIN = 48;
const int MIDI_NOTE_MAX = 72;
// Timeout duration
const unsigned long TIMEOUT_DURATION = 5000; // 5 seconds
// Variables to track button state and timeout
bool buttonPressed = false;
unsigned long buttonPressTime = 0;
bool notePlaying = false;
int currentNote = 0;
unsigned long timeoutStartTime = 0;
void setup()
{
// Initialize the button object
button1.begin();
// Set the button callback
button1.onPressed(handleButtonPress);
// Initialize MIDI
MIDI.begin();
}
void loop()
{
// Read the button state
button1.read();
// Check for timeout
if (notePlaying && millis() - timeoutStartTime >= TIMEOUT_DURATION)
{
MIDI.sendNoteOff(currentNote, 0, 1);
notePlaying = false;
}
}
void handleButtonPress()
{
// Check if the button was just pressed
if (button1.isPressed())
{
// If a note is already playing, send note off
if (notePlaying)
{
MIDI.sendNoteOff(currentNote, 0, 1);
notePlaying = false;
}
// Generate a random note
currentNote = random(MIDI_NOTE_MIN, MIDI_NOTE_MAX + 1);
// Send note on
MIDI.sendNoteOn(currentNote, 127, 1);
// Set note playing flag and timeout start time
notePlaying = true;
timeoutStartTime = millis();
}
}