Callback function to serial avaiable.

Hi,

I’m writing a sketch to control a BLDC motor from HD.

The circuit is already up and running.
(http://www.c2o.pro.br/en/automation/download/BLDC_controller_4_wires_II.png)

Now I want to optimize the code to increase speed.

I want a program to receive commands from PC (start and stop) through the serial port to control the motor drive.

I Implemented a while loop in the start () function to control the motor:

void start() {

while(running) {
stepping(1);
delay(steppingDelay);
stepping(2);
delay(steppingDelay);
stepping(3);
delay(steppingDelay);
if (steppingDelay > 4) {
steppingDelay = steppingDelay - 1;

}
checkSerial();
}

}

Is there any way to make the update of the boolean variable “running” without to call the function “checkSerial” at the end of each while loop?

Some callback function to be called “only” when there is a complete message in serial.

Thanks for the tips.

Markos

PS-
void checkSerial() {

if (Serial.available() > 0) {

for (int i = 0; i < 7; i++) {
message = 0;

  • } *

  • delay(6);*

  • length_message = Serial.available();*

  • if (length_message >= 7) {*

  • Serial.print(“message larger than the limit (7 characters)!”);*

  • Serial.println(length_message);*

  • for (int i = 0; i < length_message; i++) {*

  • c = Serial.read();*

  • }*

  • } else {*

  • for (int i = 0; i < length_message; i++) {*

  • c = Serial.read();*

  • if (c != ‘\n’ && c != ‘\r’) {*
    _ message = c;_
    * }*
    * }*

* length = strlen(message);*

* message[length] = ‘\0’; // message[length] = 0*

* if ( (strcmp(message, “START”) == 0) || (strcmp(message, “start”) == 0) ) {*
* Serial.println(“Starting”);*
* running = true;*

* } else if (strcmp(message, “STOP”) == 0 || strcmp(message, “stop”) == 0) {*
* Serial.println(“Stopping”);*
* running = false;*

* } else {*
* Serial.print(message);*
* Serial.println(" - Unknown command!");*

* }*
* }*
* }*

}

Hello,

You want to increase speed, yet you are using delays and while loop... :)

Read this: http://gammon.com.au/serial

And also read about "Blink without delay", for non blocking code.

Your problem is not with checkSerial(). It is the use of the delay() function. Look at the demo code in the first post of this Thread shows how to manage timing without using delay().

If you know how many characters will be sent you could use if Serial.available(numChars) as a quick check. But it is easy to integrate reading bytes one at a time with other stuff.

...R