加载模型
首先,打开之前创建好的四轮小车模型,本文将写一段代码实现对小车的简单控制。
新建控制器
- 菜单栏向导–>新建机器人控制器,下一步后可以看到将会选一种语言编写控制器,这里我选择C语言
- 接下来选择编辑器,可以选择Webots自己的编辑器,也可以选择VS,这里我就直接用Webots的文本编辑器吧
- - 最后就会在代码区得到
电机控制
- 查看参考手册,可以发现有速度控制,位置控制,这里我进行小车的速度控制
代码
/*
* File: my_controller.c
* Date:
* Description:
* Author:
* Modifications:
*/
/*
* You may need to add include files like <webots/distance_sensor.h> or
* <webots/motor.h>, etc.
*/
#include <webots/robot.h>
#include <webots/motor.h>
//添加电机控制头文件
/*
* You may want to add macros here.
*/
#define TIME_STEP 64
/*
* This is the main program.
* The arguments of the main function can be specified by the
* "controllerArgs" field of the Robot node
*/
int main(int argc, char **argv) {
/* necessary to initialize webots stuff */
wb_robot_init();
/*
* You should declare here WbDeviceTag variables for storing
* robot devices like this:
* WbDeviceTag my_sensor = wb_robot_get_device("my_sensor");
* WbDeviceTag my_actuator = wb_robot_get_device("my_actuator");
*/
//读取电机
WbDeviceTag left_front_motor
= wb_robot_get_device("left_front_motor");
wb_motor_set_position(left_front_motor,INFINITY);
wb_motor_set_velocity(left_front_motor,0);
WbDeviceTag left_back_motor
= wb_robot_get_device("left_back_motor");
wb_motor_set_position(left_back_motor,INFINITY);
wb_motor_set_velocity(left_back_motor,0);
WbDeviceTag right_front_motor
= wb_robot_get_device("right_front_motor");
wb_motor_set_position(right_front_motor,INFINITY);
wb_motor_set_velocity(right_front_motor,0);
WbDeviceTag right_back_motor
= wb_robot_get_device("right_back_motor");
wb_motor_set_position(right_back_motor,INFINITY);
wb_motor_set_velocity(right_back_motor,0);
/* main loop
* Perform simulation steps of TIME_STEP milliseconds
* and leave the loop when the simulation is over
*/
while (wb_robot_step(TIME_STEP) != -1) {
/*
* Read the sensors :
* Enter here functions to read sensor data, like:
* double val = wb_distance_sensor_get_value(my_sensor);
*/
//设置电机速度
wb_motor_set_velocity(left_front_motor,10);
wb_motor_set_velocity(left_back_motor,10);
wb_motor_set_velocity(right_front_motor,0);
wb_motor_set_velocity(right_back_motor,0);
/* Process sensor data here */
/*
* Enter here functions to send actuator commands, like:
* wb_motor_set_position(my_actuator, 10.0);
*/
};
/* Enter your cleanup code here */
/* This is necessary to cleanup webots resources */
wb_robot_cleanup();
return 0;
}