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

Don't limit your robot's potential – subscribe to ARC Pro and transform it into a dynamic, intelligent machine.

#17  

@Athena, what is the Javascript command that is equivalent to the EZ Script command:

UARTReadBinary( boardIndex, port, numBytes, variable )

Receive binary bytes from the Peripheral UART Receive Buffer of the EZ-B v4 into the variable as an array. The UART receive buffers on the EZ-B v4 are 5,000 bytes. To know how many bytes are available, use the UARTAvailable() function. The Board Index is the EZ-B index starting at 0. The port can be 0, 1 or 2. Look near at the UART Port section lower in this document for the EZ-B Pin’s associated with each UART Port. Example: UARTReadBinary(0, 0, 10, $variable) Example: UARTReadBinary(0, 0, UARTAvailable(0, 1), $variable))

I am trying to convert one of my EZ Scripts into Javascript and have this command I can't figure out how to write it in Javascritp:

UartReadBinary(2, 0, $y, $Get_Lft_Elbow_P

Here is my whole EZ script that works. I'm sending a Simple Serial command to a Kangaroo Motor controller. The controller will return a position number starting with a upper or lower case "P" (P or p). Upper case "P" means the motor stopped and a lower case "p" means it's still moving. The purpose of this script is to find out if the motor is still moving:

# The script below to get Binary "P or "p"
# This Script will return the Binary "P or "p" of the Left Elbow.
# If Print returns 112, Then this is a lowercase p and move is still underway.
# If Print returns 80, Then this is a Uppercase P and move is over. 

#-----------------------------------

# Get Right Channel ARS Kangaroo position
uartWrite(2, 0, "2, Getp", 0x0d)

:waitForData

$y = UartAvailable(2, 0)
#Sleep(30)
print("Bytes in buffer:" + $y)

if ($y < 6)
  # Go back and wait for data again because we did not receive the least number of expected bytes.
  goto(waitForData)
endif

  # Sleep(30)
UartReadBinary(2, 0, $y, $Get_Lft_Elbow_P)

Sleep(50)

# ###################################################
# -------------------------------
# Find out and print if the Lft P is upper or lower case.
# Upper case means motor has finished move and stopped.
# Lower Case means that motor is still moving.
# If Print returns 112, Then this is a lowercase p and move is still underway.
# If Print returns 80, Then this is a Uppercase P and move is over. 
# If any other value is returned this is a Kangaroo Error message. Restart
# Kangaroo and rehome then try again.
#########################################################

# Assign a variable to either a capitol P or Small case p returned by Kangaroo.
$Lft_Elbow_P_or_p = $Get_Lft_Elbow_P[2]
Print("Received:" + $Lft_Elbow_P_or_p)
One last question, Like I mentioned, this script works as written in EZ Script. Inside the script control on the console I'll see the return in Binary numbers which is OK (112, Then this is a lowercase p and move is still underway and if Print command returns 80, Then this is a Uppercase P and move is over.). Now on the outside of the control in the control's console window I'll see the actual "P" or "p" letter. Why the different return between the script control's inside and outside console windows? What should I look for as a return in a script? Binary or the actual letters?
PRO
Canada
#18  

In ARC's JavaScript environment, to perform an operation similar to the EZ-Script UARTReadBinary() function, you would use a combination of the UART.initHardwareUart(), UART.hardwareUartWrite(), and UART.hardwareUartRead() functions. These functions allow you to initialize a UART port, send data, and read incoming binary data from the UART buffer.

Here's how you might convert your EZ-Script to JavaScript for sending a command to your Kangaroo Motor controller and reading the response to check if the motor is still moving:

// Initialize UART port (if not already initialized)
UART.initHardwareUart(0, 9600); // Assuming UART 0 and baud rate of 9600

// Function to send command to Kangaroo Motor controller
function sendCommandToKangaroo(command) {
  // Convert the command string to a byte array
  var commandBytes = [];
  for (var i = 0; i < command.length; i++) {
    commandBytes.push(command.charCodeAt(i));
  }
  
  // Send the command bytes to the Kangaroo Motor controller
  UART.hardwareUartWrite(0, commandBytes);
}

// Function to check if the motor is still moving
function isMotorMoving() {
  // Assuming you've already sent a command to the Kangaroo that triggers a response
  // Check how many bytes are available to read
  var availableBytes = UART.hardwareUartAvailable(0);
  
  if (availableBytes > 0) {
    // Read the available bytes
    var responseBytes = UART.hardwareUartRead(0, availableBytes);
    
    // Convert byte array to string to check for 'P' or 'p'
    var responseString = String.fromCharCode.apply(null, responseBytes);
    
    if (responseString.indexOf('P') !== -1) {
      // Motor stopped (found uppercase 'P')
      return false;
    } else if (responseString.indexOf('p') !== -1) {
      // Motor is moving (found lowercase 'p')
      return true;
    }
  }
  
  // Default case, if no 'P' or 'p' found
  return false;
}

// Example usage
sendCommandToKangaroo("YourCommandHere");
sleep(1000); // Wait for a response (adjust timing as needed)
var moving = isMotorMoving();
if (moving) {
  print("Motor is moving.");
} else {
  print("Motor stopped.");
}

This script demonstrates how to send a command to the Kangaroo Motor controller and read the response to determine if the motor is still moving. Note that the sleep() function is used to provide a delay between sending the command and reading the response, which may need to be adjusted based on your specific requirements.


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  

Ugh. A lot of that doesn't sound correct. I already have written commands to do that. It's a one line command:

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

All I really wanted to know was if there is a JavaScript command that I can use that is the same as this EZ Script command.

UARTReadBinary( boardIndex, port, numBytes, variable )

@Athena, One last question, Like I mentioned, this script works as written in EZ Script. Inside the script control on the console I'll see the return in Binary numbers which is OK (112, Then this is a lowercase p and move is still underway and if Print command returns 80, Then this is a Uppercase P and move is over.). Now on the outside of the control in the control's console window I'll see the actual "P" or "p" letter. Why the different return between the script control's inside and outside console windows? What should I look for as a return in a script? Binary or the actual letters?

PRO
Synthiam
#20  

She's "sort of" correct because the code you pasted is a bit unrelated to the question, so i think she was trying to help you rewrite the whole thing without having any context of what the code does.:)

The answer to your question is this: synthiam.com/Support/javascript-api/UART/hardwareUartRead

hardwareUartRead

You can see all available UART commands in the UART section of the javascript support. That link will bring you to it.

In her example, she demonstrated how to determine how many bytes are available, and then read those bytes using hardwareUARTRead

  var availableBytes = UART.hardwareUartAvailable(0);
  
  if (availableBytes > 0) {

   var responseBytes = UART.hardwareUartRead(0, availableBytes);

   /// the array responseBytes contains the bytes from the response
    }
#21   — Edited

OK, Thanks DJ, I'm able to get that far in a JavaScript written script and am able to read the returned value. For example I'll get a returned position that looks like this: 1,P2074 *The "1" is the motor channel on the Kangaroo *The "," is just a comma. *The P is returned in wither upper case or lower case depending on if the move is completed or not (motor moving or stopped). *The last numbers are the actual position when the data was sent.

Then I use this command to Parse the numbers from the "1" and "," :

var Rt_Elbow_stopped = Number(UartReadStringAvailable_RtElbow.substr(3, 7));
print ("Rt_Elbow_stopped: " + Rt_Elbow_stopped);

When I try to adjust the .substr(3, 7)  to target the "P" in the returned value of 1,P2074 I get a "NaN". My target is .substr(2, 4)

Any Idea why I am gettin NAN and not the status of the P?

PRO
Synthiam
#22  

I need clarification to ensure my advice doesn't take you down the wrong path - why are you asking about reading bytes, but the last bit of code you pasted shows reading a string?

PRO
Canada
#23  

It seems there might be a bit of confusion regarding handling binary data and string parsing in JavaScript. Let's clarify the process of reading data from a UART port and extracting specific parts of the data, such as the 'P' character and the position value from a string like "1,P2074".

Firstly, when you use UART.hardwareUartRead(), you're reading binary data (bytes) from the UART buffer. If you're expecting a string response like "1,P2074", you'll need to convert the binary data (byte array) into a string for easier manipulation.

Here's a step-by-step approach to read the UART data, convert it to a string, and then parse the string to extract the 'P' character and the position value:

  1. Read UART Data: Read the available bytes from the UART buffer.
  2. Convert to String: Convert the byte array to a string.
  3. Parse the String: Extract the desired parts from the string.

Here's how you could implement it in JavaScript:

// Step 1: Read UART Data
var availableBytes = UART.hardwareUartAvailable(0);
if (availableBytes > 0) {
    var responseBytes = UART.hardwareUartRead(0, availableBytes);

    // Step 2: Convert to String
    // Assuming the response is ASCII encoded
    var responseString = String.fromCharCode.apply(null, responseBytes);

    // Step 3: Parse the String
    // Example response: "1,P2074"
    var channel = responseString.charAt(0); // '1'
    var movementStatus = responseString.charAt(2); // 'P'
    var position = responseString.substring(3); // "2074"

    // Convert position to a number
    var positionValue = parseInt(position, 10);

    // Check if parsing was successful
    if (!isNaN(positionValue)) {
        // Parsing successful
        console.log("Channel:", channel);
        console.log("Movement Status:", movementStatus);
        console.log("Position:", positionValue);
    } else {
        // Parsing failed, handle error
        console.log("Error parsing position");
    }
}

Regarding your question about getting NaN (Not a Number) when trying to parse the position:

  • NaN results from attempting to convert a non-numeric string to a number using parseInt() or similar functions. If you're targeting the correct substring but still getting NaN, ensure that the substring indeed contains only numeric characters.
  • The .substr(2, 4) usage might not be what you want if you're trying to extract the position. .substr(2, 4) starts at index 2 and extracts 4 characters, which, in your example "1,P2074", would result in "P207". To extract the position, you should start parsing after the 'P', as shown in the example above.

Remember, the exact parsing logic might need to be adjusted based on the consistent format of the data you're receiving from the UART port.


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

@athena what about this?

var avail = UART.hardwareUartAvailable(0);

if (avail >= 7) {

  var resp = UART.hardwareUartReadString(0, 7);
  
  if (resp[0] != '1')
    throw new Error("First character should be a 1");

  if (resp[1] != ',')
    throw new Error("Second character should be a ,");
    
  if (resp[2] != 'P')
    throw new Error("Third character should be a P");

  // get the last 4 characters of the string
  var tmpPart = resp.slice(-4);
  
  // convert the string to an int
  // THIS is your final number value
  var tmpInt = parseInt(tmpPart);
  
  // Do something with tmpInt
  print(tmpInt);    
}