/*
Forum: https://forum.arduino.cc/t/problem-sending-program-change-through-arduino-pro-micro/1405537
Wokwi: https://wokwi.com/projects/441625794402989057
ec2021
2025/09/09
*/
#include <SoftwareSerial.h>
constexpr byte buttonPin {2}; // pushbutton pin
constexpr byte ledPin {10}; // led pin
constexpr byte midiRx {6};
constexpr byte midiTx {7};
constexpr uint16_t midiBdRate {31250};
SoftwareSerial midi(midiRx,midiTx); // create a SoftwareSerial object
unsigned long changeTime = 0;
boolean ledOn = false;
void setup() {
Serial.begin(115200);
midi.begin(midiBdRate);
pinMode(buttonPin, INPUT_PULLUP); // Configure button as Input
pinMode(ledPin, OUTPUT);
}
void loop() {
if (buttonPressed()) {
sendProgramChange(2,16);
}
if (ledOn && millis()-changeTime > 1000) {
digitalWrite(ledPin,LOW);
ledOn = false;
}
}
void sendProgramChange(byte channel, byte number){ // channel = 1 .. 16, number = 0 .. 127
byte cmd = 0xC0 + ((channel-1) % 16);
//midi.write(cmd);
Serial.print("0x");
Serial.print(cmd,HEX);
Serial.print("\t0x");
Serial.println(number, HEX);
digitalWrite(ledPin,HIGH);
changeTime = millis();
ledOn = true;
}
boolean buttonPressed() {
constexpr unsigned long debounceTime {50}; // ms
static unsigned long lastChange = 0;
static byte state = HIGH;
static byte lastState = LOW;
byte actState = digitalRead(buttonPin);
if (actState != lastState) {
lastState = actState;
lastChange = millis();
}
if (state != actState && millis() - lastChange >= debounceTime) {
state = actState;
return !state;
}
return false;
}