# Coding a slider as a linear on/off switch

**URL:** <https://forum.electromage.com/t/coding-a-slider-as-a-linear-on-off-switch/3730>\
**Category:** Patterns and Code\
**Created:** [August 29, 2024, 8:58am UTC](https://forum.electromage.com/t/coding-a-slider-as-a-linear-on-off-switch/3730 "2024-08-29T08:58:46Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jdhollan](https://forum.electromage.com/letter_avatar_proxy/v4/letter/j/eb8c5e/32.png) [@jdhollan](https://forum.electromage.com/u/jdhollan)\
**Post date:** [August 29, 2024, 8:58am UTC](https://forum.electromage.com/t/coding-a-slider-as-a-linear-on-off-switch/3730/1 "2024-08-29T08:58:46Z")

</div>

Dear coders, i am looking for some help.  
I tried to create a slider as a ‘runner-up’. (no leds when 0, all pixels on when 1)  
But i kept on getting errors of all kind.  
Someone has done this before?

The plan is to later replace the slider by an analog input from a potmeter.  
Thanks

---

<div class="post-metadata">

**Author:** ![zranger1](https://forum.electromage.com/user_avatar/forum.electromage.com/zranger1/32/301_2.png) [@zranger1](https://forum.electromage.com/u/zranger1)\
**Post date:** [August 30, 2024, 10:13pm UTC](https://forum.electromage.com/t/coding-a-slider-as-a-linear-on-off-switch/3730/2 "2024-08-30T22:13:41Z")

</div>

Hi,  
If I understand correctly, you want to use a slider, and eventually a potentiometer to control how many of the LEDs are lit on a strip or other display. Here’s one way you might do that, based on the default “rainbow” pattern (the pattern you get when you press the “New Pattern” button.)

```auto
// start with all LEDs lit
var onPct = 1

export function sliderLightsOn(v) {
  onPct = v
}

export function beforeRender(delta) {
  t1 = time(.1)
}

export function render(index) {
  // calculate the position of the current LED as a percentage of the
  // total. We'll use this to generate the rainbow color, and to 
  // determine which LEDs should be turned on.
  pct = index/pixelCount;
  
  // animated rainbow hue
  h = t1 + pct
  
  // LED will be lit if the current slider setting is greater than
  // the LED's % position in the strip. Move the slider to change
  // the number of lit LEDs.
  hsv(h, 1, onPct > pct)
}

```

---

<div class="post-metadata">

**Author:** ![jdhollan](https://forum.electromage.com/letter_avatar_proxy/v4/letter/j/eb8c5e/32.png) [@jdhollan](https://forum.electromage.com/u/jdhollan)\
**Post date:** [September 14, 2024, 9:30am UTC](https://forum.electromage.com/t/coding-a-slider-as-a-linear-on-off-switch/3730/3 "2024-09-14T09:30:37Z")

</div>

Thanks a lot Zranger, works perfectly with great potential. I am building a tubular lamp that you can dim by rotating it. Now i can add a ‘linear’ dim. I will send video soon.
