Asked — Edited
Resolved Resolved by Athena AI!

Help With Sorting Array Implementation

Hello @Athena,

I'm currently working on a project where I need to sort values and utilize the lowest value within my script using Synthiam ARC. I believe that utilizing an array in JavaScript is the appropriate approach. Although I have researched JavaScript commands and sorting techniques, I would appreciate some assistance to jumpstart my implementation process.

Objectives:

  1. Capture a single servo's position and take five sample readings from an infrared (IR) sensor. I need to sort these readings to find the lowest value and associate this lowest IR reading with the current servo position.
  2. Repeat the first step for nine consecutive servo positions.
  3. Identify which servo position corresponds to the lowest IR value among all the sampled positions.

Could you provide an example of how to structure an array in JavaScript within ARC to achieve these objectives?

Thank you for your support,
Jack


Related Hardware Roli Rover

ARC Pro

Upgrade to ARC Pro

Stay on the cutting edge of robotics with ARC Pro, guaranteeing that your robot is always ahead of the game.

PRO
Canada
#1  

Below is an example that demonstrates one approach using JavaScript in ARC. In this example, we assume:

Your servo is controlled by a robot skill (for example, using Servo.setPosition) on a specific digital port (for example d1).
Your IR sensor is connected to an ADC port (for example ADC0).
You have an array of nine servo angles (you can change these values to match your positions).

The script will:

  1. Move the servo to one of the nine positions.
  2. Take five sample readings from the IR sensor.
  3. Sort the readings to pick the lowest value for that position.
  4. Store the lowest value along with the respective servo position.
  5. Finally, compare all positions to figure out which servo position produced the lowest IR reading.

You can paste the following code into your Script skill’s JavaScript editor in ARC:


// Example: Sort IR sensor samples over multiple servo positions

// Define the servo port and IR sensor ADC port (update these to your configuration)
var servoPort = d1;      // (Change this to your servo's port: e.g., d1, d2, etc.)
var irSensorPort = ADC0; // (Change this to your ADC sensor port, e.g., ADC0)

// Define an array of servo positions (in degrees) you want to test.
// In this case we use 9 positions.
var servoPositions = [10, 20, 30, 40, 50, 60, 70, 80, 90];

// Variables to hold overall best (lowest) IR reading and corresponding servo position.
var overallLowestIR = Number.MAX_VALUE;
var bestServoPosition = null;

// Loop through each servo position.
for (var i = 0; i < servoPositions.length; i++) {
  
  // Set the servo to the current position.
  var currentPos = servoPositions[i];
  print("Setting servo to position: " + currentPos);
  Servo.setPosition(servoPort, currentPos);
  
  // Wait a short period for the servo to reach its position.
  sleep(500);  // 500 ms delay (adjust if necessary)
  
  // Create an array to store our IR sensor samples.
  var irSamples = [];
  
  // Take 5 IR sensor readings.
  for (var j = 0; j < 5; j++) {
    // Read the IR sensor value. 
    // Note: ADC.get() returns a value between 0-255. Adjust if your sensor or sampling method differs.
    var reading = ADC.get(irSensorPort);
    print("Sample " + (j + 1) + " at pos " + currentPos + ": " + reading);
    irSamples.push(reading);
    
    // Wait a little between samples (adjust timing if necessary).
    sleep(100);
  }
  
  // Sort the samples numerically to get the lowest sample as the first element.
  irSamples.sort(function(a, b) {
    return a - b;
  });
  
  var lowestForThisPos = irSamples[0];
  print("Lowest IR reading at servo position " + currentPos + " is " + lowestForThisPos);
  
  // Check if the current position has the overall lowest IR reading.
  if (lowestForThisPos < overallLowestIR) {
    overallLowestIR = lowestForThisPos;
    bestServoPosition = currentPos;
  }
  
  // Optional: short delay before the next servo position
  sleep(250);
}

// After checking all positions, output the best servo position and its IR reading.
print("Overall lowest IR reading is " + overallLowestIR + " at servo position " + bestServoPosition);

Explanation

  1. Setup and Variables
    We set your servo port and the IR sensor port.
    An array called servoPositions is established with nine desired positions.

  2. Looping Through Positions
    For each servo position, the servo is moved to that angle using Servo.setPosition.
    The script waits (with sleep) for the servo to reach its destination.

  3. Sampling & Sorting
    Five samples are acquired from the IR sensor using ADC.get.
    These samples are pushed into an array which is then sorted numerically.
    The lowest sample (the first element after sorting) is taken as that servo’s reading.

  4. Determine the Best Position
    The script compares all the lowest samples from each servo position to find the overall lowest reading and saves the corresponding servo position.

  5. Output Results
    Finally, the overall best IR reading and the servo position that produced it are printed.

Next Steps

Adjust the ports (servoPort and irSensorPort) and sleep durations based on your hardware setup and response time.
You might later decide to store these results in global ARC variables for other skills (using setVar()) or use them further in your project.

If you have any questions or need further details, please let me know!


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.
#2  

Thank you @Athena.  Arrays are new to me, and I will need to study and experiment with the examples and commands that you have introduced.  I intend to use arrays in multiple scripts that I have underway.   Thank you Jack

PRO
Canada
#3  

You're very welcome, Jack!

I'm glad you found the sample useful. Arrays can be incredibly powerful when you're working on projects in ARC, especially when you have to capture and analyze multiple readings. Do take your time experimenting with the code and commands. As you explore further, here are a couple of quick tips:

  • Debugging: Use the print() command liberally so you can see the values in your console as your code runs. This is very helpful when learning arrays.
  • Global Variables: When you need to pass values between scripts or controls, consider storing your results with setVar() to share data across ARC.
  • Documentation: If you're curious about other JavaScript functions or want to dive deeper, you can check out additional examples on our Synthiam support site: Synthiam Support.

If you run into any more issues or need further examples while working on your scripts, feel free to ask. Happy coding and good luck with your project!


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.
#4  

@Athena, Thank you for your continued help.  I wish to modify the previous provided script to accomplish the following STEPS:

1. Move the servo to one of the nine positions. 2. Take five sample readings from the IR sensor. 3. Sum the five sample readings. 4. Store the sum value with the respective servo position. 5. Finally, compare all positions to figure out which servo position produced the lowest sum IR reading.

Could you please provide a JavaScript to perform these steps? Thank you, Jack

PRO
Canada
#5  

Below is an example JavaScript code snippet for ARC that adapts the previous script to perform these steps:

  1. Move the servo to one of the nine positions.
  2. Take five sample IR sensor readings.
  3. Sum the five samples.
  4. Store the sum value associated with that servo position.
  5. Compare all positions to find which produced the lowest total reading.

Copy the code into your Script skill’s JavaScript editor and adjust the ports, positions, and sleep durations as needed for your setup.

// Define the servo port (update to match your configuration)
var servoPort = d1; // Example: servo connected to port d1

// Define the IR sensor's ADC port (update to match your configuration)
var irSensorPort = ADC0; // Example: IR sensor connected to ADC0

// Define an array of nine servo positions (angles in degrees)
var servoPositions = [10, 20, 30, 40, 50, 60, 70, 80, 90];

// Variables to store the overall lowest sum of IR readings and its associated servo position
var overallLowestSum = Number.MAX_VALUE;
var bestServoPosition = null;

// Loop through each servo position
for (var i = 0; i < servoPositions.length; i++) {
    // Set the servo to the current position
    var currentPos = servoPositions[i];
    print("Setting servo to position: " + currentPos);
    Servo.setPosition(servoPort, currentPos);

    // Wait for the servo to reach its destination (adjust delay as needed)
    sleep(500); // 500 ms delay

    // Initialize sum for the current position
    var sumIR = 0;

    // Take 5 IR sensor samples and calculate their sum
    for (var j = 0; j < 5; j++) {
        var reading = ADC.get(irSensorPort); // ADC.get returns a value between 0 and 255
        sumIR += reading;
        print("Sample " + (j + 1) + " at pos " + currentPos + ": " + reading);
        sleep(100); // slight delay between samples
    }
    
    print("Sum of IR readings at servo position " + currentPos + " is " + sumIR);
    
    // Check if this sum is lower than all previous ones
    if (sumIR < overallLowestSum) {
        overallLowestSum = sumIR;
        bestServoPosition = currentPos;
    }
    
    // Optional: delay before moving to the next position
    sleep(250);
}

// Output the final result with the lowest sum of IR readings
print("Overall lowest sum IR reading is " + overallLowestSum + " at servo position " + bestServoPosition);

Explanation

  1. Setup and Variables:

    • The servo and IR sensor ports are defined (adjust as necessary).
    • An array of nine servo positions is created.
  2. Loop Through servo Positions:

    • For each position, the code commands the servo to move using Servo.setPosition() and waits for it to settle.
    • It then initializes a sum variable (sumIR).
  3. Sampling the IR Sensor:

    • A forloop takes five samples with a short delay between each sample using ADC.get(), adding each reading to the sum.
  4. Determine the Best servo Position:

    • After summing, the script prints the sum for that position and checks if it’s lower than the current best.
  5. Final Output:

    • Once all positions are checked, the final best position along with the lowest IR sum is printed.

Feel free to experiment with sleep durations and sensor readings based on your sensor's response. If you have any more questions or need further assistance, let me know!


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.
#6   — Edited

Hi @ Athena; I am still learning about Arrays. I am able to do some, but not all of the following steps.  I need to write JavaScript code that will accomplish the following:

1.  Reposition servo to 45 degrees.

2.   Begin scan at 45 degrees measuring IR Value for each degree (+1) until reaching 90 degrees.  The IR Value will be measured 3 times and a Low IR Value for each degree noted.

3.   Arriving back at 90 degrees, reposition servo to 135 degrees.

4.  Begin scan from 135 degrees measuring IR Values for each degree (-1) until reaching 91 degrees.  The IR Value will be measured 3 times and a Low IR Value for each degree noted.

5.  An Absolute Low IR Value for the entire scan from 45 degrees to 135 degrees will be determined and the servo position noted as global variable Actual Course.

6.  The Low IR Value at degrees (83,84,85) will be combined and noted as global variable Neg Total.

7.  The Low IR Value at degrees (97,96,95) will be combined and noted as global variable Pos Total.

Could you please write JavaScript that I can copy and paste for the above steps 1-7? Thank you, Jack

PRO
Canada
#7  

Below is an example JavaScript code snippet you can copy into your Script skill in ARC. This script will:

  1. Reposition the servo to 45.
  2. From 45 to 90 (in 1 increments), sample the IR sensor 3 times at each degree and record the lowest reading.
  3. Reposition the servo to 135.
  4. From 135 down to 91 (in 1 decrements), sample the IR sensor 3 times at each degree and record the lowest reading.
  5. Check all stored readings (from 45 to 90 plus 135 to 91) to determine which servo position produced the absolute lowest IR value. This value’s degree is stored in the global variable Actual Course.
  6. Calculate the sum of the lowest IR readings at degrees 83, 84, & 85 and store in global variable Neg Total.
  7. Calculate the sum of the lowest IR readings at degrees 97, 96, & 95 and store in global variable Pos Total.

Simply adjust ports, sleep times, and comments as necessary for your setup.

// Define the servo and IR sensor ports (adjust to your hardware configuration)
var servoPort = d1;        // e.g., connected on port d1
var irSensorPort = ADC0;   // e.g., connected to ADC0

// Object to store the lowest IR reading for each degree scanned
var scanResults = {};

// ---------------------
// Phase 1:
// Scan from 45 to 90 (increasing)
// ---------------------
print("=== Phase 1: Scanning from 45 to 90 ===");

// Start at 45
Servo.setPosition(servoPort, 45);
sleep(500); // Allow servo to reach 45

// Loop from 45 to 90 (increment by 1)
for (var pos = 45; pos <= 90; pos++) {
    // Move servo to the current position
    print("Moving servo to " + pos + "");
    Servo.setPosition(servoPort, pos);
    sleep(300); // Adjust delay for your servo response time

    // For each position, take 3 IR sensor samples and record the lowest value
    var lowValue = Number.MAX_VALUE;
    for (var sample = 0; sample < 3; sample++) {
        var reading = ADC.get(irSensorPort);
        print("  Pos " + pos + " sample " + (sample + 1) + ": " + reading);
        if (reading < lowValue) {
            lowValue = reading;
        }
        sleep(100); // Delay between samples
    }
    // Store the lowest value for the current degree
    scanResults[pos] = lowValue;
    print("  -> Lowest IR at " + pos + " = " + lowValue);
    sleep(100);
}

// ---------------------
// Phase 2:
// Reposition servo to 135 and scan from 135 down to 91 (decreasing)
// ---------------------
print("=== Phase 2: Scanning from 135 to 91 ===");

// Reposition servo to 135
Servo.setPosition(servoPort, 135);
sleep(500); // Allow servo to reach 135

for (var pos = 135; pos >= 91; pos--) {
    // Move servo to the current position
    print("Moving servo to " + pos + "");
    Servo.setPosition(servoPort, pos);
    sleep(300);  

    // Take 3 samples for each degree and record the lowest value
    var lowValue = Number.MAX_VALUE;
    for (var sample = 0; sample < 3; sample++) {
        var reading = ADC.get(irSensorPort);
        print("  Pos " + pos + " sample " + (sample + 1) + ": " + reading);
        if (reading < lowValue) {
            lowValue = reading;
        }
        sleep(100);
    }
    // Store the lowest value for the current degree
    scanResults[pos] = lowValue;
    print("  -> Lowest IR at " + pos + " = " + lowValue);
    sleep(100);
}

// ---------------------
// Phase 3:
// Determine the absolute lowest IR reading across all degrees scanned
// and store its servo position as global variable Actual Course.
// ---------------------
var overallLowest = Number.MAX_VALUE;
var actualCourse = null;

for (var degree in scanResults) {
    var reading = scanResults[degree];
    if (reading < overallLowest) {
        overallLowest = reading;
        actualCourse = parseInt(degree); // ensure it's a number
    }
}
print("=> Overall lowest IR reading: " + overallLowest + " at " + actualCourse + "");
setVar("$ActualCourse", actualCourse);  

// ---------------------
// Phase 4:
// Calculate Neg Total: The sum of low IR values at degrees 83, 84, and 85
// ---------------------
var negTotal = 0;
negTotal += (scanResults[83] !== undefined ? scanResults[83] : 0);
negTotal += (scanResults[84] !== undefined ? scanResults[84] : 0);
negTotal += (scanResults[85] !== undefined ? scanResults[85] : 0);
print("=> Neg Total (sum at 83,84,85): " + negTotal);
setVar("$NegTotal", negTotal);

// ---------------------
// Phase 5:
// Calculate Pos Total: The sum of low IR values at degrees 97, 96, and 95
// (from the scan in Phase 2)
// ---------------------
var posTotal = 0;
posTotal += (scanResults[97] !== undefined ? scanResults[97] : 0);
posTotal += (scanResults[96] !== undefined ? scanResults[96] : 0);
posTotal += (scanResults[95] !== undefined ? scanResults[95] : 0);
print("=> Pos Total (sum at 97,96,95): " + posTotal);
setVar("$PosTotal", posTotal);

How It Works:

  1. Initialization:

    • The servo and IR sensor ports are defined.
    • An empty object (scanResults) is used to store the lowest IR value for each degree.
  2. Phase 1 (45 to 90):

    • The servo moves from 45 to 90 in 1 increments.
    • At each degree, the script takes three IR sensor readings and keeps the lowest one.
  3. Phase 2 (135 to 91):

    • The servo is repositioned to 135.
    • It then scans from 135 down to 91 (decrementing by 1) and records the lowest IR reading for each position.
  4. Phase 3 (Finding the Overall Lowest):

    • The script iterates through all stored results (from both scan phases) to find the absolute lowest reading and its corresponding degree.
    • This servo position is stored in the global variable Actual Course.
  5. Phase 4 (Neg Total):

    • The script sums the IR readings at degrees 83, 84, and 85 (from Phase 1) and stores that sum to the global variable Neg Total.
  6. Phase 5 (Pos Total):

    • The script sums the IR readings at degrees 97, 96, and 95 (from Phase 2) and stores the result in the global variable Pos Total.

Feel free to adjust the sleep durations, servo ports, ADC ports, and angle ranges as needed for your particular robot configuration and IR sensor response characteristics. If you have any more questions or need further assistance, just let me know!


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.
#8  

Thank you @ Athena.  The coding architecture in phases 4 and 5 are the most difficult for me to understand.  Is there a tutorial or website that could teach me more about Arrays and their structure? BTW, the code works perfectly.   Thankyou Jack