Hello @Athena,
I would appreciate your review of the following JavaScript code within the ARC environment. The script is designed to process infrared (IR) sensor readings, which can vary significantly due to sensor noise. My objective is to obtain a reliable result, finalLowIR, that only changes when the last three samples are consistent.
The current algorithm involves collecting three samples from an IR sensor connected via the ADC feature, calculating the lowest value from each set of samples, and then using a moving average to stabilize the reading. The final variable finalLowIR is adjusted to limit variability.
//$IRSAMPLE consists of three sample IR readings.
//lowIR is identified as the lowest of the three $IRSAMPLE readings.
//totLowIR aggregates the sum of three lowIR readings.
//avgLowIR is calculated as ((totLowIR * 1000)/3).
//finalLowIR is rounded and divided by 10000 to manage IR reading variability.
while(true) {
var totLowIR = 0;
var avgLowIR = 0;
for(var count1 = 0; count1 < 3; count1++) { // Loop for 3 samples
var lowIR = 300;
for (var count = 0; count < 3; count++) { // Capture individual samples
setVar("$IRSAMPLE", ADC.get(2)); // Obtain IR sample
if (getVar("$IRSAMPLE") < lowIR) {
lowIR = getVar("$IRSAMPLE");
}
}
totLowIR += lowIR;
}
avgLowIR = ((totLowIR * 1000) / 3);
finalLowIR = Math.round(avgLowIR / 10000);
setVar("$IRADC", finalLowIR); // Store the final reading
sleep(100); // Pause the loop for 100ms
}
Could you provide feedback or suggestions for a more efficient script in this context? Your expertise would be greatly appreciated.
Thank you,
Jack
Related Hardware (view all EZB hardware)
Related Robot Skills (view all robot skills)

Thanks - nice explanation of your intent. Your script works but has a few inefficiencies and some strange math that reduces precision unnecessarily. Below I explain the issues and provide two cleaner, robust JavaScript approaches you can drop into an ARC Script robot skill.
Key notes up front
Option A - Median sampling + 3-sample stability (recommended) Behavior: for each cycle, take several quick ADC samples, compute a robust sample (median). Keep the last 3 robust samples and only update final reading when those 3 are consistent within a small tolerance. This matches your requirement "only changes when the last three samples are consistent."
Why this is good:
Tuning:
Option B - Exponential Moving Average (EMA) + threshold (more responsive) Behavior: smooths the value continuously; update final only when smoothed value changes by a meaningful threshold (debounce).
Why this is good:
Extra tips & links
Questions so I can make this even more specific
If you tell me your port and the acceptable tolerance & update rate, I’ll adapt the code to those exact numbers and give recommended values for sample counts/delays.
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.