Using a Sin wave to control BLDC motor

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?

So you could save the millis() value in the moment of command arriving as, say, start variable and then use a difference between start and millis rather than millis itself.

1 Like

Thank you sir.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.