Hello,
I use below lines to get data from VisualBasic (visual studio 2022) .
It works ... but it takes the conversion "num = data.toInt" 2 (two seconds) to continue.
Why is this and what can I do to get this (much)faster?
if(Serial.available()) {
String data = Serial.readString();
num = data.toInt();
if( num < 32 && num >15 ){
//trein[0] = num;
// and so on .....
}
It isn't the data.toInt() that takes the time. Serial.readString() is timing out because that's the way it always works. Try Serial.readStringUntil('\r').
Although, the Serial timeout defaults to 1 second, so not sure why you are seeing a 2 second delay.
You could also try Serial.parseInt(), which combines Serial.readString() and string.toInt() into a single function.
if(Serial.available()) {
num = Serial.parseInt();
if( num < 32 && num >15 ){
//trein[0] = num;
// and so on .....
}
The reason your code is slow (about 2 seconds delay) is because of this line:
String data = Serial.readString();
The readString() function waits for the entire string to be received and also waits until the serial timeout period ends, even if data has already arrived. By default, this timeout is 1000 ms, so if it gets triggered more than once, you can easily see delays like 2 seconds.
If you're sending a newline character (\n) at the end of your data from Visual Basic, use:
String data = Serial.readStringUntil('\n'); // much faster