Robots suiveurs 3 - Code Communication Intermédiaire (maître)
Sauter à la navigation
Sauter à la recherche
#include <webots/Robot.hpp>
#include <webots/Emitter.hpp>
#include <webots/Receiver.hpp>
#include <webots/Motor.hpp>
#include <webots/Keyboard.hpp>
#include <stdio.h>
#include <string.h>
#define COMMUNICATION_CHANNEL 1
#define MAX_SPEED 6.28
// 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();
//get a handler to the peripherials
Motor *left_motor = robot->getMotor("left wheel motor");
Motor *right_motor = robot->getMotor("right wheel motor");
Emitter *emitter = robot->getEmitter("emitter");
//Motor initialisation
left_motor->setVelocity(0);
right_motor->setVelocity(0);
left_motor->setPosition(INFINITY);
right_motor->setPosition(INFINITY);
// get the time step of the current world.
int timeStep = (int)robot->getBasicTimeStep();
//if wrong channel
const int channel = emitter->getChannel();
if (channel != COMMUNICATION_CHANNEL)
{
emitter->setChannel(COMMUNICATION_CHANNEL);
}
emitter->setRange(0.4); //Defines the emitters range
//get a handler to the keybord and enables it
Keyboard keyboard = Keyboard();
keyboard.enable(50);
// Main loop:
while (robot->step(timeStep) != -1)
{
/* send null-terminated message */
const char *message = "Hello!";
emitter->send(message, strlen(message) + 1);
//Keybord control
int key = keyboard.getKey();
if (key == -1) {
left_motor->setVelocity(0);
right_motor->setVelocity(0);
}
while (key > 0) {
switch (key) {
case 'Z':
left_motor->setVelocity(MAX_SPEED);
right_motor->setVelocity(MAX_SPEED);
break;
case 'S':
left_motor->setVelocity(-MAX_SPEED);
right_motor->setVelocity(-MAX_SPEED);
break;
case 'Q':
left_motor->setVelocity(-0.49*MAX_SPEED);
right_motor->setVelocity(0.49*MAX_SPEED);
break;
case 'D':
left_motor->setVelocity(0.49*MAX_SPEED);
right_motor->setVelocity(-0.49*MAX_SPEED);
break;
case 'A':
left_motor->setVelocity(0.5*MAX_SPEED);
right_motor->setVelocity(0.75*MAX_SPEED);
break;
case 'E':
left_motor->setVelocity(0.75*MAX_SPEED);
right_motor->setVelocity(0.5*MAX_SPEED);
break;
default:
left_motor->setVelocity(0);
right_motor->setVelocity(0);
break;
}
key = keyboard.getKey();
}
}
// Enter here exit cleanup code.
delete robot;
return 0;
}