加載模型
首先,打開之前建立好的四輪小車模型,本文将寫一段代碼實作對小車的簡單控制。
建立控制器
- 菜單欄向導–>建立機器人控制器,下一步後可以看到将會選一種語言編寫控制器,這裡我選擇C語言
-
Webots學習筆記(三)---控制器(電機控制)加載模型建立控制器電機控制代碼添加控制器運作仿真 -
接下來選擇編輯器,可以選擇Webots自己的編輯器,也可以選擇VS,這裡我就直接用Webots的文本編輯器吧
-
Webots學習筆記(三)---控制器(電機控制)加載模型建立控制器電機控制代碼添加控制器運作仿真 - 最後就會在代碼區得到
Webots學習筆記(三)---控制器(電機控制)加載模型建立控制器電機控制代碼添加控制器運作仿真
電機控制
- 檢視參考手冊,可以發現有速度控制,位置控制,這裡我進行小車的速度控制
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;
}
- 點選編譯生成目前項目,就可以在調試區看到編譯進度
Webots學習筆記(三)---控制器(電機控制)加載模型建立控制器電機控制代碼添加控制器運作仿真 - 出現這樣,即可
Webots學習筆記(三)---控制器(電機控制)加載模型建立控制器電機控制代碼添加控制器運作仿真 添加控制器
- 在Robot節點下找到controller節點,添加剛剛編譯生成的控制器
Webots學習筆記(三)---控制器(電機控制)加載模型建立控制器電機控制代碼添加控制器運作仿真 - 儲存
運作仿真
Webots學習筆記(三)---控制器(電機控制)加載模型建立控制器電機控制代碼添加控制器運作仿真 - 在Robot節點下找到controller節點,添加剛剛編譯生成的控制器