8
votes

Just trying some things out, as I want to use my Arduino Nano as an interface to my computer with a couple of LED's and buttons. So I need to send some commands and data to the Arduino from my PC. However i find the serial communication of the Arduino quite slow. In fact, from the moment I press Enter to send, my command in the Serial Monitor takes almost a second to execute (in this case to control an LED).

Is this a limitation or can it be sped up somehow?

Here's my simple code:

String cmd;
int loopNum;
int ledPin = 13;

void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}

void loop() {

if(loopNum == 0) {
Serial.println("Waiting for commands"); // Only display this when sketch is initiated. 
}

cmd = Serial.readString();

if(cmd == "LEDON") {
digitalWrite(ledPin, HIGH);
Serial.println("LED ON");
}
if(cmd == "LEDOFF") {
digitalWrite(ledPin, LOW);
Serial.println("LED OFF");
}
if(cmd == "HELP") {
Serial.println("Available commands:\nLEDON\nLEDOFF\nHelp");
}

loopNum++; // Counts the loop...
delay(50);
}

Changing the baud rate of the serial doesn't seem to change anything.

Some help would be appreciated! :)

3
You are not checking if there's anything to read when you call Serial.readString(). You discovered that the default for Serial.setTimeout() is 1000 milliseconds.Hans Passant

3 Answers

30
votes

Solution was to set:

Serial.setTimeout(50)

Thanks everybody!

2
votes

In my opinion, to improve your program, you have to modify your code as:

String cmd;
int ledPin = 13;

void setup() {
    Serial.begin(9600);
    pinMode(ledPin, OUTPUT);
    Serial.println("Waiting for commands"); // Only display this when sketch is initiated. 
}

void loop() {
    if (Serial.available()) {
        cmd = Serial.readString(); //Assign cmd just if someone send string in serial monitor

        if(cmd == "LEDON") {
            digitalWrite(ledPin, HIGH);
            Serial.println("LED ON");
        }
        if(cmd == "LEDOFF") {
            digitalWrite(ledPin, LOW);
            Serial.println("LED OFF");
        }
        if(cmd == "HELP") {
            Serial.println("Available commands:\nLEDON\nLEDOFF\nHelp");
        } 
    } //Serial.available()
}

I suppose that you don't need to count the loop (there's no reason why you have to do it, improving delay). Using Serial.available() function help you to check if statements just if someone is send a string in the serial monitor (reducing your delay). At last, to print something just one time in your program, you could put it into the Setup() function.

-2
votes

When you send a string from the serial monitor, it sends all the strings one by one. So if you send 'LEDON' it will transfer 5 characters one by one serially. Thats why it takes some time in execution.