Serial command Decode delay

hello, everyone,

I was writing code for home automation consist of 2 relays and 3 light dimmer with zero cross detection when I send key on the serial monitor
‘A’ switches on relay1

‘a’ switches off relay1

‘B’ switches on relay2

‘b’ switches off relay2

for changing the brightness of three light dimmer I was using an identifier such as X for dimmer1 Y,Z followed by an integer to change the brightness

eg X10-dimmer1 with 10% brightness

i have used following code reading stream function takes data to string variable if data length is 1relay will be turned on if data length is less than 5 it will parse int with respective to the identifier dimmer brightness will adjust

the problem I was facing was whenever data sent through serial it taking 1second of time is there any execution delay happening in read stream function can it be implemented better?

please let me know thoughts

elear_homeautomation.ino (2.5 KB)

Serial.readString() will block for the duration set by Serial.setTimeout(). If you have not set a timeout duration then it will wait the default 1000 ms. Better is to use Serial.readStringUntil(). This is still subject to the timeout duration, but it will immediately return if it finds the specified terminator character.

More information:

Or use Serial.parseInt() and turn on line endings. The parseInt() will not only do the conversion to integer but will also return immediately on finding a non-digit (like a line ending).

Have a look at the examples in Serial Input Basics - simple reliable, non-blocking ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.