//<script src="https://gist.github.com/big-penguin/9a431b6dfe91d4c5e97902a7db3160e7.js"></script>
#include <SimpleFOC.h>
// Stepper motor instance
StepperMotor motor = StepperMotor(19, 21, 22, 23, 50);
// encoder instance
Encoder encoder = Encoder(5, 18, 400);
// Interrupt routine intialisation
// channel A and B callbacks
void doA(){encoder.handleA();}
void doB(){encoder.handleB();}
void setup() {
/* LPF velocity| Tf: 0.70
PID velocity| P: 3.00
PID velocity| I: 0.10
PID velocity| D: 0.00 */
// initialize encoder sensor hardware
encoder.init();
encoder.enableInterrupts(doA, doB);
// link the motor to the sensor
motor.linkSensor(&encoder);
// choose FOC modulation
motor.foc_modulation = FOCModulationType::SpaceVectorPWM;
// power supply voltage [V]
motor.voltage_power_supply = 12;
// set control loop type to be used
motor.controller = ControlType::voltage;
// contoller configuration based on the controll type
motor.PID_velocity.P = 0.2;
motor.PID_velocity.I = 20;
motor.PID_velocity.D = 0;
// default voltage_power_supply
motor.voltage_limit = 12;
// velocity low pass filtering time constant
motor.LPF_velocity.Tf = 0.01;
// angle loop controller
motor.P_angle.P = 20;
// angle loop velocity limit
motor.velocity_limit = 5;
// use monitoring with serial for motor init
// monitoring port
Serial.begin(115200);
// comment out if not needed
motor.useMonitoring(Serial);
// initialise motor
motor.init();
// align encoder and start FOC
motor.initFOC();
// set the inital target value
motor.target = 2;
// Run user commands to configure and the motor (find the full command list in docs.simplefoc.com)
Serial.println("Motor commands sketch | Initial motion control > torque/voltage : target 2V.");
_delay(1000);
}
void loop() {
// iterative setting FOC phase voltage
motor.loopFOC();
// iterative function setting the outter loop target
// velocity, position or voltage
// if tatget not set in parameter uses motor.target variable
motor.move();
// user communication
motor.command(serialReceiveUserCommand());
}
// utility function enabling serial communication the user
String serialReceiveUserCommand() {
// a string to hold incoming data
static String received_chars;
String command = "";
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the string buffer:
received_chars += inChar;
// end of user input
if (inChar == '\n') {
// execute the user command
command = received_chars;
// reset the command buffer
received_chars = "";
}
}
return command;
}