DEV Community

Hedy
Hedy

Posted on

How to use pot to set delay function of Arduino?

Here’s the quick way to make a potentiometer (pot) set an Arduino’s delay time.

Wiring (10 kΩ pot is perfect)

  • One outer leg → 5V
  • Other outer leg → GND
  • Middle wiper → A0
  • We’ll blink the onboard LED on D13.

If the pot works “backwards,” just swap the two outer legs.

A) Easiest (uses delay()—blocking)

const int POT = A0;
const int LED = 13;

void setup() {
  pinMode(LED, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  // Read 0..1023 from the pot
  int raw = analogRead(POT);

  // Map to a usable delay range, e.g. 50..2000 ms
  long delayMs = map(raw, 0, 1023, 50, 2000);

  // (Optional) simple smoothing to reduce jitter
  static long filt = 200;
  filt = (filt * 7 + delayMs) / 8;  // 1st-order IIR filter

  digitalWrite(LED, !digitalRead(LED));  // toggle LED
  Serial.println(filt);
  delay(filt);  // pot sets the delay
}
Enter fullscreen mode Exit fullscreen mode

B) Better style (non-blocking with millis())

This avoids freezing the CPU, so you can read buttons/sensors while blinking.

const int POT = A0;
const int LED = 13;

unsigned long interval = 300;    // ms, updated from the pot
unsigned long lastToggle = 0;
bool ledState = false;

void setup() {
  pinMode(LED, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  // Read and map pot to 30..1500 ms (adjust to taste)
  int raw = analogRead(POT);
  unsigned long newInterval = map(raw, 0, 1023, 30, 1500);

  // Optional smoothing
  interval = (interval * 3 + newInterval) / 4;

  // Time-based toggle
  unsigned long now = millis();
  if (now - lastToggle >= interval) {
    ledState = !ledState;
    digitalWrite(LED, ledState);
    lastToggle = now;
    Serial.println(interval);
  }

  // Do other work here without blocking...
}
Enter fullscreen mode Exit fullscreen mode

Tips

  • Range shaping: Human perception likes finer control at short delays. You can make the bottom end more precise by mapping nonlinearly (e.g., exponential).
float x = analogRead(A0) / 1023.0;          // 0..1
unsigned long delayMs = 20 * pow(100.0, x); // ~20..2000 ms
Enter fullscreen mode Exit fullscreen mode
  • Noise suppression: A 0.1 µF cap from A0 → GND (near the pot) can steady readings.
  • 3.3 V boards: Power the pot from 3.3 V, not 5 V, to protect the analog pin.
  • Multiple controls: You can read more pots (A1, A2…) to set other parameters (brightness, duty cycle, etc.).

Top comments (0)