RoboidControl-cpp/DiscreteAngle.cpp
2024-03-05 09:55:07 +01:00

51 lines
1.3 KiB
C++

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0.If a copy of the MPL was not distributed with this
// file, You can obtain one at https ://mozilla.org/MPL/2.0/.
#include "DiscreteAngle.h"
#include <math.h>
template <> AngleUsing<unsigned char>::AngleUsing(unsigned char angle) {
if (!isfinite(angle)) {
value = 0;
return;
}
// clamp the float range to -1..1
while (angle <= -180.0F)
angle += 360.0F;
while (angle > 180.0F)
angle -= 360.0F;
// map (-180..180] to 1..256
// This means that range value 0 is not used
this->value = (unsigned char)((angle + 180.0F) * 255.0F);
}
template <> float AngleUsing<unsigned char>::ToFloat() {
float f = ((float)this->value / 255.0F) - 180.0F;
return f;
}
template <> AngleUsing<unsigned short>::AngleUsing(unsigned short angle) {
if (!isfinite(angle)) {
value = 0;
return;
}
// clamp the float range to -1..1
while (angle <= -180.0F)
angle += 360.0F;
while (angle > 180.0F)
angle -= 360.0F;
// map (-180..180] to 1..256
// This means that range value 0 is not used
this->value = (unsigned short)((angle + 180.0F) * 65535.0F);
}
template <> float AngleUsing<unsigned short>::ToFloat() {
float f = ((float)this->value / 65535.0F) - 180.0F;
return f;
}