Checking controls & millisDelay

Hi,

I'm trying to send a series of timing pulses with variable rate.
I'm using a millisDelay to set a loop and another one to read the value of a pot which sets the rate.
This seems to kind of work, but whenever I turn the pot I have to stop and restart the timer to set the new rate. This stops the pulses while the pot is being turned and I'd like to keep them going even while adjusting their rate.

What is a better way to do this?

Here's the code:

#include <millisDelay.h>

const unsigned int pinSeq = 2;

const unsigned int hysterisis = 2;
const unsigned int minClock = 20;
const unsigned int maxClock = 1000;

int clockPot;

millisDelay internal_clock;
millisDelay trig_length;
millisDelay control_timer;

void setClock(int rate) {
  internal_clock.stop();
  internal_clock.start(rate);
}

void checkClock() {
  // check if delay has timed out
  if (internal_clock.justFinished()) {
    internal_clock.repeat();
    // start delay again without drift
    // do stuff
    Serial.write("X");
  }
}


void checkControls() {
  // check if delay has timed out
  if (control_timer.justFinished()) {
    float newClock = analogRead(A0);
    if (clockPot + hysterisis < newClock || clockPot - hysterisis > newClock) {
      clockPot = newClock;
      newClock = ((newClock / 1023) * (maxClock - minClock)) + minClock;
      setClock((int)newClock);
    }
    control_timer.repeat();
  }
}

void setup() {
  Serial.begin(9600);
  clockPot = analogRead(A0);
  internal_clock.start(100);
  control_timer.start(100);
  pinMode(pinSeq, OUTPUT);
}

void loop() {
  checkControls();
  checkClock();
}

Please provide a link to the 'millisDelay' library.

It's this one: https://www.forward.com.au/pfod/ArduinoProgramming/TimingDelaysInArduino.html

Hello torigurafu

Keep it simple and stupid.

Check, test and modify the BLINKWITHOUTDELAY example from the IDE.

I agree with @paulpaulson. You have made something that is very simple into something that is complex, and difficult to understand though the use of unnecessary libraries.

I think the following does what you want, and you don't have to search through library code to understand how it works.

unsigned long currMillis, prevMillis, duration;

void setup()
{
  Serial.begin(115200);
}

void loop()
{
  currMillis = millis();
  
  duration = map(analogRead(A0), 0, 1023, 20, 1000);

  if (currMillis - prevMillis > duration)
  {
    prevMillis = currMillis;
    Serial.println(duration);
  }
}

Indeed! Thank you both!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.