在Webots C++中将速度设置为差速轮的问题

Issue with setting speed to DifferentialWheels in Webots C++

本文关键字:问题 设置 C++ Webots 速度      更新时间:2023-10-16

这里的小社区,但希望有人看到这个。 我正在尝试为E-puck做一个Webots模拟的纯C++实现。 C++文档非常缺乏,我似乎找不到这个问题的解决方案(C 实现非常出色,但所有函数调用都已更改为 C++)。

从本质上讲,我只是想启动并运行一个简单的应用程序......我想让E-puck前进。 我将在下面发布我的全部代码...我所做的只是实例化一个机器人实体,打印出所有红外传感器值,并尝试将其向前移动。

问题是它不动。 我认为会有一些调用将 Differential Wheel 对象链接到 E-puck(类似于 camera = getCamera("camera") 调用)。

如果我注释掉对setSpeed的调用,程序可以完美运行(不移动,但打印值)。 如果我把它留在里面,模拟会在一个步骤后冻结,一旦它到达那个电话。 老实说,我不确定我做错了什么。

// webots
#include <webots/Robot.hpp>
#include <webots/Camera.hpp>
#include <webots/DistanceSensor.hpp>
#include <webots/DifferentialWheels.hpp>
#include <webots/LED.hpp>
// standard
#include <iostream>
using namespace webots;
#define TIME_STEP 16
class MyRobot : public Robot
{
  private:
    Camera *camera;
    DistanceSensor *distanceSensors[8];
    LED *leds[8];
    DifferentialWheels *diffWheels;
  public: 
    MyRobot() : Robot()
    {
      // camera
      camera             = getCamera("camera");
      // sensors
      distanceSensors[0] = getDistanceSensor("ps0");
      distanceSensors[1] = getDistanceSensor("ps1");
      distanceSensors[2] = getDistanceSensor("ps2");
      distanceSensors[3] = getDistanceSensor("ps3");
      distanceSensors[4] = getDistanceSensor("ps4");
      distanceSensors[5] = getDistanceSensor("ps5");
      distanceSensors[6] = getDistanceSensor("ps6");
      distanceSensors[7] = getDistanceSensor("ps7");
      for (unsigned int i = 0; i < 8; ++i)
        distanceSensors[i]->enable(TIME_STEP);
      // leds
      leds[0] = getLED("led0");
      leds[1] = getLED("led1");
      leds[2] = getLED("led2");
      leds[3] = getLED("led3");
      leds[4] = getLED("led4");
      leds[5] = getLED("led5");
      leds[6] = getLED("led6");
      leds[7] = getLED("led7");
    }
    virtual ~MyRobot()
    {
      // cleanup
    }
    void run()
    {
      double speed[2] = {20.0, 0.0};
      // main loop
      while (step(TIME_STEP) != -1)
      {
        // read sensor values
        for (unsigned int i = 0; i < 8; ++i)
          std::cout << " [" << distanceSensors[i]->getValue() << "]";
        std::cout << std::endl;
        // process data
        // send actuator commands
// this call kills the simulation
//        diffWheels->setSpeed(1000, 1000);
      }
    }
};
int main(int argc, char* argv[])
{
  MyRobot *robot = new MyRobot();
  robot->run();
  delete robot;
  return 0;
}

现在,如果这是 C 实现,我会调用 wb_differential_wheels_set_speed(1000, 1000); 但是,该调用在C++头文件中不可用。

导致冻结的问题是由于使用了未初始化的变量 diffWheels。差速轮(以及机器人和主管)不需要初始化。

您必须将 MyRobot 类的基类更改为差速轮

class MyRobot : public DifferentialWheels

然后简单地打电话

setSpeed(1000, 1000)

而不是

diffWheels->setSpeed(1000, 1000)

您似乎没有初始化diffWheels,所以我想您因取消引用垃圾指针而出现段错误。尝试推杆

diffWheels = new DifferentialWheels;

MyRobot的构造函数中。