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.

PRO
Synthiam
#49   — Edited

She's spot on. Except you should be using: [url]https://synthiam.com/Support/javascript-api/UART/hardwareUartWriteString


// 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.hardwareUartWriteString(uartIndex, command);

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

    // Optional: Add a delay or other logic here if needed
    sleep(250);
}
PRO
Synthiam
#50   — Edited

You can even make it super small by doing this... the above example is easier to read though:)


var position = 1000; // Example initial position
var decrementAmount = 10; // The amount by which you want to decrement the position
var threshold = 100; // Loop until the position drops below this threshold 

while (position > threshold) {

    UART.hardwareUartWriteString(0, "1,p" + (position-=20) + "\r");
    sleep(250);
}
#51  

Ahhh, I was so close. Looks like I was missing the + on the second part that would have tied it all together. Thanks for the help. I felt like I was hitting a wall. I'll work on this tomorrow using your suggestions and get it running.

PRO
Synthiam
#52  

On a note about how terrible ezscript is... I can't believe this even makes sense to anyone...

uartWrite(2, 0, "2,P"2492, "s300\r")

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

Like, what are those? I can't even understand it. EZScript is the worst, haha. I'm pretty sure most of your old ezscript code didn't work but only appeared to work. I feel like it did something, and it seemed to work, so you just assumed it was fine. But ezscript does more damage than good!

#53  

I understand what you're saying. While learning and converting my EZ Scripts I've noticed how strict Javascript is. It does not let me get away with any of the stuff EZ Script did.

However to clear the air, of the two EZ Scripts of mine you just posted only the bottom one works for me. And yes, I can confirm that it does work. There must be some powerful Juju working behind the EZ Script curtain. LOL.

The first command does not run. I must have copied the wrong command. This EZ Command however run perfectly:

uartWrite(2, 0, "2,P2492, s300\r")

This will send a command to the second motor channel on the Kangaroo through UART 0 of EZB 2. That command moves the motor to position 2492 at the speed of 300.

#54   — Edited

@Athena , @DJ or anyone else willing to read this long post. My apologies in advance for it's length.

OK! I'm very happy to report back that thanks to the assistance you provided, I've got my script working nicely. I took your suggestions and the scripts you shared and turned them into a working script that fits my needs. I actually expanded on my simple request asking how to read the "P" returned by the Kangaroo motor controller and do a little math within a Javascript string. However those requests are the backbone of how my script works. Thnkas so much for the help and guidance.

What I'm doing is trying to control two robot arms that moves up and down on an arc. Then they both need stop exactly in the middle of that ARC and retract back into the robot body. It's very important that they stop exactly in the middle of the arc, have the script make a few safety checks to make sure the arms are stopped in the correct spot before other motors start up to retract the arms. You can only imagine the carnage that would happen if the motors retract the arms if they are not centered. There's not much room as I'm pulling a 15.24cm diameter arm through a 17.78cm hole.

Right now in my script I have two checks. *The first method is to read the state of the Returned P being reporting back from the Kangaroo motor controller. Like we mentioned in a different post it will be either an upper case P or lower case p. The upper case (capitol) P means the move is complete. It will look something like this: 1,P2402 depending on what motor channel the motor is attached to and how far the move is. The first number is the roo's motor channel and the last numbers are the actual position.  *The second method id to read the stat of an interoperable opto switch I have mounted exactly at the middle of the arm arc. I have this opto switch wired to an ADC port of an EZB. When an interrupter on the arm cuts off the opto switch beam the ADC reading jumps up and the script knows it's at the midpoint.

Now, here's the good part. What happens when the capitol P pops up in the script telling it that the motor has stopped but the opto switch isn't closed? That should mean that the arm isn't quite centered for some reason. If this ever happens, the script will move the arm to a offset point away from the center and start very small movement steps back towards the center until the opto switch is blocked by the arm's interrupter. This is confirmation that the arm is back to center. The script will do this for each of the two arms.

I've tested this script many time by deliberately stopping the arm off center. Every time the script will see that the opto is not closed and start the decentering routine.

There is one worry I have with this setup. I've forced the arm decentering routine to shoot by the opto switch in a manner that the script didn't see the quick closure. The script will continue to loop and step the motor to the end of the arm's end point of the arc. Luckily the Kangaroo motor controller has a endpoint it watches and wont let the motor go past it. This saves the robot arm but the script continues to loop for ever until I manually stop it.

Letting the Kangaroo reach it's limit to stop the arm is not the worst thing but I'd like to find a way for the script to see that the command to move the motor to re-center it is being sent past a certain point and halt the script. I've worked on this for many hours and can't seem to find a way to stop the Javascript if this happens. I've read all about javascript loops and how to stop or break out of them. I've also studied the different kinds of loops and how they work. I think one issue is I may be having a problem with sending a request for position to the Kangaroo to quickly. Any ideas? I'll post my script. I think It looks clean but I'm just a JS beginner and I really don't know the best way to build it.

Again, thanks for everything!  script.txt

PRO
Canada
#55  

I'm glad to hear that you've made significant progress with your script and that the guidance provided was helpful! It sounds like you've developed a sophisticated system for controlling your robot arms with precision. Your approach to using both the Kangaroo motor controller's feedback and an opto switch for position verification is clever and should provide a reliable mechanism for ensuring the arms are correctly positioned before retracting.

Regarding your concern about the script entering an infinite loop if the arm overshoots the center point without triggering the opto switch, one approach to mitigate this issue is to implement a counter or a limit check within your loop. This counter would increment with each iteration of the loop, and if it exceeds a predefined threshold (indicating that the arm has attempted to re-center itself more times than expected), you can break out of the loop and perhaps trigger an error handling routine.

Here's a conceptual example of how you might implement such a mechanism in your JavaScript code:

var position = 1000; // Example initial position
var decrementAmount = 10; // The amount by which you want to decrement the position
var threshold = 100; // Loop until the position drops below this threshold
var maxAttempts = 50; // Maximum number of attempts to re-center the arm
var attempts = 0; // Counter for the number of re-centering attempts

while (position > threshold && attempts < maxAttempts) {
    // Send the command to re-center the arm
    UART.hardwareUartWriteString(0, "1,p" + (position -= decrementAmount) + "\r");
    sleep(250);
    
    // Increment the attempts counter
    attempts++;
    
    // Check if the opto switch is triggered (example condition)
    if (optoSwitchIsTriggered()) {
        break; // Exit the loop if the arm is centered
    }
}

if (attempts >= maxAttempts) {
    // Handle the error condition (e.g., log an error, stop the motors, etc.)
    console.log("Failed to re-center the arm within the maximum number of attempts.");
}

In this example, optoSwitchIsTriggered() is a placeholder for the actual condition or function you would use to check if the opto switch has been triggered, indicating that the arm is centered. The key addition here is the attempts counter and the maxAttempts threshold, which prevent the loop from running indefinitely.

This approach provides a safeguard against infinite looping by limiting the number of attempts to re-center the arm. If the maximum number of attempts is reached without successfully centering the arm, you can then execute an error handling routine to safely manage the situation.

Remember, the specific implementation details (e.g., how you check the opto switch status) will depend on your project's setup and requirements. The concept here is to use a counter as a mechanism to prevent infinite loops and provide a way to handle situations where the arm cannot be re-centered 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.
#56   — Edited

OK, @Athena , Thanks.

In my build and it's control script I'm mostly interested in implementing the counter. I know that this part of the script loops about 20 times until the interrupter should hit the opto switch. once it passes the opto switch it will not come back and try again. No in this version of the script anyway. If I could find a way to put thiscounter into this part of the loop and set it anywhere between 25 and 35 loops I could have the script stop just after it misses the switch and long before it hits the end limit. Tomorrow is another day.