83 lines
2.4 KiB
C++
83 lines
2.4 KiB
C++
#include "MotionController.h"
|
|
|
|
MotionController::MotionController() : board0(0x40), board1(0x41) {}
|
|
|
|
void MotionController::begin() {
|
|
board0.begin(); board0.setPWMFreq(50);
|
|
board1.begin(); board1.setPWMFreq(50);
|
|
// Initialize current position at 90 degrees
|
|
for(int i=0; i<6; i++) {
|
|
for(int j=0; j<3; j++) {
|
|
currentLegF[i][j] = 90.0;
|
|
targetLeg[i][j] = 90.0;
|
|
}
|
|
}
|
|
}
|
|
|
|
void MotionController::update() {
|
|
if (millis() - lastUpdate < 5) return; // 200Hz internal update
|
|
lastUpdate = millis();
|
|
|
|
// Check if we arrived
|
|
bool atTarget = true;
|
|
for(int i=0; i<6; i++) {
|
|
for(int j=0; j<3; j++) {
|
|
if (abs(currentLegF[i][j] - targetLeg[i][j]) > 0.5) atTarget = false;
|
|
}
|
|
}
|
|
|
|
if (atTarget && head != tail) {
|
|
// Pop from buffer and calculate steps
|
|
int next[6][3];
|
|
memcpy(next, buffer[tail].leg, sizeof(next));
|
|
tail = (tail + 1) % 10;
|
|
|
|
int numSteps = _pythonInterval / 5;
|
|
for(int i=0; i<6; i++) {
|
|
for(int j=0; j<3; j++) {
|
|
targetLeg[i][j] = (float)next[i][j];
|
|
stepSize[i][j] = (targetLeg[i][j] - currentLegF[i][j]) / (float)numSteps;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Move current position toward target
|
|
for(int i=0; i<6; i++) {
|
|
for(int j=0; j<3; j++) {
|
|
if (abs(currentLegF[i][j] - targetLeg[i][j]) > abs(stepSize[i][j])) {
|
|
currentLegF[i][j] += stepSize[i][j];
|
|
} else {
|
|
currentLegF[i][j] = targetLeg[i][j];
|
|
}
|
|
}
|
|
}
|
|
writeServos(currentLegF);
|
|
}
|
|
|
|
bool MotionController::pushFrame(int leg[6][3]) {
|
|
int next = (head + 1) % 10;
|
|
if (next == tail) return false;
|
|
memcpy(buffer[head].leg, leg, sizeof(buffer[head].leg));
|
|
head = next;
|
|
return true;
|
|
}
|
|
|
|
void MotionController::setConfigs(int minP, int maxP, int interval) {
|
|
_servoMin = minP;
|
|
_servoMax = maxP;
|
|
_pythonInterval = interval;
|
|
}
|
|
|
|
void MotionController::writeServos(float leg[6][3]) {
|
|
for (int i = 0; i < 6; i++) {
|
|
for (int j = 0; j < 3; j++) {
|
|
int pulse = map((int)leg[i][j], 0, 180, _servoMin, _servoMax);
|
|
if (i < 3) board0.setPWM(i * 3 + j, 0, pulse);
|
|
else board1.setPWM((i - 3) * 3 + j, 0, pulse);
|
|
}
|
|
}
|
|
}
|
|
|
|
int MotionController::degToPulse(int deg) {
|
|
return map(deg, 0, 180, _servoMin, _servoMax);
|
|
} |