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! :)
It's because you're using Serial. parseInt() . It uses a timeout to find the end of the data on the serial port, and while it's waiting for that timeout it can do nothing else.
The latency timer controls the time interval between two commands in serial communication. We can confirm this by observing the communications signal on an oscilloscope.
begin(9600)'. This starts serial communication, so that the Arduino can send out commands through the USB connection. The value 9600 is called the 'baud rate' of the connection. This is how fast the data is to be sent.
The default baud rate in Arduino is 9600 bps (bits per second). We can specify other baud rates as well, such as 4800, 14400, 38400, 28800, etc.
Solution was to set:
Serial.setTimeout(50);
Thanks everybody!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With