Webot機器人仿真平臺(七) 鍵盤控制小車

上一篇博客中我們利用距離傳感器讓小車在環境中實現避障行走,但是在實際的使用情況下我們更加希望讓小車按我們指定的路線行進,即遙控小車行走,在這篇博客中我們使用鍵盤上的方向鍵控制小車前後左右運動,實現遙控操作機器人或者小車。

1. 新建C++控制器

新建一個C++控制器並命名爲 keyboard ,將以下代碼填入 keyboard.cpp中然後編譯
在這裏插入圖片描述
控制器代碼:

#include <webots/Robot.hpp>
#include <webots/DistanceSensor.hpp>
#include <webots/Motor.hpp>
#include <webots/Keyboard.hpp>
#include <stdio.h>

#define TIME_STEP 64
// All the webots classes are defined in the "webots" namespace
using namespace webots;
 
int main(int argc, char **argv) {
  // create the Robot instance.
  Robot *robot = new Robot();
  Keyboard kb;
  
  DistanceSensor *ds[2];
  char dsNames[2][10] = {"ds_right","ds_left"};
  for (int i = 0; i < 2; i++) {
    ds[i] = robot->getDistanceSensor(dsNames[i]);
    ds[i]->enable(TIME_STEP);
  }

  // initialise motors
  Motor *wheels[4];
  char wheels_names[4][8] = {"wheel1", "wheel2", "wheel3", "wheel4"};
  for (int i = 0; i < 4; i++) {
    wheels[i] = robot->getMotor(wheels_names[i]);
    wheels[i]->setPosition(INFINITY);
    wheels[i]->setVelocity(0);
  }
  printf("init successd ...\n");
  
  kb.enable(TIME_STEP);
  double leftSpeed = 0.0;
  double rightSpeed = 0.0;

   // Main loop:
  // - perform simulation steps until Webots is stopping the controller
  while (robot->step(TIME_STEP) != -1)
   {
    int key = kb.getKey();
    if(key== 315)
    {
      leftSpeed = 3.0;
      rightSpeed = 3.0;
    }
    else if(key== 317)
    {
      leftSpeed = -3.0;
      rightSpeed = -3.0;
    }
    else if(key== 314)
    {
      leftSpeed = -3.0;
      rightSpeed = 3.0;
    }
    else if(key== 316)
    {
      leftSpeed = 3.0;
      rightSpeed = -3.0;
    }
    else  
    {
      leftSpeed = 0.0;
      rightSpeed = 0.0;
    }
    std::cout<< " Right Sensor Value:" <<ds[0]->getValue() << "  Left Sensor Value:" <<ds[1]->getValue() <<std::endl;  
     
     
     wheels[0]->setVelocity(leftSpeed);
     wheels[1]->setVelocity(rightSpeed);
     wheels[2]->setVelocity(leftSpeed);
     wheels[3]->setVelocity(rightSpeed);
  };

  // Enter here exit cleanup code.

  delete robot;
  return 0;
}

隨後對控制器進行編譯。利用我們之前博客(Webot機器人仿真平臺(五) 新建四輪小車模型)建立的四輪小車做實驗,爲小車指定我們新構建的控制器

在這裏插入圖片描述

2. 代碼說明

這裏我們使用的是C++版本的控制器,控制器的接口函數與C的類似,只是換成了類變量操作方式。程序思路是讀取鍵盤方向鍵的鍵值,判斷是哪一個按鍵按下,根據按鍵值設置小車左右車輪的速度。

其中以下兩行代碼爲初始化鍵盤

 Keyboard kb;
  kb.enable(TIME_STEP);

kb.getKey()函數爲讀取按鍵值

int key = kb.getKey();

3. 演示效果

下圖是一個利用鍵盤方向鍵控制小車前後左右移動的效果
在這裏插入圖片描述

參考資料

[1] 1https://cyberbotics.com/doc/reference/index?version=R2020a-rev1
[2] https://www.cyberbotics.com/doc/reference/motion

如果大家覺得文章對你有所幫助,請大家幫忙點個贊。O(∩_∩)O

歡迎大家在評論區交流討論([email protected]

上一篇:Webot機器人仿真平臺(六) 新建四輪小車控制器

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章