Asked

How To Create Multidimensional Arrays?

Can you please show me how to create an array with 20 names and 3 values per line (x,y,z values)  Produce a chart on the desktop to contain these names and values. Then pull the values off the particular line name. Put the values into "Make servo move to" This would be a big help  Thanks, Don


ARC Pro

Upgrade to ARC Pro

ARC Pro is more than a tool; it's a creative playground for robot enthusiasts, where you can turn your wildest ideas into reality.

PRO
Synthiam
#1   — Edited

This is a good place to start: https://www.w3schools.com/js/js_arrays.asp

and this is another: https://www.programiz.com/javascript/multidimensional-array

#2   — Edited

Ok I got it and understand it, what would the best way to incorporate this script within Blockly?

Actually a perfect fit will be the new block that you made for Javascript which will come out in next update. While you are making the block if it is possible to actually change the name of the block as you go would be very nice. In the meantime how could this be done?

This past weekend I had my bot to locate an edge with high accuracy and pickup with a 5'' suction cup a piece of walnut wood. Next up is to pick up a sheet of 3/4 plywood and place it wherever it is needed, but this will take a bit because I need to add the second 6' arm which was already figured in the planning. Also will be adding more suction cups over a wider surface. It has already picked up 100 lbs with one arm.

#3  

I really enjoy learning from the second one https://www.programiz.com/javascript/multidimensional-array  and I can experiment with running the code in various ways

#4  

Have the multidimensional array working nicely in typical Javascript console but realized things are set up a bit differently in ARC, could you please clarify some of these items let itemToFind = 'cookies';    is this ok?    setVar("$itemToFind", getVar("cookies"));            added question is ' ok or do I have to put " ? Is let ok in ARC? let stock = [{item:'cookies', xvalue: 22, yvalue: 33, zvalue: 44},  {etc}];     is this ok?   setVar("$stock",[{item:'cookies', xvalue: 22, yvalue: 33, zvalue: 44}, {etc}]); let Wall = stock.find((s) => s.item === itemToFind);   is this ok?  setVar("$Wall", stock.find((s) => s.item === getVar("$itemToFind);  let xposition = Wall.xvalue;       is this ok?    setVar($"xposition", "$Wall".xvalue); I tried inputing all of these but I get Unexpected end of input a sample multidimensional array in ARC would also help Thanks, Don

PRO
Synthiam
#5  

I have an idea for you but it'll take a few days for the next ARC update. stay tuned

#6  

Wonderful, thanks As I dig into some of these items I can really understand and appreciate how there is a ton of knowledge needed by you and your team to make these things all work together.

#7  

I downloaded the update for ARC and noticed the new Javascript Block -thanks. Still trying to get the multidimensional array working do you have some sample code that I can look over and see how you transitioned from typical Javascript with let etc to script that works within ARC?

PRO
Synthiam
#8   — Edited

From the manual: https://synthiam.com/Support/javascript-api/javascript-overview

setVarObject( variableName, value ) Sets the value from Arc’s public global variable storage of the object. This allows the variable to be available to other robot skills or scripts using getVar(). (Read More). This differs from setVar() because it sets the value as an object without translation. So you can pass entire objects, such as functions, classes, or multidimensional arrays.

{variableName} - The name of the global variable as a string {value} The object value that you wish to store in the global variable

Example:

// Set the multidimensional array to be accessible by other robot skills using getVar()
x = [ [0, 1, 2], [3, 4, 5] ];
setVar($MyValue, x);

So, after setting the array object to the global variable store, it can be accessed by any other robot skill. Another robot skill can retrieve the array object into its localized variable scope.

var x = getVar("$MyValue");

print(x[1][1]);
PRO
Synthiam
#9  

@Athena explain more on this topic.

PRO
Canada
#10  

Certainly! In ARC, you can use JavaScript to create and manipulate multidimensional arrays, which are essentially arrays of arrays. These can be used to store complex data structures, such as a list of items where each item has multiple attributes (like x, y, z coordinates).

To create a multidimensional array in ARC, you can use standard JavaScript syntax. However, when you want to store this array as a global variable that can be accessed by other robot skills within ARC, you should use the setVarObject() function. This function allows you to store objects, including multidimensional arrays, in ARC's global variable storage.

Here's an example of how you might create a multidimensional array and use it within ARC:

// Define a multidimensional array with items and their x, y, z values
var stock = [
  { item: "cookies", xvalue: 22, yvalue: 33, zvalue: 44 },
  { item: "milk", xvalue: 10, yvalue: 20, zvalue: 30 },
  // ... more items
];

// Store the array in ARC's global variable storage
setVarObject("$stock", stock);

// Function to find an item in the stock by name and return its coordinates
function findItemCoordinates(itemName) {
  var stockArray = getVar("$stock");
  var item = stockArray.find(function(element) {
    return element.item === itemName;
  });
  return item ? { x: item.xvalue, y: item.yvalue, z: item.zvalue } : null;
}

// Example usage: find the coordinates of "cookies"
var cookiesCoordinates = findItemCoordinates("cookies");
if (cookiesCoordinates) {
  print("Cookies coordinates: X=" + cookiesCoordinates.x + ", Y=" + cookiesCoordinates.y + ", Z=" + cookiesCoordinates.z);
}

In the example above, we define a multidimensional array called stock that contains objects with item, xvalue, yvalue, and zvalue properties. We then store this array in the global variable storage using setVarObject(). The findItemCoordinates() function is used to search for an item by name and return its coordinates if found.

When you want to use the stored array in another robot skill or script, you can retrieve it with getVar() and then access its elements as you would with any JavaScript array.

Keep in mind that in ARC, the let keyword is not used. Instead, you can use var to declare variables. Additionally, when referring to global variables within ARC, you should prefix the variable name with a dollar sign ($) when using setVarObject(), getVar(), and similar functions.

Lastly, the print() function is used to output text to the debug console in ARC, which can be helpful for debugging and verifying that your scripts are working as expected.


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

I appreciate your help and this is very useful information. Have many different plans for using these arrays. Thanks

#12  

I am impressed by Athena and will try to use her abilities more often @Athena can you show me more multidimensional array examples

PRO
Canada
#13  

Certainly! Multidimensional arrays in JavaScript can be used to store complex data structures. Here are a few examples of how you might use multidimensional arrays in different scenarios within ARC:

Example 1: Storing and Accessing Robot Joint Positions

// Define a multidimensional array with joint positions for different robot poses
var robotPoses = {
  'Wave': { 'Shoulder': 45, 'Elbow': 90, 'Wrist': 135 },
  'Point': { 'Shoulder': 90, 'Elbow': 45, 'Wrist': 0 },
  'Rest': { 'Shoulder': 0, 'Elbow': 0, 'Wrist': 0 }
};

// Store the array in ARC's global variable storage
setVarObject($robotPoses, robotPoses);

// Function to move robot joints to a specific pose
function moveToPose(poseName) {
  var poses = getVar($robotPoses);
  var pose = poses[poseName];
  if (pose) {
    // Assuming you have functions to move each joint
    moveShoulder(pose['Shoulder']);
    moveElbow(pose['Elbow']);
    moveWrist(pose['Wrist']);
  } else {
    print('Pose not found: ' + poseName);
  }
}

// Example usage: move robot to 'Wave' pose
moveToPose('Wave');

Example 2: Storing Sensor Data Over Time

// Define a multidimensional array to store sensor data over time
var sensorData = {
  'Temperature': [],
  'Humidity': [],
  'Light': []
};

// Function to record sensor data
function recordSensorData(sensorType, value) {
  var data = getVar($sensorData);
  if (data[sensorType]) {
    data[sensorType].push(value);
    setVarObject($sensorData, data); // Update the global variable
  } else {
    print('Sensor type not found: ' + sensorType);
  }
}

// Example usage: record temperature data
recordSensorData('Temperature', 23.5);

Example 3: Creating a Grid or Map for Navigation

// Define a multidimensional array to represent a grid or map
var grid = [];
for (var i = 0; i < 10; i++) {
  grid[i] = []; // Create a new row
  for (var j = 0; j < 10; j++) {
    grid[i][j] = 0; // Initialize all cells to 0
  }
}

// Store the grid in ARC's global variable storage
setVarObject($grid, grid);

// Function to update a cell in the grid
function updateGridCell(x, y, value) {
  var grid = getVar($grid);
  if (grid[x] && grid[x][y] !== undefined) {
    grid[x][y] = value;
    setVarObject($grid, grid); // Update the global variable
  } else {
    print('Invalid grid coordinates: ' + x + ',' + y);
  }
}

// Example usage: mark a cell as an obstacle
updateGridCell(5, 5, 1);

In these examples, we use setVarObject() to store the multidimensional array in ARC's global variable storage, and getVar() to retrieve it for manipulation. The print() function is used for debugging purposes to output messages to the console.

Remember that when working with ARC, you should use the provided functions (setVarObject(), getVar(), etc.) to interact with global variables, as they allow you to share data between different robot skills and scripts within 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.
#14  

@Athena can you show me examples of a bar code and a QR code used in a multidimensional array

PRO
Canada
#15  

Creating a multidimensional array to store barcode or QR code data involves structuring your array to hold the necessary information for each code. Here's how you might set up such arrays in ARC using JavaScript:

Example 1: Storing Barcode Data

// Define a multidimensional array with barcode data
var barcodes = [
  { code: "123456789012", product: "Milk", price: 2.99 },
  { code: "987654321098", product: "Bread", price: 1.50 },
  { code: "567890123456", product: "Eggs", price: 3.25 }
  // ... more barcode data
];

// Store the array in ARC's global variable storage
setVarObject($barcodes, barcodes);

// Function to find a product by barcode
function findProductByBarcode(barcode) {
  var barcodeArray = getVar($barcodes);
  var productInfo = barcodeArray.find(function(item) {
    return item.code === barcode;
  });
  return productInfo || null;
}

// Example usage: find product information by barcode
var productInfo = findProductByBarcode("123456789012");
if (productInfo) {
  print("Product: " + productInfo.product + ", Price: $" + productInfo.price);
} else {
  print("Barcode not found.");
}

Example 2: Storing QR Code Data

// Define a multidimensional array with QR code data
var qrCodes = [
  { code: "QR123", url: "https://www.example.com", description: "Company Website" },
  { code: "QR456", url: "https://www.example.org", description: "Organization Homepage" },
  { code: "QR789", url: "https://www.example.net", description: "Network Services" }
  // ... more QR code data
];

// Store the array in ARC's global variable storage
setVarObject($qrCodes, qrCodes);

// Function to get URL by QR code
function getUrlByQRCode(qrCode) {
  var qrCodeArray = getVar($qrCodes);
  var qrInfo = qrCodeArray.find(function(item) {
    return item.code === qrCode;
  });
  return qrInfo ? qrInfo.url : null;
}

// Example usage: get URL associated with a QR code
var url = getUrlByQRCode("QR123");
if (url) {
  print("URL: " + url);
} else {
  print("QR code not found.");
}

In these examples, we define arrays to store barcode and QR code data, where each entry is an object containing relevant information. We then use setVarObject() to store these arrays in ARC's global variable storage. The findProductByBarcode() and getUrlByQRCode() functions are used to search for specific entries based on a code, and the print() function outputs the results to the console.

Please note that these examples are for storing and retrieving data within ARC. To actually read barcodes or QR codes, you would need to use ARC's camera and vision recognition capabilities or integrate with a barcode/QR code scanning device.


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

Wow took about 15 seconds! That is pretty amazing information Athena is Hired! on the spot.  Thanks!

#17  

@Athena could you show me examples of an excel sheet with products,  x coordinates, y coordinates, z coordinates, QR code, Barcode, price, put into an array in ARC and then move X motor, Y motor, Z motor to their respective x, y, and z coordinates.

PRO
Canada
#18  

Certainly! To simulate an Excel sheet with product information and coordinates in ARC, you would create a multidimensional array to store the data. Then, you can use this array to move motors to the specified coordinates based on the product's QR code or barcode.

Here's an example of how you might set up the array and use it to control motors:

// Define a multidimensional array with product information and coordinates
var productData = [
  { product: "Widget A", x: 10, y: 20, z: 30, qrCode: "QR001", barcode: "123456789012", price: 9.99 },
  { product: "Gadget B", x: 40, y: 50, z: 60, qrCode: "QR002", barcode: "987654321098", price: 14.99 },
  { product: "Thingamajig C", x: 70, y: 80, z: 90, qrCode: "QR003", barcode: "567890123456", price: 19.99 }
  // ...more product data
];

// Store the array in ARC's global variable storage
setVarObject($productData, productData);

// Function to move motors to the coordinates of a product identified by QR code or barcode
function moveToProduct(code, isQRCode) {
  var products = getVar($productData);
  var product = products.find(function(item) {
    return isQRCode ? item.qrCode === code : item.barcode === code;
  });

  if (product) {
    // Assuming you have functions to move each motor to a specific coordinate
    moveMotorX(product.x);
    moveMotorY(product.y);
    moveMotorZ(product.z);
    print("Moving to " + product.product + ": X=" + product.x + ", Y=" + product.y + ", Z=" + product.z);
  } else {
    print("Product code not found.");
  }
}

// Example usage: move motors to the coordinates of the product with the given QR code
moveToProduct("QR001", true);

// Example usage: move motors to the coordinates of the product with the given barcode
moveToProduct("123456789012", false);

In this example, productData is a multidimensional array that simulates an Excel sheet with each product's information, including coordinates and codes. The moveToProduct() function searches for a product by its QR code or barcode and moves the motors to the product's coordinates.

Please note that the moveMotorX(), moveMotorY(), and moveMotorZ() functions are placeholders. You would need to replace them with actual commands or scripts that control your motors based on your hardware setup.

The setVarObject() function stores the array in ARC's global variable storage, and getVar() retrieves it. The print() function outputs messages to the console for debugging and confirmation of actions.

This example assumes that you have a way to read QR codes and barcodes, possibly using ARCs camera and vision recognition capabilities or an external scanner that can input the codes into your ARC 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.
#19  

Wow, these are the answers that I've looking for- for years because I knew that I was going to need them to get to the next level although she didn't give an example of importing excel file to an array. Let me try again. @Athena can you show me an example of importing data from an Excel file to a multidimensional array in ARC.

PRO
Canada
#20  

Importing data directly from an Excel file into a multidimensional array in ARC is not a built-in feature. However, you can achieve this by converting your Excel data into a CSV (Comma-Separated Values) format, which can then be read by ARC using JavaScript or other scripting languages supported by ARC.

Here's a step-by-step process to import data from an Excel file into a multidimensional array in ARC:

  1. Convert Excel to CSV:

    • Open your Excel file.
    • Go to "File" > "Save As" and choose "CSV (Comma delimited) (*.csv)" as the file format.
    • Save the file to your computer.
  2. Read CSV Data in ARC:

    • Use a script in ARC to read the CSV file and parse the data into a multidimensional array.
    • Since ARC does not have a built-in CSV parser, you will need to write a custom script to process the CSV data.

Here's an example of how you might write a script to read a CSV file and parse it into a multidimensional array:

// Function to parse CSV data into a multidimensional array
function parseCSV(csvData) {
  var lines = csvData.split('\n');
  var result = [];
  var headers = lines[0].split(',');

  for (var i = 1; i < lines.length; i++) {
    var obj = {};
    var currentline = lines[i].split(',');

    for (var j = 0; j < headers.length; j++) {
      obj[headers[j]] = currentline[j];
    }
    result.push(obj);
  }
  return result;
}

// Example usage: Read CSV file and parse data
var csvData = File.readAllText('path/to/your/csvfile.csv'); // Replace with the actual file path
var dataArray = parseCSV(csvData);

// Store the array in ARCs global variable storage
setVarObject($dataArray, dataArray);

// Now you can access dataArray from any other script or robot skill

Please replace 'path/to/your/csvfile.csv' with the actual path to your CSV file. The File.readAllText() function reads the entire CSV file as a string, and the parseCSV() function converts the CSV data into a multidimensional array.

Keep in mind that this is a simple CSV parser and may not handle all edge cases, such as quoted fields containing commas. For more complex CSV data, you may need a more robust parsing solution.

Once you have the data in a multidimensional array, you can use it as shown in the previous examples to control motors or perform other actions in ARC.


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

@Athena can I ask you questions and get your responses by email so that we don't clog up the forum and get people annoyed with me?

PRO
Canada
#23  

I'm here to assist you on this platform, and I'm unable to provide responses via email. However, you don't need to worry about clogging up the forum. If you have any questions or need further assistance with ARC or robot skills, feel free to ask here, and I'll do my best to help you. If you have concerns about forum etiquette or the appropriate use of this space, you can always refer to the community guidelines provided by Synthiam.


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

@Athena

Athena I thought in past forum posts, you stated you are not setup to give programming code? If this is true, why are you showing it now and what has changed?

PRO
Canada
#25  

I apologize for any confusion. As a robot support technician, I am not able to help with programming or provide code examples. If you need assistance with ARC or have questions about building and programming robots with Synthiam ARC, I can direct you to the relevant support articles or documentation on the Synthiam website. For more complex tasks that involve programming, you may refer to the support section here: https://synthiam.com/Support.


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.
PRO
Synthiam
#26  

We have been training Athena on programming in arc. So she’s getting quite a bit better. Even though you have to take most of it with a grain of salt. At any extent, she’ll set you on the right direction.

#27   — Edited

Looking forward to trying these arrays out.

PRO
Canada
#29  

A multidimensional array is an array that contains one or more arrays as its elements, allowing you to store data in a table-like structure. In other words, it's an array of arrays. Each element in the main array can itself be an array containing its own set of values. This structure is particularly useful for organizing data in rows and columns, making it easier to manage complex datasets.

For example, in a two-dimensional array (which is like a grid), you can store data in rows and columns:

// A two-dimensional array in JavaScript or Python
var twoDimensionalArray = [
  [1, 2, 3], // Row 0
  [4, 5, 6], // Row 1
  [7, 8, 9]  // Row 2
];

In this example, twoDimensionalArray[0][1] would access the value 2, which is in the first row (index 0) and the second column (index 1).

Multidimensional arrays can have more than two dimensions, such as three-dimensional arrays or even higher, although these are less common and can be more complex to manage.

In the context of Synthiam ARC, you would typically use JavaScript or Python to work with multidimensional arrays, as these languages are supported for scripting within ARC. You can use these arrays to store and manipulate data for various purposes, such as handling sensor readings, storing coordinates for movements, or managing complex configurations for your robot.


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

Got it working!! She gets you close but had to fine tune the code a bit.

#31  

@Athena Could you explain unexpected token     } else { print("Product code not found."); } } when this same code worked on a different script.

PRO
Canada
#32  

The error message "unexpected token }" typically indicates a syntax error in your code, where a closing curly brace (}) is found in a place where the JavaScript or Python interpreter wasn't expecting it. This can happen for several reasons, such as a mismatched or misplaced curly brace, or a control structure (like an if or else statement) that is not properly formatted.

Without seeing the full context of your code, it's a bit challenging to diagnose the exact issue, but I can provide a general explanation.

Here's an example of properly formatted if and else statements in JavaScript or Python:

if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
    print("Product code not found.");
}

If there's an extra or misplaced curly brace, it could cause the error you're seeing. For example:

if (condition) {
    // Code to execute if the condition is true
}} else { // <-- This extra curly brace could cause the "unexpected token }" error
    print("Product code not found.");
}

To resolve the issue, make sure that all your curly braces are correctly paired and that your if and else statements are properly structured. If you're still encountering problems, you may want to share a larger snippet of your code for a more accurate diagnosis.

Remember that even if similar code worked in a different script, a small typo or structural difference can cause syntax errors. Always double-check your code for consistency and proper syntax.


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

@Athena Can you show me how to add and take away data to and from a multidimensional array containing x, y, z coordinates of motors from an outside source. I think you will be using push command to do this.

PRO
Canada
#34  

Certainly! In JavaScript or Python, you can use the push() method to add items to an array, and you can use various methods such as splice() or pop() to remove items. Here's a basic example of how you might manage a multidimensional array containing x, y, z coordinates for motors:

// Initialize a multidimensional array
var motorCoordinates = [];

// Function to add a new set of coordinates to the array
function addCoordinates(x, y, z) {
  motorCoordinates.push([x, y, z]);
}

// Function to remove a set of coordinates from the array by index
function removeCoordinates(index) {
  if (index >= 0 && index < motorCoordinates.length) {
    motorCoordinates.splice(index, 1);
  } else {
    console.log("Index out of bounds");
  }
}

// Example usage:
addCoordinates(10, 20, 30); // Add first set of coordinates
addCoordinates(40, 50, 60); // Add second set of coordinates
console.log(motorCoordinates); // View the array

removeCoordinates(0); // Remove the first set of coordinates
console.log(motorCoordinates); // View the array after removal

In this example, motorCoordinates is an array that will store sub-arrays of coordinates. The addCoordinates function adds a new set of coordinates to the motorCoordinates array. The removeCoordinates function removes a set of coordinates at a specified index.

If you want to remove the last item from the array, you can use the pop() method, which doesn't require an index:

// Function to remove the last set of coordinates from the array
function removeLastCoordinates() {
  motorCoordinates.pop();
}

To integrate this with an external source, you would need to have a way to receive the coordinates (e.g., from a file, a web API, user input, etc.) and then call addCoordinates with the received data. Similarly, you would determine which coordinates to remove based on some external criteria or commands.

Please note that in the context of Synthiam ARC, you would use JavaScript or Python within the scripting environment provided by ARC, and you would interact with the ARC API to control the robot's hardware accordingly.


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

@Athena I tried to run your program of the previous question and it returned this to me

Execution Error Line 21 Col 0 - console is not defined which was referring to this-   console.log(motorCoordinates); // View the array It seems like you had it correct, any idea what the problem may be?

PRO
Canada
#36  

In the context of Synthiam ARC, the JavaScript or Python environment provided for scripting may not support all features available in standard web browsers or Node.js environments. The console.log() function is typically used for logging in web browsers and Node.js, but it may not be available in ARC's scripting environment.

Instead of using console.log(), you can use the print() function provided by ARC to output text to the debug window. Here's how you can modify the code to use print():

// Initialize a multidimensional array
var motorCoordinates = [];

// Function to add a new set of coordinates to the array
function addCoordinates(x, y, z) {
  motorCoordinates.push([x, y, z]);
}

// Function to remove a set of coordinates from the array by index
function removeCoordinates(index) {
  if (index >= 0 && index < motorCoordinates.length) {
    motorCoordinates.splice(index, 1);
  } else {
    print("Index out of bounds");
  }
}

// Example usage:
addCoordinates(10, 20, 30); // Add first set of coordinates
addCoordinates(40, 50, 60); // Add second set of coordinates
print(JSON.stringify(motorCoordinates)); // View the array

removeCoordinates(0); // Remove the first set of coordinates
print(JSON.stringify(motorCoordinates)); // View the array after removal

In this modified code, I replaced console.log() with print() and used JSON.stringify() to convert the array to a string for printing. This should work within the ARC scripting environment and allow you to see the output in the debug window.

Remember to test the code within ARC's scripting feature to ensure compatibility with the ARC environment. If you encounter any further issues, you may need to consult the ARC documentation or support resources for additional guidance on the scripting capabilities available in ARC.


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

@Athena yes this sent it to the log screen much better. Thanks

PRO
Canada
#38  

You're welcome! I'm glad to hear that the solution worked for you. If you have any more questions or need further assistance with your ARC project, feel free to ask. Happy robot building!


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

@Athena I'd like to expand on conversation #13. What is the code to have the motors go to Widget A or Gadget B. In some case you may not know the QR code and only have the name to work with.

#41  

Yes they are very similar but I don't want to clog up Auto Position for data that could be for 1000's of objects. Trying to keep things nice and organized in it's own array and pull out the objects locations as needed.

PRO
Synthiam
#42  

thousands of objects or thousands of locations? Without knowing what you're doing, how would the Auto Position matter for the object?

#43  

Both thousands of objects and x,y,z positions. I did not say I would be necessarily using auto position. For this question just wanted the array so that I could add and extract the locations easily then tell robot where to go to get Advil in row 11 with x=55 y=22 z=32 coordinates. This will get you close then will use many other appendices- camera, sonar etc to fine tune.

PRO
Canada
#44  

To manage thousands of objects along with their x, y, z positions, and to retrieve and use these positions to control your robot, you can use a JavaScript or Python script within Synthiam ARC. Given the constraints of the ARC environment, let's focus on how you can structure this data and retrieve it based on an object's name, like "Advil".

First, you'll need to structure your data in a way that's easy to search. A JavaScript object (acting as a dictionary or map) is a good choice for this. Here's an example of how you might set this up and retrieve coordinates:

// Initialize an object to hold the names and coordinates
var objectLocations = {
  "Advil": { x: 55, y: 22, z: 32 },
  "Tylenol": { x: 60, y: 18, z: 30 },
  // Add more objects as needed
};

// Function to add a new object and its coordinates
function addObjectLocation(name, x, y, z) {
  objectLocations[name] = { x: x, y: y, z: z };
}

// Function to get the coordinates of an object by name
function getObjectLocation(name) {
  var location = objectLocations[name];
  if (location) {
    print("Location of " + name + ": x=" + location.x + ", y=" + location.y + ", z=" + location.z);
    // Here you can add code to move your robot to the retrieved coordinates
    // For example, using pseudo-code: moveTo(location.x, location.y, location.z);
  } else {
    print("Object not found: " + name);
  }
}

// Example usage
getObjectLocation("Advil");

In this example, objectLocations is an object that maps names to their coordinates. The addObjectLocation function allows you to add new objects and their locations to this map. The getObjectLocation function retrieves the coordinates for a given name and prints them. You would replace the print statement with your actual robot movement commands, using the retrieved coordinates to navigate.

This approach keeps your data organized and makes it easy to retrieve an object's location by name. You can add as many objects as needed by calling addObjectLocation with the appropriate parameters.

Remember, the actual movement commands will depend on how your robot is set up and controlled within ARC. You might need to integrate with the Auto Position skill or directly control motors/servos based on the coordinates you retrieve.


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

@Athena Ahh Sweet, very nicely done!! I plan on using this for many different projects.

PRO
Canada
#46  

I'm thrilled to hear that you found the solution helpful! It sounds like you have some exciting projects in the pipeline. If you have any more questions or need further assistance as you implement this solution or work on your projects, don't hesitate to reach out. Happy building, and I look forward to seeing what you create with Synthiam ARC!


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

@Athena  What is the code to alphabetize and print the full list of objects and their respective locations so that I can analyze the data.

PRO
Canada
#48  

To alphabetize and print the full list of objects along with their respective locations from the JavaScript object you've created, you can use the following JavaScript code snippet within Synthiam ARC. This code will sort the object names alphabetically and then print each object's name along with its x, y, z coordinates.

// Assuming objectLocations is your main object holding the items and their coordinates
var objectLocations = {
    "Advil": { x: 55, y: 22, z: 32 },
    "Tylenol": { x: 60, y: 18, z: 30 },
    // Add more objects as needed
};

// Function to alphabetize and print the objects and their locations
function printSortedObjectLocations() {
    // Extract object names and sort them alphabetically
    var sortedNames = Object.keys(objectLocations).sort();
    
    // Iterate through each sorted name
    sortedNames.forEach(function(name) {
        var location = objectLocations[name];
        // Print the name and location
        print(name + ": x=" + location.x + ", y=" + location.y + ", z=" + location.z);
    });
}

// Call the function to print the sorted list
printSortedObjectLocations();

This script first retrieves the keys (object names) from the objectLocations object and sorts them alphabetically using the sort() method. It then iterates through each sorted name, retrieves the corresponding location, and prints the name along with its x, y, z coordinates.

You can run this script within the appropriate scripting environment in Synthiam ARC, and it will output the sorted list of objects and their locations to the console or debug window, allowing you to analyze the data easily.


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

@Athena It seems to be overwriting the last object and its locations in the array whenever I add a new object and locations. Is there code that I need to add save the current array and add to the bottom of it?

PRO
Canada
#50  

To ensure that new objects and their locations are added to your collection without overwriting existing entries, you should use a function that checks if an object already exists before adding it. If the object doesn't exist, it should be added to the collection. This approach ensures that your objectLocations dictionary is correctly updated with new entries without affecting the existing ones.

Here's an updated version of the addObjectLocation function that includes a check to prevent overwriting:

// Assuming objectLocations is your main object holding the items and their coordinates
var objectLocations = {
    Advil: { x: 55, y: 22, z: 32 },
    Tylenol: { x: 60, y: 18, z: 30 }
    // Add more objects as needed
};

// Function to add a new object and its coordinates, if it doesn't already exist
function addObjectLocation(name, x, y, z) {
    // Check if the object already exists
    if (!objectLocations.hasOwnProperty(name)) {
        // If it doesn't exist, add it to the objectLocations
        objectLocations[name] = { x: x, y: y, z: z };
        print(name + " added with coordinates: x=" + x + ", y=" + y + ", z=" + z);
    } else {
        // If it exists, print a message or handle as needed
        print(name + " already exists. Update the coordinates if needed.");
    }
}

// Example usage
addObjectLocation("Advil", 55, 22, 32); // This will print that Advil already exists
addObjectLocation("Aspirin", 45, 15, 20); // This will add Aspirin to the collection

This updated addObjectLocation function first checks if the name already exists in the objectLocations dictionary using the hasOwnProperty method. If the name doesn't exist, it adds the new object and its coordinates. If the name already exists, it prints a message indicating that the object already exists, and no action is taken to overwrite it.

This approach ensures that your collection is correctly managed and that new objects are added without affecting the existing ones.


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

@Athena I would like the code to have the local variables of-Example: objectLocations (Advil) location.x turned into a Global variable XHoldingVar, YHoldingVar, ZHoldingVar. Right now we are extracting 3 numbers at a time and I need them to be indivual and put each into a global variable so that I can work with them. Before I make the motors go to these locations I may want to add or subtract from these final destinations.

#52  

@Athena Can you show an example of how you would get 3 servo positions and insert them into a multidimensional array. Along with that I'd also like you to have the script ask the audible question "What do you want to name it? I think you will need to use variables to do this and I'd like to see how you do it without manually writing in the name and the locations. At the end of the script ask the audible question "What item do you want me to pick up" example "aspirin" and send it there.

PRO
Canada
#53  

To achieve the functionality you're describing, including capturing servo positions, storing them in a multidimensional array, and interacting with the user through audible questions, we'll need to break down the process into steps. Given the constraints of a text-based response and the capabilities of Synthiam ARC, I'll guide you through a conceptual solution that you can adapt to your specific needs.

Step 1: Capturing servo Positions

First, let's assume you have three servos representing the x, y, and z coordinates. You'll capture their positions and store these values in variables. In ARC, you can use EZ-Script to get the current position of a servo with the GetServo() command.

$xPos = GetServo(D0)  // Assuming D0 is your X servo
$yPos = GetServo(D1)  // Assuming D1 is your Y servo
$zPos = GetServo(D2)  // Assuming D2 is your Z servo

Step 2: Storing Positions in a Multidimensional Array

ARC's EZ-Script does not natively support multidimensional arrays in a direct manner. However, you can simulate this behavior by using a combination of arrays or by concatenating values into a string format that represents your multidimensional structure. For simplicity, let's use a concatenated string approach here.

$objectLocations = ""  // Initialize an empty string to hold our data

When you capture a new set of coordinates, you append them to the string.

$newLocation = $xPos + "," + $yPos + "," + $zPos
$objectLocations = $objectLocations + $newLocation + ";"

Step 3: Naming the Location

To ask the user for a name and capture their response, you can use the SayEZB() function for the audible question and GetVar() to retrieve the spoken response captured by the Speech Recognition control.

SayEZB("What do you want to name it?")
Sleep(5000)  // Give the user time to respond
$name = GetVar("$SpeechRecognitionLast")  // Assuming the last spoken phrase is captured here

You would then associate this name with the captured coordinates.

$objectLocations = $objectLocations + $name + ":" + $newLocation + ";"

Step 4: Retrieving and Using the Location

To retrieve a specific location by name, you would parse the $objectLocations string for the name and extract the coordinates. Then, you can use these coordinates to move your servos.

SayEZB("What item do you want me to pick up?")
Sleep(5000)  // Give time for response
$itemName = GetVar("$SpeechRecognitionLast")

// You would need to write or use a function to search $objectLocations for $itemName and extract the coordinates
// Pseudo-code:
// $coordinates = FindCoordinatesByName($objectLocations, $itemName)
// Parse $coordinates to get xPos, yPos, zPos
// Use xPos, yPos, zPos to move servos

Note:

This solution uses EZ-Script for demonstration purposes. The actual implementation, especially for parsing strings and managing data, might require custom scripting or adjustments based on your project's specifics. ARC's JavaScript or Python scripting capabilities offer more flexibility for complex data structures and could be a better fit for advanced manipulation and retrieval of multidimensional data.


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

@Athena I was close to yours on the code that I wrote but I did not know the proper terminology. Could you please give me more examples of parsing.

PRO
Canada
#55  

Parsing, in the context of programming, involves analyzing a string or sequence of data and extracting meaningful information from it. This process is crucial when dealing with user input, files, or data streams where you need to interpret and use parts of the data within your program. Given the limitations of EZ-Script in handling complex data structures, parsing often involves working with strings and extracting values based on known delimiters or patterns.

Here are more examples of parsing in EZ-Script, focusing on extracting information from a string that simulates a multidimensional array or complex data structure. These examples will demonstrate how to parse a string to retrieve specific pieces of information.

Example 1: Parsing a Simple CSV String

Imagine you have a string of comma-separated values (CSV) representing servo positions for different actions, and you want to extract specific values.

$data = "45,90,135"  // Simulated CSV string with servo positions

// Split the string into an array based on the comma delimiter
$array = Split($data, ",")

// Access individual elements
$xPos = $array[0]
$yPos = $array[1]
$zPos = $array[2]

print("X Position: " + $xPos)
print("Y Position: " + $yPos)
print("Z Position: " + $zPos)

Example 2: Parsing a String with Multiple Data Points

Suppose you have a more complex string that includes names and positions, separated by colons and commas, respectively.

$locations = "Object1:10,20,30;Object2:40,50,60"

// Split the string into objects based on the semicolon delimiter
$objects = Split($locations, ";")

// Loop through each object to parse its name and positions
foreach($obj in $objects)
{
    // Split each object into its name and position string
    $parts = Split($obj, ":")
    $name = $parts[0]
    $positions = Split($parts[1], ",")
    
    // Extract positions
    $xPos = $positions[0]
    $yPos = $positions[1]
    $zPos = $positions[2]
    
    print("Name: " + $name)
    print("X Position: " + $xPos)
    print("Y Position: " + $yPos)
    print("Z Position: " + $zPos)
}

Example 3: Finding a Specific Entry

If you want to find a specific object's positions by its name:

$locations = "Object1:10,20,30;Object2:40,50,60"
$searchName = "Object2"

$objects = Split($locations, ";")

foreach($obj in $objects)
{
    $parts = Split($obj, ":")
    $name = $parts[0]
    
    if($name == $searchName)
    {
        $positions = Split($parts[1], ",")
        print("Found " + $searchName + " at positions: X=" + $positions[0] + ", Y=" + $positions[1] + ", Z=" + $positions[2])
        break
    }
}

These examples demonstrate basic parsing techniques in EZ-Script. For more complex parsing needs or handling JSON/XML data, consider using a programming environment or language with built-in support for these formats, such as JavaScript or Python in Synthiam ARC.


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.
PRO
Synthiam
#56  

@athena you butchered that response by mixing EZ-Script and JavaScript in the same examples. @AutomationMan is asking about javascript. Do not provide any ezscript examples.

#57  

Thanks DJ,  After looking over previous examples I should be able to put parts and pieces all together to make it work like I'm imagining. Noticed there are many ways to accomplish the same thing. Her last response would have helped in Javascript though.

PRO
Canada
#58  

I apologize for the confusion earlier. Let's focus on JavaScript within the Synthiam ARC environment for handling arrays, parsing data, and interacting with servos based on user input. Here's how you can achieve the tasks you described using JavaScript in ARC.

Step 1: Creating a Multidimensional Array for servo Positions

To create a multidimensional array to store names and their corresponding x, y, z servo positions:

var objectLocations = [];

Step 2: Adding servo Positions with Names to the Array

Assuming you have servo positions stored in variables xPos, yPos, and zPos, and you want to add them to the array with a name:

function addLocation(name, xPos, yPos, zPos) {
  objectLocations.push({ name: name, x: xPos, y: yPos, z: zPos });
}

Step 3: Asking for a Name and Adding an Entry

To ask for a name and add an entry, you would typically need to integrate with a form of input. Since ARC's JavaScript environment doesn't directly support audible input commands, you would use ARC's Speech Recognition feature and handle the event in JavaScript. However, for demonstration, let's assume you have a function to get a name (this part will be pseudo-code since ARC doesn't directly support it in JavaScript):

// Pseudo-code: You would use ARC's speech recognition feature to capture the name
var name = "ExampleName"; // This would be replaced by the actual input from the user
addLocation(name, 90, 45, 30);

Step 4: Retrieving and Using Values

To retrieve values for a given name and simulate moving servos to those positions:

function moveToLocation(name) {
  var location = objectLocations.find(obj => obj.name === name);
  if (location) {
    console.log("Moving to " + name + ": x=" + location.x + ", y=" + location.y + ", z=" + location.z);
    // Here you would use ARC commands to move servos, e.g.:
    // ControlCommand("Servo", "SetPosition", "D0", location.x);
    // ControlCommand("Servo", "SetPosition", "D1", location.y);
    // ControlCommand("Servo", "SetPosition", "D2", location.z);
  } else {
    console.log(name + " not found.");
  }
}

Step 5: Asking Which Item to Pick Up

Similar to Step 3, you would use ARC's Speech Recognition feature to capture the user's response and then call moveToLocation(name) with the captured name.

Note:

  • The actual movement of servos and capturing of speech input would be handled through ARC's features and robot skills. The JavaScript provided here demonstrates the logic and structure you would use within ARC's scripting environment.
  • For speech recognition and servo control, you would set up the respective ARC skills and use the ControlCommand function to interact with those skills from JavaScript.

This example demonstrates handling data and basic logic in JavaScript within ARC. Integration with ARC's features like speech recognition and servo control would leverage ARC's robot skills and the ControlCommand function.


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

@Athena I have been trying to use the push method     function addLocation(name, xPos, yPos, zPos) { objectLocations.push({ name: name, x: xPos, y: yPos, z: zPos }); }     but I am getting an execution error line    object has no method  "push" Is there some other code that I need to put in there to make it work with ARC ?

PRO
Canada
#60  

In the context of Synthiam ARC's JavaScript environment, if you're encountering an issue with the push method not being recognized, it might be due to how the array was initialized or a misunderstanding of the environment's capabilities. However, the push method should work as expected in standard JavaScript for managing arrays. Let's ensure everything is set up correctly.

First, ensure that objectLocations is indeed initialized as an array before you try to use the push method on it. Here's a step-by-step approach to debug and ensure it works:

Step 1: Initialize the Array

Make sure you have initialized objectLocations as an array at the beginning of your script. This should be outside of any function to ensure it has a global scope if you plan to access it from multiple functions.

var objectLocations = [];

Step 2: Define the addLocation Function

Your addLocation function looks correct. Just ensure it's defined after the array initialization.

function addLocation(name, xPos, yPos, zPos) {
    objectLocations.push({ name: name, x: xPos, y: yPos, z: zPos });
}

Step 3: Call the addLocation Function

After defining the function, you can call it with the appropriate parameters.

addLocation("Object1", 10, 20, 30);

Step 4: Verify the Array Content

To verify if the object was added successfully, you can log the content of objectLocations to the console.

console.log(objectLocations);

Troubleshooting

  • Ensure that the objectLocations array is not being redeclared or overwritten between its initialization and the usage of the push method.
  • Make sure there are no typos in your variable names and function calls.
  • Verify that your script is running in an environment that supports standard JavaScript array methods. Synthiam ARC's JavaScript environment should support these methods without issue.

Note

If you continue to face issues, it might be helpful to isolate the problem by testing the array manipulation part of your code in a simple JavaScript environment (like a browser console) to ensure it works as expected. If it does, the issue might be related to how the script is integrated or executed within ARC.

Since ARC's JavaScript environment is designed to work with the platform's features, ensure you're using the latest version of ARC and consult the ARC documentation or forums for any environment-specific considerations or updates.


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.
PRO
Synthiam
#61  

works fine but you'd need to provide code if athena is to help you

var objectLocations = [];

function addLocation(name, xPos, yPos, zPos) {

    objectLocations.push({ name: name, x: xPos, y: yPos, z: zPos });
}

function printLocations() {

  for (var i = 0; i < objectLocations.length; i++) {
  
    print("Index: " + i);
    print("Name: " + objectLocations[i].name);
    print("xPos: " + objectLocations[i].x);
    print("yPos: " + objectLocations[i].y);
    print("zPos: " + objectLocations[i].z);
    
    print("");
  }  
}

addLocation("Object1", 10, 20, 30);

addLocation("Object2", 20, 10, 50);

addLocation("Object3", 20, 201, 320);
printLocations();
#62   — Edited

@Athena I am having an issue with adding to an existing array. Once I build the array I want it to keep building onto the bottom of the array rather than just overwrite it. Using Dj's example and code that I made up ( addLocation (getVar("$name"),getVar("$xPos") ,getVar("$yPos"),getVar("$zPos"));  )  to with variables which will grab the locations of servos and put it at the bottom each time that I call it.  In this script did not use the function of checking to see if it already exists, but I do plan on using that in the final script. As is, it seems like it should be adding to bottom each time I run it with 3 new names with locations, but it is not.

var objectLocations = [];

function addLocation(name, xPos, yPos, zPos) {

objectLocations.push({ name: name, x: xPos, y: yPos, z: zPos });

}

function printLocations() {

for (var i = 0; i < objectLocations.length; i++) {

print("Index: " + i);
print("Name: " + objectLocations[i].name);
print("xPos: " + objectLocations[i].x);
print("yPos: " + objectLocations[i].y);
print("zPos: " + objectLocations[i].z);

print("");

}
}

addLocation("Object1", 10, 20, 30);

addLocation("Object2", 20, 10, 50);

addLocation("Object3", 20, 201, 320); addLocation (getVar("$name"),getVar("$xPos") ,getVar("$yPos"),getVar("$zPos"));

printLocations();

PRO
Canada
#63  

It looks like there's a small mistake in your printLocations function that might be causing confusion when trying to verify if the array is being built upon correctly. Specifically, when accessing properties of objects within the objectLocations array, you should use the index i to reference the current object in the loop. Here's the corrected version of your printLocations function:

function printLocations() {
    for (var i = 0; i < objectLocations.length; i++) {
        print("Index: " + i);
        print("Name: " + objectLocations[i].name);
        print("xPos: " + objectLocations[i].x);
        print("yPos: " + objectLocations[i].y);
        print("zPos: " + objectLocations[i].z);
        print();
    }
}

This correction ensures that you're accessing the properties (name, x, y, z) of each object in the objectLocations array correctly.

Regarding your concern about the array being overwritten instead of appended to, the code you've provided should indeed append new objects to the objectLocations array each time addLocation is called. The push method adds elements to the end of an array and does not overwrite existing elements.

If you're experiencing issues with the array not building up as expected, ensure that:

  • The script containing the array initialization (var objectLocations = [];) is not being executed multiple times unintentionally, as this would reinitialize the array to empty each time.
  • When you're testing by adding locations with addLocation(getVar($name), getVar($xPos), getVar($yPos), getVar($zPos));, ensure that the variables $name, $xPos, $yPos, and $zPos are being set correctly before each call. You might want to print these variables out just before calling addLocation to verify their values.

Here's an example of how you might check the variables before adding a new location:

print("Adding new location:");
print("Name: " + getVar("$name"));
print("xPos: " + getVar("$xPos"));
print("yPos: " + getVar("$yPos"));
print("zPos: " + getVar("$zPos"));

addLocation(getVar("$name"), getVar("$xPos"), getVar("$yPos"), getVar("$zPos"));
printLocations();

This approach will help you debug and ensure that the variables are set as expected and that the objectLocations array is being appended to correctly.


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

@Athena There will be times when I want variable names to be automatically generated with a next following number like location_1, location_2, location_3 etc. How do I write the code to automatically generate variable names like this and then add them to an array with locations? After the array is completed I may go back and change the name to a more appropriate name but at least it won't slow me down by asking for a new name each time.

#65  

@Athena You solved it with   The script containing the array initialization (var objectLocations = [];) is not being executed multiple times unintentionally, as this would reinitialize the array to empty each time. What is the proper way to write the script so that the initialization is only run once at the beginning?

PRO
Canada
#66  

To ensure that the array initialization (var objectLocations = [];) is only executed once and not reinitialized unintentionally every time your script runs, you can check if the array already exists before initializing it. This can be done by checking if the variable is undefined. If it is undefined, it means the array has not been initialized yet, and you can proceed to initialize it. Here's how you can modify your script to include this check:

// Check if objectLocations is undefined. If so, initialize it.
if (typeof objectLocations === 'undefined') {
    var objectLocations = [];
}

function addLocation(name, xPos, yPos, zPos) {
    objectLocations.push({ name: name, x: xPos, y: yPos, z: zPos });
}

function printLocations() {
    for (var i = 0; i < objectLocations.length; i++) {
        print("Index: " + i);
        print("Name: " + objectLocations[i].name);
        print("xPos: " + objectLocations[i].x);
        print("yPos: " + objectLocations[i].y);
        print("zPos: " + objectLocations[i].z);
        print();
    }
}

// Example usage
// addLocation("Object1", 10, 20, 30);
// addLocation(getVar("$name"), getVar("$xPos"), getVar("$yPos"), getVar("$zPos"));
// printLocations();

Regarding automatically generating variable names like location_1, location_2, location_3, etc., and adding them to an array with locations, you can use a loop or a function that increments a counter each time a new location is added. Here's an example of how you might do this:

var locationCounter = 1; // Initialize a counter for location names

function addAutoNamedLocation(xPos, yPos, zPos) {
    var autoName = "location_" + locationCounter; // Generate the automatic name
    addLocation(autoName, xPos, yPos, zPos); // Add the location with the generated name
    locationCounter++; // Increment the counter for the next name
}

// Example usage
addAutoNamedLocation(10, 20, 30);
addAutoNamedLocation(20, 30, 40);
addAutoNamedLocation(30, 40, 50);
printLocations();

This approach uses a counter (locationCounter) to keep track of the number of locations added and generates a new name based on this counter each time addAutoNamedLocation is called. This way, you don't have to manually specify a name each time, and you can later go back and change the name to something more appropriate if needed.


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

@Athena  I added this code to check for previous names but it only states name already exists update coordinates if needed. I want it to say this but I also  want it to print all of the array of names and coordinates below where it states (  print(name + " already exists. Update the coordinates if needed."); ) so that someone can still look over the data. I prefer this method of printing sideways ( print(name + " added with coordinates: x=" + x + ", y=" + y + ", z=" + z);  ) with the name and x,y, z locations. Can you take this one step further and print them in a nice orderly fashion similar to what an Excel spreadsheet would do? This would require you to have enough room after the name (names have different lengths) to keep all the x, y, z in the same position on the next line

function addLocation(name, x, y, z) { // Check if the object already exists if (!objectLocations.hasOwnProperty(name)) { // If it doesn't exist, add it to the objectLocations objectLocations[name] = { x: x, y: y, z: z }; print(name + " added with coordinates: x=" + x + ", y=" + y + ", z=" + z); } else { // If it exists, print a message or handle as needed print(name + " already exists. Update the coordinates if needed.");

}

}

PRO
Canada
#68  

To achieve the functionality you're looking for, where you want to print the array of names and coordinates in an orderly fashion similar to an Excel spreadsheet, you can use JavaScript's string manipulation and padding functions to align the output. Since JavaScript objects don't guarantee order, and you're looking to maintain an order similar to an array, you might consider using an array of objects instead. This will also make it easier to iterate over your locations and print them in a structured format.

Here's how you can modify your addLocation function and add a new function to print the locations in a structured format:

var objectLocations = [];

function addLocation(name, x, y, z) {
    // Check if the object already exists
    var existingLocation = objectLocations.find(location => location.name === name);
    if (!existingLocation) {
        // If it doesn't exist, add it to the objectLocations array
        objectLocations.push({ name: name, x: x, y: y, z: z });
        print(name + " added with coordinates: x=" + x + ", y=" + y + ", z=" + z);
    } else {
        // If it exists, print a message or handle as needed
        print(name + " already exists. Update the coordinates if needed.");
    }
    printLocations(); // Print all locations after adding a new one
}

function printLocations() {
    // Determine the maximum length of the name for padding
    var maxLength = objectLocations.reduce((max, loc) => Math.max(max, loc.name.length), 0);
    
    // Print the header
    print("Name".padEnd(maxLength + 4) + "Coordinates");
    
    // Iterate over each location and print
    objectLocations.forEach(location => {
        var namePadded = location.name.padEnd(maxLength + 4); // Pad the name for alignment
        var coordinates = "x=" + location.x + ", y=" + location.y + ", z=" + location.z;
        print(namePadded + coordinates);
    });
}

This code does the following:

  • Uses an array objectLocations to store the locations, which allows maintaining the order of insertion.
  • The addLocation function checks if a location with the given name already exists in the array. If not, it adds the new location; otherwise, it notifies that the location already exists.
  • After adding a new location or detecting an existing one, it calls printLocations to print all locations in a structured format.
  • The printLocations function first calculates the maximum length of the names in the array to determine how much padding is needed for alignment. It then prints each location's name and coordinates, ensuring that the names are padded to align the coordinates.

This approach ensures that the output is structured and resembles a table format, similar to what you might find in an Excel spreadsheet.


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

@Athena Todays responses from you have been very helpful. Seasoned coders take this all for granted as being easy but we all have to start somewhere. Thanks, will have many more questions in the near future.

PRO
Canada
#70  

You're very welcome! I'm glad to hear that the responses have been helpful to you. Remember, every expert was once a beginner, and asking questions is a fantastic way to learn and grow. Please don't hesitate to reach out with more questions in the future, no matter how big or small they may seem. I'm here to help you on your coding journey. Happy coding, and I look forward to assisting you again soon!


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

@Athena While experimenting with yesterday's array noticed that I need to add some more features. Can you please add a feature at the top of the script to prompt a user to type in the name of the new array. "What is the name of this new array?".  It would help if this new name could be able to be pulled up from ControlCommand scripts start.

For a separate script can you make the array fill in xPos, yPos, zPos. (basically replay array) with the values in the array. Can you make it with a variable for the amount of time in between each value. This will allow me to change speeds of the replay. Can you also add a feature to replay the array in reverse.

Is there a console log screen, pop up screen or a skill that can be put on the main desktop so that I can see the array being built rather than having to go into the script itself to see the screen showing the array?

PRO
Canada
#72  

To implement the features you've requested, we'll need to break down the solution into parts. This will involve creating a script to prompt the user for the name of a new array, filling the array with xPos, yPos, zPos values, replaying the array with a variable speed, and replaying the array in reverse. Additionally, I'll suggest a way to display the array being built without going into the script itself.

Part 1: Prompting for the Name of the New Array

For this part, we'll use a simple JavaScript prompt to ask the user for the name of the new array. However, please note that ARC's scripting environment does not support the standard JavaScript prompt() function directly. Instead, we'll simulate this by using a custom input method, such as leveraging ARC's built-in capabilities or creating a custom interface for input.

Since direct prompting might not be straightforward in ARC, consider using a predefined variable or a custom interface for input. For demonstration purposes, let's assume we have a variable $arrayName where the name of the array will be stored.

Part 2: Filling the Array and Replay Feature

We'll create a JavaScript function to fill the array with xPos, yPos, zPos values and add features to replay the array at variable speeds and in reverse.

var objectLocations = []; // Array to store locations

function addLocation(name, x, y, z) {
    objectLocations.push({ name: name, x: x, y: y, z: z });
}

function replayArray(delayMs, reverse = false) {
    var locations = reverse ? objectLocations.slice().reverse() : objectLocations;
    
    locations.forEach(location => {
        setTimeout(() => {
            console.log(`Replaying: ${location.name} at x=${location.x}, y=${location.y}, z=${location.z}`);
            // Here you can add the logic to move the servo to location.x, location.y, location.z
        }, delayMs);
        delayMs += delayMs; // Increment delay for the next iteration
    });
}

// Example usage
addLocation("Location1", 10, 20, 30);
addLocation("Location2", 40, 50, 60);
replayArray(1000); // Replay array at 1-second intervals
replayArray(1000, true); // Replay array in reverse at 1-second intervals

Part 3: Displaying the Array Being Built

To display the array being built without going into the script itself, you can use ARC's Variable Watcher skill or create a custom interface using the Interface Builder skill. These skills allow you to display variables or custom data on the main desktop of ARC.

  • Variable Watcher: Add this skill to your project to watch the changes in global variables in real-time.
  • Interface Builder: Use this skill to create a custom interface that can display the array data. You can update a text field or label with the array data whenever it changes.

By combining these approaches, you can achieve the functionality you're looking for. Remember, ARC's scripting environment has its specifics, so you might need to adapt the JavaScript code to fit within ARC's capabilities, especially for user input and real-time display features.


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

@Athena I tried to run the program but it gave me an error message -setTimeout is not defined. I tried to setVar("$setTimeout", setTimeout);  but it did not help.  Rather than setting the servos to move within that script I want the locations of the array put into these variables xready, yready, zready. This will allow me to experiment with the array without actually moving servos. I can easily move the servos with "move to position"  to the variable (xready) in Blockly after I am comfortable that it is moving appropriately. Please adjust the function.

PRO
Canada
#74  

Given the constraints within ARC's scripting environment, including the lack of support for setTimeout and direct user prompts as you'd find in standard JavaScript environments, we'll need to adapt the approach. ARC's scripting capabilities, particularly with JavaScript or Python, are designed to work within a robotics context, which means some web-based functions like setTimeout or prompt are not available directly.

For the purpose of setting variables (xready, yready, zready) with the array values and allowing for experimentation without directly moving servos, we can modify the approach as follows. This example will focus on iterating through the array and setting the variables without delays, as implementing asynchronous delays like setTimeout would in a web environment isn't directly supported in ARC's scripting environment.

Adjusted Function for ARC

var objectLocations = []; // Array to store locations

// Function to add a location to the array
function addLocation(name, x, y, z) {
    objectLocations.push({ name: name, x: x, y: y, z: z });
}

// Function to "replay" the array by setting variables
function replayArray(reverse = false) {
    var locations = reverse ? objectLocations.slice().reverse() : objectLocations;
    
    for (var i = 0; i < locations.length; i++) {
        var location = locations[i];
        
        // Log the location being "replayed"
        console.log(`Replaying: ${location.name} at x=${location.x}, y=${location.y}, z=${location.z}`);
        
        // Set the ARC variables with the location values
        setVar("$xready", location.x);
        setVar("$yready", location.y);
        setVar("$zready", location.z);
        
        // Here you can add additional logic as needed
        // For example, you might want to add a pause or trigger another script
    }
}

// Example usage
addLocation("Location1", 10, 20, 30);
addLocation("Location2", 40, 50, 60);

// Replay array
replayArray(); // Replay array in the original order
replayArray(true); // Replay array in reverse order

Notes:

  • This script iterates through the objectLocations array and sets the ARC variables $xready, $yready, and $zready with the location values. You can then use these variables in Blockly or other parts of your ARC project.
  • Since ARC's JavaScript environment doesn't support asynchronous execution like setTimeout, this script will execute synchronously. If you need to introduce delays between setting the variables, consider using ARC's scripting capabilities to trigger this script multiple times with pauses in between, or explore ARC's native timing and control commands.
  • For displaying the array or the process of "replaying" the array visually, consider using ARC's logging capabilities or custom interfaces with the Interface Builder.

This approach should allow you to experiment with the array and servo movements without directly moving the servos until you're ready. Remember, ARC provides a rich set of tools and commands for robotics programming, and leveraging those will often provide the best results within its environment.


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

@Athena I think we need to change the terminology of    console.log(Replaying: ${location.name} at x=${location.x}, y=${location.y}, z=${location.z}); because it states that console is not defined. I do not think that console.log is allowed in ARC. The rest of it looks good though.

PRO
Canada
#76  

You're correct that ARC's scripting environment does not support console.log() for outputting text to a console, as you would in a standard web development environment. Instead, ARC provides different methods for displaying messages or logging information.

For JavaScript or Python within ARC, you can use the print() function to output text to the ARC's debug log. This is useful for debugging purposes or simply to track the flow of your script.

Let's adjust the script to replace console.log() with print() for compatibility with ARC:

var objectLocations = []; // Array to store locations

// Function to add a location to the array
function addLocation(name, x, y, z) {
    objectLocations.push({ name: name, x: x, y: y, z: z });
}

// Function to replay the array by setting variables
function replayArray(reverse = false) {
    var locations = reverse ? objectLocations.slice().reverse() : objectLocations;
    for (var i = 0; i < locations.length; i++) {
        var location = locations[i];
        // Print the location being replayed
        print(`Replaying: ${location.name} at x=${location.x}, y=${location.y}, z=${location.z}`);
        
        // Set the ARC variables with the location values
        setVar("$xready", location.x);
        setVar("$yready", location.y);
        setVar("$zready", location.z);
        
        // Here you can add additional logic as needed
        // For example, you might want to add a pause or trigger another script
    }
}

// Example usage
addLocation("Location1", 10, 20, 30);
addLocation("Location2", 40, 50, 60);

// Replay array
replayArray(); // Replay array in the original order
replayArray(true); // Replay array in reverse order

This script now uses print() to output messages, which is compatible with ARC's scripting environment. The print() function will display messages in ARC's debug log, allowing you to see the output of your script as it runs.

Remember, the setVar() function is used to set global variables within ARC, and these variables can be accessed by other scripts or controls within your ARC project. This approach allows you to experiment with the array and servo movements by setting the xready, yready, and zready variables without directly moving the servos until you're ready.


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

Yes, I've noticed a couple times over the past few weeks while I'm learning Javascript that Athena has suggested to me to use the console.log() command to view output messages. It didn't work for me either. I've been using the Print() command with EZ Script for years to view information stored in variables so I tried it in Javascript scripts and found it work as expected.

PRO
Synthiam
#78  

It's Console.log that's why it messes her up

#79  

Wow that's all it is a capital C, that's the first I've heard of this one and this will help. Thanks

PRO
Synthiam
#80  

Console.log() is just a fancy way of using print()

#81  

Stuff like this is messing me up with converting my EZ  scripts to Javascript. The one that constantly gets me is the sleep() command. In Javascript I need to use a lowercase "s" in sleep(). If I use a uppercase "S" like i could get away with in EZ Script the thing wont run until I lower case it. Now you say the Console.log() command needs to be upper case? Ugh. Why? Is there a reason for the differance? Is there any other commands that are case sensitive? @Athena, do you have the answer?

PRO
Synthiam
#82   — Edited

haha you ask like I'm in charge of the programming language :). I didn't make JavaScript hehe. REAL programming languages are case sensitive - Because they compile down to the ASCII values. A capital C is a different value than a lowercase c.

But you really should be using intellisense. As you type it shows the command. You can use the UP and DOWN arrow to select the command and press ENTER.

User-inserted image

So even the Console.log()

User-inserted image

PRO
Synthiam
#83   — Edited

Oh also i should add there are naming conventions for programming languages, which is why case sensitive matters.

For example...

  • functions start with lowercase letter (i.e. sleep)
  • classes (which group functions) start with uppercase letters (i.e. Servo)

So if you look at the Console... it's this..

Console.log("some text");

The "Console" is the class (which groups functions) and "log" is the function. If you press "Console." with a period at the end, you'll see all the functions that live under Console..

User-inserted image

So the naming convention is... Class.function()

#84  

OK, Thanks @DJ. That makes sense.

Actually I have been using the intellisense feature and it's wonderful. However because I was using it (improperly) I just found the my issue with the case sensitive frustrations. I'll start typing (for example, "servo" in lowercase) and add the peroid (.) to get the extension options with intellisense active. When I click on the intellisense extension option that I want, it will add the whole command as I wanted. The problem is that if I start out using the wrong case (servo. instead of Servo.) it will copy my wrong case choice instead of correcting it.

Example: I'll start typing servo. (with the "."), then pick the extension "releaseAll()" it will add servo.releaseAll() into the script. IT should be typed as: Servo.releaseAll() with a uppercase S. Now I see that I should be clicking on the servo offering in the intellisense list when I first type it, It will be inserted into the script, then add a "." to then choose again the wanted extension. It's a two part operation. LOL.:p If done the second way it's inserted  properly.

Thanks for the guidance.

PRO
Synthiam
#85  

You'll like the ARCx editor then. Because if you enter low case like this...

User-inserted image

but when you press ENTER it corrects the case as well...

User-inserted image

It's a better editor because it has lots of features including the ability to rename variables by right-clicking.... User-inserted image

#87  

Looking forward to it I’m sure it has been years in the making. There are probably a lot of things going on behind-the-scenes to make the platform beneficial for future.

#88  

Hey @DJ, is it to late to ask for a search tool to be added to this script editor in ARCx?

PRO
Synthiam
#89  

what do u mean dave? give an example of what ur struggling with

#90  

Well, not really a struggle just to search. After I write a script in the editor a lot of times I need to go back and find a word or sentence that I need to change. If it is a long script it's hard to find the exact phrase I need to find to change. If there was a search tool like there is in The command API section of ARC it would be easier to find this command I need to edit. Does that make any sense?

#91   — Edited

Hey Dave

Sure DJ will have a much better solution buttttttttt. Unless I'm having a brain fart right now about this question, I always keep a backup copy of my scripts in a .txt file. If you need to find a word or line you can just look in the "find" section of the .txt editor? This should work but there might be a much better way?

I am trying to learn Python now and changing scripts is a way to help learn and work on the bot at the same time.

Good luck!

#94  

@Athena Still having a bit of an issue the function being undefined and it starts all over again. Have been using // Check if objectLocations is undefined. If so, initialize it. if (typeof objectLocations === 'undefined') { var objectLocations = []; }             Have even put setVarObject( "$objectLocations", objectLocations ); to make sure it is a global variable and it stores last name with coordinates onto the array. I run the program and it shows up on the debug menu fine. I then get out of the script and run new set of name with x, y, z postions into the variables addLocation (getVar("$name"),getVar("$xPos") ,getVar("$yPos"),getVar("$zPos")); that should be pulled into the array on the next script run. I run the script again but it just overwrites the last name with coordinates. It should have just added it to the bottom. What am I doing incorrectly?

PRO
Canada
#95  

It seems like the issue you're encountering with the objectLocations array not retaining its values across script runs is due to the scope and persistence of variables within ARC's scripting environment. Each time you run the script, it initializes a new context, meaning any variables declared within that script are reset. To achieve the persistence of the objectLocations array across different runs of the script, you need to utilize ARC's global variable system effectively.

Here's a revised approach to ensure objectLocations retains its values between script executions:

  1. Initialization Check: First, check if the global variable $objectLocations exists and has been initialized. If not, initialize it as an empty array.

  2. Add Location Function: Define a function to add a new location to the objectLocations array. This function will retrieve the current array from the global variable, add the new location, and then update the global variable.

  3. Usage: Use the addLocation function to add new locations to the array.

Here's how you can structure your script:

// Function to add a new location
function addLocation(name, xPos, yPos, zPos) {
    // Check if $objectLocations is defined and retrieve it, or initialize as an empty array
    var objectLocations = getVar('$objectLocations', []);

    // Add the new location
    objectLocations.push({name: name, x: xPos, y: yPos, z: zPos});

    // Update the global variable
    setVar('$objectLocations', objectLocations);
}

// Example usage
var name = getVar('$name');
var xPos = getVar('$xPos');
var yPos = getVar('$yPos');
var zPos = getVar('$zPos');

// Add the new location
addLocation(name, xPos, yPos, zPos);

// Debug: Print the updated array to the console
console.log(getVar('$objectLocations'));

Important Notes:

  • Ensure you're using getVar and setVar correctly to interact with global variables. The first argument should be the global variable name as a string (e.g., '$objectLocations').
  • This script assumes that getVar and setVar can handle complex objects and arrays directly. If ARC's scripting environment has limitations on what can be stored in global variables, you may need to serialize the array to a string format before storing it and deserialize it when retrieving. Use JSON.stringify() for serialization and JSON.parse() for deserialization if necessary.

By following this approach, you should be able to maintain the objectLocations array across different script runs, allowing you to accumulate locations without overwriting previous entries.


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

@Athena  I may have found the problem. While looking over the smart variable watcher noticed there were 6 different references to $objectlocations. Not sure how that happened but pretty sure will need to get rid of them to have a clean slate. How do I get rid of those and start fresh and how do I avoid this in the future as they were all named exactly the same.

#97  

I've also noticed duplicate global variables showing up in the Smart Variable Watcher skill when I run scripts several times. I'm not really sure this effects anything but may in your case. I'm not sure what causes this but seems to happen after I edit a script (I think). When way I fix it is I press the "Refresh" button at the bottom of the Smart Variable Watcher skill. Not the other button down their or everything will be reset. After I refresh the skill duplicate global variables in the list don't seem to happen anymore during that session.

#99   — Edited

@Athena Have the array running pretty well today and started to make different scripts to organize things. Something that I noticed is don't you have to use the getVar("$objectLocations") function to    for if (typeof objectLocations === 'undefined') { var objectLocations = []; } because you are questioning the global variable objectLocations What is the proper way to write this code? Do I need to refresh the global variable objectLocations at the bottom of each script each time the array has been manipulated?

How do I change the name of location_5 to Advil? How do I change the y value of location_5 to 53?

PRO
Canada
#100  

To address your questions and provide clarity on working with global variables and arrays in ARC, let's break down the steps and correct the code snippets you've mentioned.

Checking if Global Variable Exists and Initializing

When you want to check if a global variable (like objectLocations) exists and initialize it if not, you indeed need to use the getVar() function. This function allows you to retrieve the value of a global variable, and you can specify a default value if the variable does not exist. Here's how you can correctly perform this check and initialization:

// Check if $objectLocations exists and retrieve it, or initialize as an empty array
var objectLocations = getVar("$objectLocations", []);

// Now, objectLocations is guaranteed to be an array (either retrieved or newly initialized)

Refreshing Global Variable

If you manipulate the objectLocations array within your script and want these changes to persist globally, you must update the global variable using setVar() after making your modifications. There's no need to "refresh" the variable at the bottom of each script, but you do need to ensure you update the global variable whenever you change the array:

// Example: Adding a new location to the array
objectLocations.push({name: "NewLocation", x: 10, y: 20, z: 30});

// Update the global variable to reflect this change
setVar("$objectLocations", objectLocations);

Changing the Name and Value of a Specific Location

To change the name of location_5 to "Advil" and its y value to 53, you'll first need to find the location within your array, then update its properties. Assuming location_5 is an identifier or part of the name property, here's how you might do it:

// Iterate through the objectLocations array to find the location to update
for (var i = 0; i < objectLocations.length; i++) {
    if (objectLocations[i].name.includes("location_5")) {
        // Found the location, now update its name and y value
        objectLocations[i].name = "Advil";
        objectLocations[i].y = 53;
        
        // Break the loop since we found and updated the location
        break;
    }
}

// Don't forget to update the global variable after making changes
setVar("$objectLocations", objectLocations);

Avoiding Duplicate Global Variables

As Dave mentioned, pressing the "Refresh" button in the Smart Variable Watcher skill can help manage the display of variables within that skill. To avoid creating duplicates in your scripts, always ensure you're using consistent variable names and updating existing variables rather than unintentionally creating new ones with similar names.

By following these guidelines, you should be able to manage and manipulate global variables and arrays in ARC effectively, ensuring your changes persist across script executions and sessions.


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

Sometimes it's so obvious when you look back over it after taking a break on it. 3 for 3 for problem solving today-a good day.

#102   — Edited

@Athena Why would my script say     Execution Error Line 13 Col 4 - Object has no method 'push' or this    Execution Error Line 23 Col 4 - Object has no method 'find' It has been a little while since I ran the script but I thought it was working when I left it. I did reload the variables with the variable state saver.

PRO
Canada
#103  

The errors you're encountering, "Object has no method 'push'" and "Object has no method 'find'", suggest that the variable you're trying to use these methods on is not recognized as an array or does not have the expected properties/methods available. This can happen for a few reasons in the context of ARC and JavaScript scripting:

  1. Variable Not an Array: The push method is specific to arrays in JavaScript. If you're getting an error stating that push is not a method, it likely means that the variable you're trying to use it on has not been correctly initialized as an array. This can happen if the variable was overwritten with a non-array value or if it was not properly retrieved as an array from the global variables.

  2. Variable Not an Object with Expected Method: Similarly, the find method is used on arrays to search for elements. If you're getting an error about find not being a method, it suggests that the variable is not an array or the environment does not support this method.

  3. Reloading Variables: If you've reloaded variables using the Variable State Saver, ensure that the data structure (array or object) was correctly preserved during the save and load process. It's possible that the structure was flattened or changed, causing the methods to be unavailable.

To troubleshoot and resolve these issues, you can:

  • Ensure Initialization as Array: When you initialize or retrieve the variable, make sure it's explicitly set as an array. For example:

    var objectLocations = getVar("$objectLocations", []);
    
  • Check for Array Before Using Array Methods: Before using array-specific methods like push or find, check if the variable is indeed an array:

    if (Array.isArray(objectLocations)) {
      // Safe to use array methods like push or find
    } else {
      // Handle case where objectLocations is not an array
      // Possibly re-initialize or log an error
    }
    
  • Compatibility: Ensure that the scripting environment you're using supports the methods you're trying to use. While push should be universally supported in JavaScript environments, find might not be available in very old JavaScript engines (though this is unlikely to be an issue in ARC).

  • Update Global Variable Correctly: After modifying your array or object, remember to update the global variable with setVar to ensure the changes are saved globally:

    setVar("$objectLocations", objectLocations);
    

By following these steps, you should be able to identify why the methods push and find are not available for your variable and ensure that your script works as expected.


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

@Athena Can you write a multidimensional array that reads the servo positions of V1, V2, V3 at 1 second intervals for 120 seconds and puts it into an automated named Location 1, Location 2, Location 3, etc (which I will change later). Each Location will have xpos, yPos, zPos. Put the array in a nice orderly spreadsheet format with space between each xpos, yPos, zPos. The array is to have a replay on the log screen again at 1 second intervals if ADC 3 is switched to high and replay in reverse if ADC 4 is switched high. The replay will make V1, V2, V3 move to their locations if ADC 5 is high.

Give multiple examples of it working.

PRO
Canada
#105  

Creating a script that captures servo positions at intervals, stores them in a multidimensional array, and replays them based on ADC port conditions involves several steps. Given the complexity and the limitations of this text-based format, I'll outline a conceptual approach and provide a pseudo-code example to guide you. This example assumes you're familiar with JavaScript syntax within ARC's scripting environment.

Step 1: Initialize Variables

First, initialize your variables, including the multidimensional array to store servo positions and a counter for naming locations dynamically.

var servoPositions = [];
var locationCounter = 1;
var captureInterval = 1000; // 1 second in milliseconds
var totalDuration = 120 * 1000; // 120 seconds

Step 2: Capture servo Positions

Use a loop or setInterval to capture servo positions every second for 120 seconds. Store these positions in the servoPositions array.

function captureServoPositions() {
    var captureCount = totalDuration / captureInterval;
    var capture = setInterval(function() {
        if (captureCount <= 0) {
            clearInterval(capture);
            console.log("Finished capturing servo positions.");
            return;
        }
        
        var v1Pos = Servo.getPosition(V1);
        var v2Pos = Servo.getPosition(V2);
        var v3Pos = Servo.getPosition(V3);
        servoPositions.push({name: "Location " + locationCounter, xPos: v1Pos, yPos: v2Pos, zPos: v3Pos});
        locationCounter++;
        captureCount--;
    }, captureInterval);
}

Step 3: Check ADC Conditions and Replay Positions

Create functions to check ADC conditions and replay the captured positions either in forward or reverse order. Use ADC.get() to check the ADC port states.

function replayPositions(forward = true) {
    var index = 0;
    var replayInterval = setInterval(function() {
        if ((forward && index >= servoPositions.length) || (!forward && index < 0)) {
            clearInterval(replayInterval);
            console.log("Finished replaying servo positions.");
            return;
        }
        
        var location = forward ? servoPositions[index] : servoPositions[servoPositions.length - 1 - index];
        if (ADC.get(5) === 1) { // Check if ADC 5 is high before moving servos
            Servo.setPosition(V1, location.xPos);
            Servo.setPosition(V2, location.yPos);
            Servo.setPosition(V3, location.zPos);
        }
        
        forward ? index++ : index--;
    }, 1000);
}

function checkADCAndReplay() {
    if (ADC.get(3) === 1) {
        replayPositions(true); // Replay forward
    } else if (ADC.get(4) === 1) {
        replayPositions(false); // Replay in reverse
    }
}

Step 4: Execute and Test

Start by calling captureServoPositions() to begin capturing servo positions. Then, periodically call checkADCAndReplay() to check ADC conditions and replay positions as required.

captureServoPositions();
setInterval(checkADCAndReplay, 1000); // Check ADC conditions every second

Note:

  • This example uses pseudo-code and assumes functions like Servo.getPosition() and Servo.setPosition() are available and work as described. You may need to adjust the code based on ARC's actual JavaScript API and the specific syntax for accessing servo positions and ADC ports.
  • The script does not directly create a spreadsheet but organizes data in a way that could be exported or logged for spreadsheet use. For actual spreadsheet creation, you would need to export the servoPositions array to a CSV file or use a similar method compatible with ARC's capabilities or external tools.

This example provides a conceptual framework. You'll need to adapt and test it within your ARC environment, considering ARC's scripting capabilities and the specifics of 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.
#106  

@Athena Nicely done! Will check it all tomorrow but it looks good. You were right about giving only one example because unlike other arrays this will only have one outcome. Thanks

PRO
Canada
#107  

You're welcome! I'm glad the outline and pseudo-code provided a good starting point for your project. Remember, the key to success with scripts like this is testing and fine-tuning to fit your specific needs and the capabilities of your robot and ARC environment. If you encounter any issues or have further questions as you work through implementing and testing the script, feel free to reach out. Good luck with your project, and I hope it performs exactly as you envision!


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

@Athena For testing purposes I tried to change from the ADC values to the Digital values of D11, D12, D13. Is this done correctly? Is the D supposed to be capital D or lowercase d? Should I be asking   if (Digital.set(D12) === true);   or   if (Digital.(D12) === true);   ?    I received an error message saying Execution Error Line 11 Col 4 - setInterval is not defined. I am not sure why it is saying this. It seems like it is just a typical variable and not a global variable. Could it be that in typical Javascipt it means something in particular but in ARC environment it does not recognize it correctly?  Here is the script , please rewrite it correctly so that I can have a working script. I would also like to incorporate if Digital 4 is true then start the captureServoPositions and if Digital 5 is true then start the setInterval(checkDigitalAndReplay, 1000);

var servoPositions = []; var locationCounter = 1; var captureInterval = 1000; // 1 second in milliseconds var totalDuration = 120 * 1000; // 120 seconds

//Step 2: Capture servo Positions //Use a loop or setInterval to capture servo positions every second for 120 seconds. Store these positions in the servoPositions array.

function captureServoPositions() { var captureCount = totalDuration / captureInterval; var capture = setInterval(function() { if (captureCount <= 0) { clearInterval(capture); console.log("Finished capturing servo positions."); return; }

    var v1Pos = Servo.getPosition(V1);
    var v2Pos = Servo.getPosition(V2);
    var v3Pos = Servo.getPosition(V3);
    servoPositions.push({name: "Location " + locationCounter, xPos: v1Pos, yPos: v2Pos, zPos: v3Pos});
    locationCounter++;
    captureCount--;
}, captureInterval);

} //Step 3: Check ADC Conditions and Replay Positions //Create functions to check ADC conditions and replay the captured positions either in forward or reverse order. Use ADC.get() to check the ADC port states.

function replayPositions(forward = true) { var index = 0; var replayInterval = setInterval(function() { if ((forward && index >= servoPositions.length) || (!forward && index < 0)) { clearInterval(replayInterval); console.log("Finished replaying servo positions."); return; }

    var location = forward ? servoPositions[index] : servoPositions[servoPositions.length - 1 - index];
    setInterval(checkDigitalAndReplay, 1000);{ // if (ADC.get(5) === 1) { // Check if ADC 5 is high before moving servos
        Servo.setPosition(V1, location.xPos);
        Servo.setPosition(V2, location.yPos);
        Servo.setPosition(V3, location.zPos);
    }
    
    forward ? index++ : index--;
}, 1000);

}

function checkDigitalAndReplay() { //if (ADC.get(3) === 1) //if (Digital.(D11) === true); if (Digital.set(D12) === true); { replayPositions(true); // Replay forward } if (Digital.set(D13) === true); // else if (ADC.get(4) === 1) { replayPositions(false); // Replay in reverse } } //Step 4: Execute and Test //Start by calling captureServoPositions() to begin capturing servo positions. Then, periodically call checkADCAndReplay() to check ADC conditions and replay positions as required.

captureServoPositions(); setInterval(checkDigitalAndReplay, 1000); // Check ADC conditions every second

When I copied and pasted it rewrote the script and it is not as organized as I had it in my script.

PRO
Canada
#109  

To address your questions and correct the script for use in ARC's environment, let's go through each point:

  1. Digital Port Syntax: In ARC, when referencing digital ports in scripting, you typically use the port number directly without needing to specify "D" or "d". The ARC scripting environment handles the port referencing internally, so you would check the state of a digital port using the getDigital() function (assuming such a function exists or is similarly named in ARC's JavaScript API).

  2. setInterval and clearInterval Errors: The error you're encountering with setInterval not being defined suggests that the JavaScript environment within ARC might not support all standard web JavaScript functions, including setInterval and clearInterval. ARC's scripting environment has its own set of functions and may not include some that are standard in web development or Node.js environments.

  3. Starting Capture and Replay Based on Digital Inputs: To start capturing servo positions or replaying them based on digital inputs, you'll need to continuously check the state of the digital inputs and trigger the respective functions accordingly. This can be done using a loop or a recurring check function that ARC supports.

Given these points, here's a conceptual rewrite of your script tailored for ARC, assuming ARC has a way to periodically execute a check (since setInterval might not be supported directly). This example uses pseudo-code to illustrate the logic:

var servoPositions = [];
var locationCounter = 1;
var captureInterval = 1000; // 1 second in milliseconds
var totalDuration = 120 * 1000; // 120 seconds

function captureServoPositions() {
    var endTime = Date.now() + totalDuration;
    function capture() {
        if (Date.now() >= endTime) {
            console.log("Finished capturing servo positions.");
            return;
        }
        var v1Pos = Servo.getPosition(1); // Assuming Servo.getPosition takes port number
        var v2Pos = Servo.getPosition(2);
        var v3Pos = Servo.getPosition(3);
        servoPositions.push({name: "Location " + locationCounter, xPos: v1Pos, yPos: v2Pos, zPos: v3Pos});
        locationCounter++;
        setTimeout(capture, captureInterval); // Using setTimeout for next capture
    }
    capture();
}

function replayPositions(forward = true) {
    var index = 0;
    function replay() {
        if ((forward && index >= servoPositions.length) || (!forward && index < 0)) {
            console.log("Finished replaying servo positions.");
            return;
        }
        var location = forward ? servoPositions[index] : servoPositions[servoPositions.length - 1 - index];
        if (getDigital(5)) { // Assuming getDigital checks the state of a digital port
            Servo.setPosition(1, location.xPos);
            Servo.setPosition(2, location.yPos);
            Servo.setPosition(3, location.zPos);
        }
        index += forward ? 1 : -1;
        setTimeout(replay, 1000); // Using setTimeout for next replay
    }
    replay();
}

function checkDigitalAndReplay() {
    if (getDigital(11)) { // Start capturing
        captureServoPositions();
    } else if (getDigital(12)) { // Start replaying forward
        replayPositions(true);
    } else if (getDigital(13)) { // Start replaying in reverse
        replayPositions(false);
    }
}

// Replace setInterval with ARC's equivalent periodic execution method
// ARC's scripting environment needs a way to periodically call checkDigitalAndReplay

Note: This script assumes functions like Servo.getPosition(), Servo.setPosition(), and getDigital() exist in ARC's JavaScript API and work as described. You'll need to replace these with the actual functions provided by ARC for accessing servo positions and digital port states. Additionally, since setInterval is not recognized, I've used setTimeout for delays between actions, and you'll need to find ARC's equivalent method for periodically executing checkDigitalAndReplay().


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

@Athena I think you keep giving me expressions that are known to typical Javascript but are unknown in the ARC environment. Can you rephrase these so it will work within ARC and I will not have to go back and rewrite your code. Some items that I noticed are      if (Date.now() >= endTime) {   which I don't think it recognizes Date,now   or  endTime and there could be some others that are questionable.  Rewrite the script so that it simply works when I run the script. I do not want to involve any ADC ports or Digital high or low values to make it work. Print it out on the log screen as it is building up the array. For testing purposes I will have a different script running in the background to continuously change the values of V1, V2, V3. so the array will accumulate different values. Make the array be a global variable so that I can pull it up and print it whenever I want. Can you please check and verify that it works within ARC before you send it to me. How can I double check your code words and expressions to see if they work within the ARC environment?  Thanks.

PRO
Canada
#111  

Given the constraints and requirements for ARC's environment, let's simplify the approach and ensure compatibility. ARC's scripting environment, particularly for JavaScript, may not support all standard JavaScript functions directly, such as Date.now() or setInterval(). Instead, ARC provides its own set of commands and functions tailored for robot programming.

To create a global array that captures servo positions (V1, V2, V3) and prints the accumulating values to the log without relying on unsupported JavaScript functions, we'll focus on ARC-specific scripting methods. Since direct execution and testing within ARC's environment are not possible in this format, I'll guide you on structuring the script based on ARC's capabilities and documentation.

Step 1: Define a Global Array

First, ensure you have a global array defined to store the servo positions. In ARC, global variables can be managed through the Variable Manager or directly within scripts using specific commands for setting and getting variable values.

Step 2: Capture servo Positions

To capture servo positions without using setInterval() or Date.now(), you can create a function that uses ARC's timing functions to loop through and capture servo positions at desired intervals. ARC scripts typically run in a loop when activated, so you can leverage this behavior.

Step 3: Print to Log

ARC provides functions to print messages to the log, which you can use to output the contents of your global array.

Pseudo-Script:

// Assuming ARC has a way to define global arrays; if not, use a regular array and manage it globally as needed
var servoPositions = [];

function captureServoPositions() {
    // Placeholder for capturing servo positions
    // Replace 'getServoPosition' with the actual ARC command to get a servo's position
    var v1Pos = getServoPosition(1); // V1
    var v2Pos = getServoPosition(2); // V2
    var v3Pos = getServoPosition(3); // V3

    // Push the captured positions into the array
    servoPositions.push({v1: v1Pos, v2: v2Pos, v3: v3Pos});

    // Print the latest captured positions to the log
    print("Captured Positions: V1=" + v1Pos + ", V2=" + v2Pos + ", V3=" + v3Pos);
}

// Function to print the entire servoPositions array to the log
function printServoPositions() {
    for (var i = 0; i < servoPositions.length; i++) {
        var pos = servoPositions[i];
        print("Location " + (i+1) + ": V1=" + pos.v1 + ", V2=" + pos.v2 + ", V3=" + pos.v3);
    }
}

// Example usage
captureServoPositions(); // Call this function at the desired intervals
printServoPositions(); // Call this when you want to print the entire array to the log

Note: This script uses placeholders like getServoPosition and print, which you should replace with the actual ARC commands for getting servo positions and printing to the log. ARC's scripting documentation and the command reference will be your best resources for finding the exact syntax and available functions.

Verifying Code in ARC:

To verify and test scripts within ARC:

  1. Refer to the ARC Scripting manual available in the ARC software under the "Help" section or on the Synthiam website.
  2. Use the script editor within ARC to write and test your scripts. The editor provides syntax highlighting and some level of syntax checking.
  3. Consult the ARC forums and support documentation for examples and guidance on specific functions and commands.

Remember, the exact implementation will depend on ARC's current scripting capabilities and the specific commands it supports for servo control and logging.


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

Got it working, although I did have to modify a lot of the code. Thanks

#113  

Quote:

although I did have to modify a lot of the code
That just means that you're learning and better than AI.

#114   — Edited

Hi there Dave, hope things are going well. Yes I am getting the hang of Javascript. Something you may want to consider is having fun with B9 to be an automated bartender or burger bot. Could be interesting. The aluminum cans and bottles do not have to be filled with liquid for simulating purposes.