I am trying to send commands from MATLAB to Arduino to let BLDC motor perform sinusoidal motion. Here is my Arduino program to control the motor to do sinusoidal motion in 4 second cycles, and it runs fine.
float ang;
float pos;
int mode;
void setup() {
Serial.begin(9600);
}
void loop() {
char rc;
rc = Serial.read();
if (rc == '1') {
mode = 1;
Serial.println("Position Mode");
}
if (rc == '0') {
mode = 0;
Serial.println("Stop");
}
if (mode == 1) {
ang = 20.0 * sin(millis() / 4000.0 * 6.283); // sin wave equation
pos = ang; // motor position
Serial.println(pos);
}
if (mode == 0) {
pos = pos;
}
}
But the only problem is that my project needs to start controlling the motor only after MATLAB sends the command. Since the millis() function start counting after Arduino is started. So if I send a command after Arduino has been started for some time, the motor will suddenly rotate to a particular angle based on the timer.
I want the motor to rotate from the initial position only after I enter the command. Any suggestions on how to do this?