/*
Forum: https://forum.arduino.cc/t/unexpected-activation-after-long-months-run/1385981
Wokwi: https://wokwi.com/projects/432557680640130049
Original @ Wokwi: https://wokwi.com/projects/432557652667267073
ec2021
2025/06/01
*/
constexpr byte RPWM {10}; // Arduino pin to IBT-2 pin RPWM
constexpr byte LPWM {11}; // Arduino pin to IBT-2 pin LPWM
constexpr byte buttonPin {2}; // pushbutton pin
constexpr int rpwmFadeStart {100};
constexpr int lpwmFadeStart {50};
constexpr int fadeEnd {255};
constexpr unsigned long rpwmFadeDelay {85};
constexpr unsigned long lpwmFadeDelay {84};
struct moveStruct {
byte fadePin;
byte zeroPin;
int Start;
unsigned long Delay;
};
moveStruct movement[2] = {
{RPWM, LPWM, rpwmFadeStart, rpwmFadeDelay},
{LPWM, RPWM, lpwmFadeStart, lpwmFadeDelay}
};
byte direction = 0;
void setup() {
pinMode(RPWM, OUTPUT); // Configure RPWM as an Output (actually not required for analogWrite!)
pinMode(LPWM, OUTPUT); // Configure LPWM as an Output (actually not required for analogWrite!)
pinMode(buttonPin, INPUT_PULLUP); // Configure button as Input
analogWrite(RPWM, 0);
analogWrite(LPWM, 0);
}
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;
}
void move() {
analogWrite(movement[direction].zeroPin, 0);
for (int fadeValue = movement[direction].Start; fadeValue <= fadeEnd; fadeValue += 5) {// sets the value (range from 0 to 255):
analogWrite(movement[direction].fadePin, fadeValue);
delay(movement[direction].Delay);
}
analogWrite(movement[direction].fadePin, 0);
if (direction == 0) {
direction = 1;
} else {
direction = 0;
}
}
void loop() {
if (buttonPressed()) {
move();
}
}