Push Button Time Step

Hello all,

I am fairly new to coding on the Arduino IDE. I am currently working on a project for one of my classes.

Currently, my code looks as attached.

In this project, my arduino is attached to a breadboard with a circuit of resistors and LEDs. Most of the code is written to make the LEDs blink with a "Knight Rider" effect. From there the code has been adapted so that the speed of the effect can be altered. First, the speed can be altered by a potentiometer or a push button: this choice is decided by a switch. Once the switch indicates to use the push button or the potentiometer, the chosen method will alternate the speed. The potentiometer alternating code has already been written. I now just need to write a code so that the speed of the effect is determined by how long the user is pushing down the button. The effect also needs to vary as the button is being pushed, not just at the end of the push. (ie if the push is long, the effect slows down even before the user takes their finger off the button)

Looking for any suggestions and tips!

lab3_q3.ino (1.89 KB)

  • use a button library to make your life easier
  • when button is pressed record the time
  • as the loop loops, update the speed based on time passing and recorded time
  • when button is released stop updating the speed

here is an example that works in the Serial Console opened at 115200 bauds. Button is on pin 27 as in your code and needs to be wired this way : pin 27 --- button ---- GND

You'll need the OneButton library

#include <OneButton.h>  // http://www.mathertel.de/Arduino/OneButtonLibrary.aspx

OneButton button(27, true); // wire pin 27 --- button ---- GND

bool adjustSpeed = false;
uint32_t topChrono;
int currentSpeed = 100;

void buttonPressed()
{
  Serial.println(F("Start Decreasing Speed"));
  printSpeed();
  adjustSpeed = true;
  topChrono = millis();
}

void buttonReleased()
{
  Serial.println(F("Stop Decreasing Speed"));
  printSpeed();
  adjustSpeed = false;
}

void printSpeed()
{
  Serial.print(F("Speed = "));
  Serial.println(currentSpeed);
}

void monitorSpeed()
{
  button.tick();
  if (adjustSpeed && (millis() - topChrono >= 1000ul)) {
    if (currentSpeed != 0) currentSpeed--;
    printSpeed();
    topChrono = millis();
  }
}

void setup() {
  Serial.begin(115200);
  button.attachLongPressStart(buttonPressed);
  button.attachLongPressStop(buttonReleased);
  printSpeed();
}

void loop() {
  monitorSpeed();
}

The speed will slowly decrease when button is long pressed by -1 every second the button is held down