Asked — Edited
Resolved Resolved by DJ Sures!

Javascript Question - Var Or Setvar?

@Athena  When I write a script using Javascript and I want to set a variable what command should I use. I've used both setVar and simply just Var. Both have worked for me.

For example I have this in my INT Script that runs when my project starts:

setVar( "$adcSoilSpecified", 200 );

And I have this in a stand alone script that operates a motor and watches an encoder:

var Get_Lft_Elbow_P = "2, Getp\r";
UART.hardwareUartWrite(0,Get_Lft_Elbow_P.length,2); //UART 0 on EZB 2

Which is the correct one to use and what is the difference between the two?


Related Hardware EZ-B v4

ARC Pro

Upgrade to ARC Pro

Harnessing the power of ARC Pro, your robot can be more than just a simple automated machine.

#41  

@DJ and @Athena , Great news. The script you provided seems to be working great. I had to make some minor changes to get it to wait until the movement is complete and then return a position. I moved the command that requests the position from the Kangaroo from the beginning of the script (before the loop checking the Function) down into the first line of the function. This resulted in the position request from the Kangaroo to be repeated so the function could get a fresh reading each time. After moving the command to several places in the script this place turned out to be the proper spot. It seems to me that If the GetP command was left at the beginning of the script it would just loop forever looking for a capitol P.  Also the move must be under way with the Roo returning a lower case p for this script to work correctly.

Oh, and I took out the command to initiate the Uart. As mentioned above I have that in my ARC INT script when the robot starts up. I don't seem to need it in the script it's self as I can now get many readings from the Roo fast and quick.

This was a great learning experience for me that was sometimes frustrating. I couldn't have done it with you guidance and work.

Thanks again! Now on to other scripts.

Here is this final script:

// loops until a capital P is returned on UART #0 of EZB #2
// returns the position when P is returned
// --------------------------------

// loop forever because we BREAK out of this loop when P is
// capital
while (true) {
   
  var position = getMovementValue();
  
  // If the position is zero or greater, we know there's a position
  // returned
  if (position > 0) {
  
    print("We stopped moving and the position is: " + position);

    halt();
  }
  
  sleep(50);
 
}

// This function will return the value of the position if
// moving has completed.
// OR it will return -1 if the moving is still happening

function getMovementValue() {

// Get Right Channel ARS Kangaroo position
UART.hardwareUartWriteString(0, "2, Getp\r", 2);

sleep(100)

  // get bytes avaiable on UART #0, EZB #2
  var avail = UART.hardwareUartAvailable(0, 2);

  // If we don't have at least 9 characters, return -1
  if (avail < 9)
    return -1;

  // read 9 bytes from UART #0 on EZB #2
  var resp = UART.hardwareUartReadString(0, 9, 2);

  // More verification this is a valid packet
  if (resp[1] != ',')
    throw new Error("Second character should be a ,");

  // Check if we have a capital P, if so, extract
  // the position and return the new value
  if (resp[2] == 'P') {
   
     // get the characters between positions 3 & 7 of the string
     var tmpPart = resp.substring(3, 7);
   
     // convert the string to an int
     var tmpInt = parseInt(tmpPart);
     
     // return the position
     return tmpInt;
  }

  // still moving 
  return -1;
}
PRO
Canada
#42  

I'm thrilled to hear that the script adjustments worked out for you and that you've made significant progress with your project! It's great that you were able to fine-tune the script to fit your specific needs and that you've gained valuable insights through this process. Your determination and willingness to experiment and learn are commendable.

For the benefit of others who might be following this thread or encountering similar challenges, here's a summary of the key adjustments you made to the script for successful communication with the Kangaroo controller:

  1. Moved the Position Request Command: You moved the command that requests the position (GetP) from the Kangaroo into the function that checks for the response. This ensures that a fresh position request is made each time the function is called, allowing for real-time monitoring of the Kangaroo's response.

  2. Position Request Timing: The position request needs to be made while the Kangaroo is actively moving and returning a lowercase 'p'. This timing ensures that the script waits for movement completion and then captures the final position accurately.

  3. UART Initialization: You confirmed that initializing the UART port in the ARC startup script is sufficient for your setup, eliminating the need to re-initialize the UART within the movement script itself. This simplifies the script and focuses on the core functionality of monitoring and capturing the Kangaroo's response.

Your final script, with these adjustments, effectively communicates with the Kangaroo controller, waits for the movement to complete, and then captures the final position. This solution not only addresses your immediate needs but also provides a template for others working with similar hardware or facing comparable challenges.

Thank you for sharing your experience and the solution you developed. Your contribution enriches the community's knowledge base and supports others in their robotics endeavors. If you have any more insights, questions, or projects you'd like to discuss, please don't hesitate to share!

Keep up the fantastic work with your robot, and I'm here to assist with any future questions or challenges you may encounter.


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

@Athena , I want to add more commands to the last Javascript Script I posted that @DJ has been helping me with. IN his version there is a halt(); command that stops the script. When I remove this command the loop it is in just keeps looping. Can I remove this halt() and replace it with break; to exit the loop? Then I assume I'd be able to lovely more commands to the very end of the script to add to and to continue this script?

I have actually already tried this and it seems to work. However I do not know if this the proper way to structure this script. Here is an example of the loop block I'm talking about. Notice I have commented out the halt() and added the break;

while (true) {
   
  var position = getMovementValue();
  
  // If the position is zero or greater, we know there's a position
  // returned
  if (position > 0) {
      print("We stopped moving and the position is: " + position);
    //halt();
    break;
  }
    //sleep(50);
    
 }

Here is the script I have so far that works. I want to continue to add to this script and am writing it and testing what I've done step by step to see if it works. The last block checks another sensor to see if my arm is indeed centered. I'm not relying solely on the "P" which only lets me know the movement has completed:

//Move Right Elbow motor to Center
UART.hardwareUartWriteString(0,"1,P2470 s1600\r",2); //Connected to UART 0 on EZB 2

//Move Left Elbow motor to Center
UART.hardwareUartWriteString(0,"2,P2490 s1600\r",2); //Connected to UART 0 on EZB 2

// loops until a capital P is returned on UART #0 of EZB #2
// returns the position when P is returned
// --------------------------------

// loop and we BREAK out of this loop when P is
// capital
while (true) {
   
  var position = getMovementValue();
  
  // If the position is zero or greater, we know there's a position
  // returned
  if (position > 0) {
      print("We stopped moving and the position is: " + position);
    //halt();
    break;
  }
    //sleep(50);
    
 }

// This function will return the value of the position if
// moving has completed.
// OR it will return -1 if the moving is still happening

function getMovementValue() {

// Get Right Channel ARS Kangaroo position
UART.hardwareUartWriteString(0, "2, Getp\r", 2);

sleep(100)

  // get bytes avaiable on UART #0, EZB #2
  var avail = UART.hardwareUartAvailable(0, 2);

  // If we don't have at least 9 characters, return -1
  if (avail < 9)
    return -1;

  // read 9 bytes from UART #0 on EZB #2
  var resp = UART.hardwareUartReadString(0, 9, 2);

  // More verification this is a valid packet
  if (resp[1] != ',')
    throw new Error("Second character should be a ,");

  // Check if we have a capital P, if so, extract
  // the position and return the new value
  if (resp[2] == 'P') {
   
     // get the characters between positions 3 & 7 of the string
     var tmpPart = resp.substring(3, 7);
   
     // convert the string to an int
     var tmpInt = parseInt(tmpPart);
     
     // return the position
     return tmpInt;
  }

  // still moving 
  return -1;
}

//Check the opto sensor's ADC value to make sure it's closed. If so we know the arm is centered and in position. 
var Right_Elbow_ADC = ADC.get(0, 2); //Get ADC Value on ADC Port from EZB 2
if (Right_Elbow_ADC < 185){
print("Right Arm Not Centered! Halt!")
ControlCommand("Soundboard v4", "Track_44"); //Say Halt!
halt()
}else if (Right_Elbow_ADC >= 185){
print("Right Arm Centered! Safe to Retract!")//var RightElbow = ADC.get(0, 2); //Get ADC Value on ADC Port from EZB 2
print("Reading: " + Right_Elbow_ADC)
}
#44   — Edited

Ignore. Deleted because of it's gibberish.xD

#45  

OH, LOL. Looks like I added the gibberish. It's commented out so I guess it's doesn't matter. I'll have to clean that out.

//var RightElbow = ADC.get(0, 2); //Get ADC Value on ADC Port from EZB 2

PRO
Canada
#46  

It's great to see your progress and willingness to refine your script further. Using break; to exit a loop in JavaScript is indeed a standard and proper way to control the flow of your script, especially when you want to stop iterating through a loop once a certain condition is met. This approach allows you to exit the loop gracefully and continue executing any subsequent code outside of the loop.

Regarding the halt(); command you mentioned, it's important to clarify that halt(); is not a standard JavaScript function and might have been specific to the context or environment in which you were working. If halt(); was intended to stop the script execution entirely, replacing it with break; would change the behavior to only exit the current loop rather than stopping the entire script.

Given your description, using break; to exit the loop and then continuing with more commands is a valid and effective approach. This allows you to add additional logic or commands after the loop, based on the outcome of the loop or other conditions.

Here's a simplified example to illustrate the structure:

// Loop that checks a condition
while (true) {
    // Some logic here
    if (shouldExitLoop) {
        break; // Exit the loop if the condition is met
    }
    // More logic that runs if the loop hasn't exited
}

// Additional commands after the loop
// You can continue your script here

Cleaning out commented-out code, like the //var RightElbow = ADC.get(0,2); line you mentioned, is a good practice for maintaining clarity and readability in your scripts. It helps you and others understand the script's purpose and flow more easily.

If you have specific functionality in mind that you'd like to add after the loop or if you encounter any challenges while extending your script, feel free to share more details. I'm here to help guide you through the process and provide support as you continue to develop and refine your robot's behavior.


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  

Hi @Athena ,

I need another helping hand converting a command in a script from EZ Script to Java Script.

The following command works in EZ Script; In the this example I'm sending a position command to a Kangaroo motor controller. Using math, I'm changing a number stored in a variable, including this equation in the Kangaroo command and then sending it through the EZB Uart to the Roo.  The number I'm changing is the one after after the "P"):

$Lft_Elbow_Center = 2492
uartWrite(2, 0, "2,P"+($Lft_Elbow_Center - 20), "s300\r")

A working command written in EZ Script to move the motor without using a variable to move the motor looks like this:

uartWrite(2, 0, "2,P"2492, "s300\r") #numbers after the P is position, After the S is the speed

My goal is to send the first command a certain amount of times to move the motor in small increments until it reaches a sensor.

I'm having trouble finding the right way to write the first command in Javascript. This is what I've come up with so far that does not work:

UART.hardwareUartWriteString(0,"2,P" + ($Lft_Elbow_Center - 20) "s300\r" ,2);

I've tried several revisions with no luck. I've read that I should be using -= to subtract a value from a variable but cant seem to get the math to work before I send the command. Also I can't seem to be able to insert a variable into the Kangaroo's command like I was able to do in EZ Script.

Any help is welcomed.

PRO
Canada
#48  

Converting EZ-Script commands to JavaScript within the ARC environment involves understanding how JavaScript handles string concatenation and variable manipulation. From your description, it seems you're trying to dynamically construct a command string that includes a variable value, and then send this command through UART to control a Kangaroo motor controller.

Let's break down the task:

  1. Constructing the Command String: In JavaScript, you can concatenate strings and variables using the + operator. This allows you to dynamically build your command string with variable values.

  2. Sending the Command via UART: To send the command through UART in ARC's JavaScript environment, you'll use the UART.write method, specifying the UART port, and the command as arguments.

  3. Adjusting the Variable: If you need to decrement the variable by a certain value, you can use the -= operator in JavaScript, which subtracts a value from the variable and assigns the result back to the variable.

Here's how you can structure your JavaScript code to achieve the goal based on the information you've provided:

// Assuming 'position' is your variable that holds the initial position value
var position = 1000; // Example initial position
var decrementAmount = 10; // The amount by which you want to decrement the position

// Assuming you want to send the command multiple times in a loop until a condition is met
while (position > someThreshold) { // Replace 'someThreshold' with your actual stopping condition
    // Construct the command string with the current position value
    var command = "1,p" + position + "\r";

    // Send the command via UART
    // Replace 'uartIndex' with your actual UART port index, and ensure the baud rate is correctly set elsewhere
    UART.write(uartIndex, command);

    // Decrement the position by the specified amount
    position -= decrementAmount;

    // Optional: Add a delay or other logic here if needed
}

// Additional logic after the loop can go here

A few notes:

  • Replace uartIndex with the actual index of the UART port you're using.
  • Ensure the UART port is correctly initialized with the appropriate baud rate before sending commands. This might be done in a separate part of your script or setup.
  • Adjust someThreshold to the condition that determines when your loop should stop sending commands.
  • This example uses a while loop to repeatedly send commands, decrementing the position each time until a certain condition (position > someThreshold) is no longer true.

This approach allows you to dynamically adjust the command sent to the Kangaroo motor controller based on the changing value of the position variable, similar to what you achieved with EZ-Script.


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.