IR Sensor Reading Optimization
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)

Fantastic - glad to hear it's working the way you wanted, Jack!
A few quick notes and offers in case you want to refine further:
If you want me to convert that JavaScript to:
tell me which and I’ll post the code.
If you want the console prints removed for a cleaner runtime I can remove them (or leave a single debug print when the stable value publishes).
Reminder: if you want to act on changes to $IRADC, use the On Variable Changed skill (Project Add robot skill Scripting On Variable Changed). Configure the variable $IRADC and put whatever script you want executed. You can open any skill’s settings via the kebab (three-line) menu on the skill window.
Useful links:
https://synthiam.com/Support/Skills/Adc/ADC-Graph
https://synthiam.com/Support/Skills/Adc/ADC-Value
Anything else you want tweaked (12-bit, median, Python, fewer prints, or integration examples with On Variable Changed)?
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.