FastLED 3.10.8
Loading...
Searching...
No Matches

◆ parseFloat()

float fl::SerialPort::parseFloat ( )

Parse floating-point number from serial input.

Returns
Parsed float value, or 0.0 if no valid float found

Skips non-numeric characters until a number is found, then parses it. Stops at first non-numeric character after the number.

Definition at line 276 of file serial.cpp.hpp.

276 {
277 bool negative = false;
278 long intPart = 0;
279 long fracPart = 0;
280 int fracDigits = 0;
281 bool foundDigit = false;
282 bool inFraction = false;
283 u32 startTime = fl::millis();
284
285 // Skip non-numeric characters
286 while (fl::millis() - startTime < mTimeoutMs) {
287 if (available() > 0) {
288 int c = peek();
289 if (c == -1) {
290 continue;
291 }
292
293 // Check for sign
294 if (c == '-') {
295 negative = true;
296 read(); // Consume the sign
297 break;
298 } else if (c == '+') {
299 read(); // Consume the sign
300 break;
301 } else if (c >= '0' && c <= '9') {
302 break; // Found a digit
303 } else if (c == '.') {
304 break; // Found decimal point
305 } else {
306 read(); // Skip non-numeric character
307 startTime = fl::millis(); // Reset timeout
308 }
309 }
310 }
311
312 // Parse digits (integer and fractional parts)
313 startTime = fl::millis();
314 while (fl::millis() - startTime < mTimeoutMs) {
315 if (available() > 0) {
316 int c = peek();
317 if (c == -1) {
318 continue;
319 }
320
321 if (c == '.' && !inFraction) {
322 inFraction = true;
323 read(); // Consume decimal point
324 foundDigit = true; // Decimal point counts as finding a number
325 startTime = fl::millis(); // Reset timeout
326 } else if (c >= '0' && c <= '9') {
327 if (inFraction) {
328 fracPart = fracPart * 10 + (c - '0');
329 fracDigits++;
330 } else {
331 intPart = intPart * 10 + (c - '0');
332 }
333 read(); // Consume the digit
334 foundDigit = true;
335 startTime = fl::millis(); // Reset timeout
336 } else {
337 break; // Non-digit, stop parsing
338 }
339 }
340 }
341
342 if (!foundDigit) {
343 return 0.0f;
344 }
345
346 // Calculate float value
347 float value = static_cast<float>(intPart);
348 if (fracDigits > 0) {
349 float divisor = 1.0f;
350 for (int i = 0; i < fracDigits; i++) {
351 divisor *= 10.0f;
352 }
353 value += static_cast<float>(fracPart) / divisor;
354 }
355
356 return negative ? -value : value;
357}
int read() FL_NO_EXCEPT
Read next byte from serial input.
int peek() FL_NO_EXCEPT
Peek at next byte without removing it from buffer.
int available() FL_NO_EXCEPT
Check how many bytes are available to read.
constexpr int type_rank< T >::value
fl::u32 millis() FL_NO_EXCEPT
Universal millisecond timer - returns milliseconds since system startup.

References available(), fl::FL_NO_EXCEPT, fl::millis(), mTimeoutMs, peek(), read(), and fl::type_rank< T >::value.

+ Here is the call graph for this function: