在设计机器人的控制器时无法避免的会用到很多的矩阵相关的运算,为了提高效率,采用开源矩阵运算库是比较合适的。
本文选用Eigen库作为控制器矩阵和矢量运算,数值分析及其相关的算法的运算库。
使用VSCode作为Webots控制器IDE的配置过程参看上一篇博客。
本文介绍如何在上述VSCode作为Webots控制器IDE的基础上添加Eigen库作为控制器的矩阵运算库,配置完成后的效果如下图所示。
直接去Eigen官方网站下载最新的稳定版本
由于是在Windows上使用所以直接下载ZIP格式,下载完成后解压到即可。
打开Webots生成的C++控制器的Makefile文件,在其中添加如下内容,D:/eigen-3.4.0/Eigen为解压后Eigen的目录
### ---- Linked libraries ---- ### if your program needs additional libraries: INCLUDE = -I D:/eigen-3.4.0/Eigen ### LIBRARIES = -L D:/eigen-3.4.0/Eigen/src/Core -lMatrix ### ### ---- Linking options ---- ### if special linking flags are needed: ### LFLAGS = -s ### ### ---- Webots included libraries ---- ### if you want to use the Webots C API in your C++ controller program: ### USE_C_API = true ###3.在VSCode的c_cpp_properties.json文件中链接库
经过在Makefile文件中添加Eigen库,即可通过编译正常使用Eigen库,但此时在VSCode中对代码进行修改时并不具备自动补全功能,因此需要在c_cpp_properties.json文件中配置Eigen库路径
{
"configurations": [
{
"name": "Win32",
"includePath": [
"D:\Program Files\Webots\include\controller\cpp",
"D:\eigen-3.4.0\Eigen" //Eigen库目录
// "D:\eigen-3.4.0\Eigen\src\Core"
],
"defines": [
"${default}"
],
"macFrameworkPath": [
"${default}"
],
"forcedInclude": [
"${default}"
],
"compileCommands": "${default}",
"browse": {
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": "${default}",
"path": [
"${default}",
"D:\Program Files\Webots\lib\controller",
"D:\eigen-3.4.0\Eigen" //Eigen库目录
//"D:\eigen-3.4.0\Eigen\src\Core"
]
},
"intelliSenseMode": "gcc-x64",
"cStandard": "c11",
"cppStandard": "c++17",
"compilerPath": "C:\mingw64\bin\g++.exe"
}
],
"version": 4
}
4.头文件中包含并声明namespace
#ifndef __MAIN_H #define __MAIN_H #include "driver.h" #include5.调用using namespace Eigen; #endif
#include "main.h"
int main(int argc, char **argv)
{
Matrix matrix_A;
Matrix matrix_B;
Matrix matrix_C;
matrix_A << 1, 2,
3, 4;
matrix_B(0, 0) = 0.5;
matrix_B(0, 1) = 0;
matrix_B(1, 0) = 0;
matrix_B(1, 1) = 0.5;
matrix_C = matrix_A * matrix_B;
cout << matrix_C;
cout << endl;
cout << "Hello" << endl;
Supervisor *robot = new Supervisor();
Driver *MyDriver = new Driver(robot,500,1000,0.8,6,0.2);
while (robot->step(MyDriver->timeStep) != -1)
{
};
delete robot;
pthread_exit(NULL);
return 0;
}
经过上述配置后即可调用Eigen库解决矩阵运算问题,如上述测试代码输出结果为
0.5 1 1.5 2 Hello



