Wyatt  1.0.1
DriveRobotCommand.cpp
1 //
2 // Created by Tucker Haydon on 4/28/17.
3 //
4 
5 #include "../../include/commands/DriveRobotCommand.h"
6 #include <iostream>
7 using namespace std;
8 
9 DriveRobotCommand::DriveRobotCommand(Communicator* comm, EncoderSensor* leftEncoder, EncoderSensor* rightEncoder, double radius, double rotationRate, int duration_ms, double wheelDiameter, double drivetrainDiameter) : Command() {
10 
11  this->duration_ms = duration_ms;
12 
13  double leftMotorRPM = rotationRate * (radius + drivetrainDiameter/2) * 60.0 / (3.14159 * wheelDiameter);
14  double rightMotorRPM = rotationRate * (radius - drivetrainDiameter/2) * 60.0 / (3.14159 * wheelDiameter);
15  int leftMotorDirection = leftMotorRPM < 0 ? BACKWARD_DIRECTION : FORWARD_DIRECTION;
16  int rightMotorDirection = rightMotorRPM < 0 ? BACKWARD_DIRECTION : FORWARD_DIRECTION;
17 
18  // cout << "radius (cm): " << radius << endl;
19  // cout << "rotation (rad/s): " << rotationRate << endl;
20  // cout << "duration (ms): " << duration_ms << endl;
21  // cout << "wheel diameter (cm): " << wheelDiameter << endl;
22  // cout << "drivetrain diameter (cm): " << drivetrainDiameter << endl;
23  // cout << "Left Motor RPM: " << leftMotorRPM << endl;
24  // cout << "Right Motor RPM: " << rightMotorRPM << endl;
25 
26  this->leftMotorCommand = new DriveMotorRPM(comm, H_LEFT_MOTOR, leftEncoder, fabs(leftMotorRPM), leftMotorDirection);
27  this->rightMotorCommand = new DriveMotorRPM(comm, H_RIGHT_MOTOR, rightEncoder, fabs(rightMotorRPM), rightMotorDirection);
28 }
29 
30 DriveRobotCommand::~DriveRobotCommand() {
31  // Nothing?
32 }
33 
35 
36  // Get the current time in ms
37  struct timeval tp;
38  gettimeofday(&tp, NULL);
39  long long currentTime = (long long) tp.tv_sec * 1000L + tp.tv_usec / 1000;
40 
41  // If the first execution
42  if(this->endTime == -1L) {
43  this->endTime = currentTime + this->duration_ms;
44  }
45 
46  // Drive the motors
47  this->leftMotorCommand->execute();
48  this->rightMotorCommand->execute();
49 
50  if(currentTime >= endTime) {
51  // Does not need to continue
52  return false;
53  } else {
54  // Needs to continue executing
55  return true;
56  }
57 }
58 
59 bool DriveRobotCommand::cleanup(bool canceled) {
60  this->leftMotorCommand->cancel();
61  this->rightMotorCommand->cancel();
62 
63  return true;
64 }
bool execute() override
void cancel()
Definition: Command.cpp:23
DriveRobotCommand(Communicator *comm, EncoderSensor *leftEncoder, EncoderSensor *rightEncoder, double radius, double rotationRate, int duration_ms, double wheelDiameter, double drivetrainDiameter)
Definition: Command.h:6
virtual bool execute()=0
bool cleanup(bool canceled) override