[Documentation] [TitleIndex] [WordIndex

(!) Please ask about problems and questions regarding this tutorial on answers.ros.org. Don't forget to include in your question the link to this page, the versions of your OS & ROS, and also add appropriate tags.

Using publish and subscribe to create control code in javascript

Description: This tutorial looks at how you can create control code in javascript using the publish and subscribe functionality

Tutorial Level: BEGINNER

This code for this tutorial is contained in rosjs_tutorials.

Video

Code Snippet

This function shows how given a command the control code can be written to move the turtles. Depending upon input from the web browser (see the full turtlesim_webcontrol.html file if you want to know how the input was handled).

        function handleinput(id){
          this.id=id;
          this.velocity={};
          this.velocity.linear=0;
          this.velocity.angular=0;

          if(this.id=="up"){
                this.velocity.linear=2;
             }
             else if(this.id=="down"){
                this.velocity.linear=-2;
             }
             else if(this.id=="left"){
                this.velocity.angular=-2;
             }
             else{
                this.velocity.angular=2;
             }
          this.rosNode=that.rosNode;
          that=this;

          return interval=setInterval(function(){
              that.rosNode.publish('/turtle1/command_velocity', 'turtlesim/Velocity',  ros.json(that.velocity));
            },100);

          };

Code Break Down

          this.id=id;
          this.velocity={};
          this.velocity.linear=0;
          this.velocity.angular=0;

          if(this.id=="up"){
                this.velocity.linear=2;
             }
             else if(this.id=="down"){
                this.velocity.linear=-2;
             }
             else if(this.id=="left"){
                this.velocity.angular=-2;
             }
             else{
                this.velocity.angular=2;
             }

This code sets the angular and linear velocity depending upon the input.

return interval=setInterval(function(){
              that.rosNode.publish('/turtle1/command_velocity', 'turtlesim/Velocity',  ros.json(that.velocity));
            },100);

This code publishes a topic with name /turtle1/command_velocity and type tutlesim/Velocity with the value that was set due to user input every 100 ms.


2019-12-07 13:04