Creating an example to use the servomotor

Now, we are going to show you how you can move the motor using a node. Create a new file, c8_dynamixel.cpp, in your /c_tutorials/src directory with the following code snippet:

#include<ros/ros.h> 
#include<std_msgs/Float64.h> 
#include<stdio.h> 
 
using namespace std; 
 
class Dynamixel{ 
  private: 
  ros::NodeHandle n; 
  ros::Publisher pub_n; 
  public: 
  Dynamixel(); 
  int moveMotor(double position); 
}; 
 
Dynamixel::Dynamixel(){ 
  pub_n = n.advertise<std_msgs::Float64> 
("/tilt_controller/command",1); } int Dynamixel::moveMotor(double position) { std_msgs::Float64 aux; aux.data = position; pub_n.publish(aux); return 1; } int main(int argc,char** argv) { ros::init(argc, argv, "c8_dynamixel"); Dynamixel motors; float counter = -180; ros::Rate loop_rate(100); while(ros::ok()) { if(counter < 180) { motors.moveMotor(counter*3.14/180); counter++; }else{ counter = -180; } loop_rate.sleep(); } }

This node will move the motor continuously from -180 to 180 degrees. It is a simple example, but you can use it to make complex movements or control more motors. We assume that you understand the code and that it is not necessary to explain it. Note that you are publishing data to the /tilt_controller/command topic; this is the name of the motor.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.157.182