73 lines
1.7 KiB
C++
Raw Normal View History

2022-11-03 08:54:35 +01:00
#include "control_module.h"
2023-01-04 21:47:54 +01:00
ControlModule::ControlModule(): ControlModule(1.0, 1.0, 1.0)
{
2022-12-14 12:30:54 +01:00
}
ControlModule::ControlModule(float forwardSpeed, float rotateSpeed, float moveSideSpeed)
2022-11-03 08:54:35 +01:00
{
2023-01-04 21:47:54 +01:00
motors[0] = 0.0;
motors[1] = 0.0;
motors[2] = 0.0;
motors[3] = 0.0;
2022-12-14 12:30:54 +01:00
this->forwardSpeed = forwardSpeed;
this->rotateSpeed = rotateSpeed;
this->moveSideSpeed = moveSideSpeed;
2022-11-03 08:54:35 +01:00
}
ControlModule::~ControlModule()
{
2022-12-14 12:30:54 +01:00
}
void ControlModule::moveForward(){
2023-01-04 21:47:54 +01:00
for(int i = 0; i < 4; i++){
2022-12-14 16:14:00 +01:00
motors[i] += forwardSpeed;
2022-12-14 12:30:54 +01:00
}
};
2022-12-14 16:14:00 +01:00
void ControlModule::moveSide(int imageColumsMiddle, int contourColumsMiddle){
2023-01-04 21:47:54 +01:00
float speed = moveSideSpeed * static_cast<float>(contourColumsMiddle - imageColumsMiddle)/static_cast<float>(imageColumsMiddle);
2022-12-14 16:14:00 +01:00
motors[0] += speed;
motors[1] -= speed;
motors[2] -= speed;
motors[3] += speed;
}
2022-12-14 12:30:54 +01:00
2022-12-14 16:14:00 +01:00
void ControlModule::rotate(int angle){
2023-01-04 21:47:54 +01:00
float speed = rotateSpeed * (static_cast<float>(angle) + 90.0f)/90.0f;
2022-12-14 16:14:00 +01:00
motors[0] += speed;
motors[1] -= speed;
motors[2] += speed;
motors[3] -= speed;
2022-12-14 12:30:54 +01:00
}
2022-12-14 16:14:00 +01:00
void ControlModule::unit(){
2023-01-04 21:47:54 +01:00
float max = 1.0E-6;
2022-12-14 16:14:00 +01:00
for(int i = 0; i <= sizeof(motors)/sizeof(int); i++){
if(motors[i] > max)
max = motors[i];
}
2023-01-04 21:47:54 +01:00
//Avoid dividing by zero
if (max > 0.001)
{
for(int i = 0; i < 4; i++){
motors[i] /= max;
}
2022-12-14 16:14:00 +01:00
}
2023-01-04 21:47:54 +01:00
2022-12-14 16:14:00 +01:00
}
2022-12-14 12:30:54 +01:00
2022-12-14 16:14:00 +01:00
void ControlModule::calcSpeeds(int imageColumsMiddle, int contourColumsMiddle, int angle){
2023-01-04 21:47:54 +01:00
std::unique_lock<std::mutex> lock(mtx);
2022-12-14 16:14:00 +01:00
moveForward();
moveSide(imageColumsMiddle, contourColumsMiddle);
rotate(angle);
unit();
2023-01-04 21:47:54 +01:00
}
std::vector<float> ControlModule::readMotors()
{
std::unique_lock<std::mutex> lock(mtx);
return std::vector<float> {motors[0], motors[1], motors[2], motors[3]};
}