#include "ClearCore.h"
#define motor ConnectorM0
#define baudRate 9600
#define SerialPort ConnectorUsb
double maxVelocity = 2000;
double torqueLimit = 100.0;
double torqueLimitAlternate = 10.0;
double pwmDeadBand = 2.0;
bool CommandVelocity(int32_t commandedVelocity);
bool LimitTorque(double limit);
int main() {
Connector::CPM_MODE_A_PWM_B_PWM);
SerialPort.Mode(Connector::USB_CDC);
SerialPort.Speed(baudRate);
uint32_t timeout = 5000;
SerialPort.PortOpen();
while (!SerialPort &&
Milliseconds() - startTime < timeout) {
continue;
}
motor.EnableRequest(true);
SerialPort.SendLine("Motor Enabled");
SerialPort.SendLine("Waiting for motor to reach speed...");
continue;
}
SerialPort.SendLine("Motor Ready");
while (true) {
CommandVelocity(100);
CommandVelocity(300);
LimitTorque(70);
CommandVelocity(-200);
LimitTorque(15);
CommandVelocity(-300);
LimitTorque(100);
CommandVelocity(100);
}
}
bool CommandVelocity(int32_t commandedVelocity) {
if (abs(commandedVelocity) > maxVelocity) {
SerialPort.SendLine("Move rejected, invalid velocity requested.");
return false;
}
SerialPort.Send("Commanding velocity: ");
SerialPort.SendLine(commandedVelocity);
double rangeUnsigned = 127.5 - (pwmDeadBand / 100 * 255);
double scaleFactor = rangeUnsigned / maxVelocity;
double dutyRequest;
if (commandedVelocity < 0) {
dutyRequest = 127.5 - (pwmDeadBand / 100 * 255)
+ (commandedVelocity * scaleFactor);
}
else if (commandedVelocity > 0) {
dutyRequest = 127.5 + (pwmDeadBand / 100 * 255)
+ (commandedVelocity * scaleFactor);
}
else {
dutyRequest = 128.0;
}
motor.MotorInBDuty(dutyRequest);
SerialPort.SendLine("Velocity Commanded");
return true;
}
bool LimitTorque(double limit) {
if (limit > torqueLimit || limit < torqueLimitAlternate) {
SerialPort.SendLine("Torque limiting rejected, invalid torque requested.");
return false;
}
SerialPort.Send("Limit torque to: ");
SerialPort.Send(limit);
SerialPort.SendLine("%.");
double scaleFactor = 255 / (torqueLimit - torqueLimitAlternate);
uint8_t dutyRequest = (torqueLimit - limit) * scaleFactor;
motor.MotorInADuty(dutyRequest);
return true;
}