FastLED 3.9.15
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 279 of file serial.cpp.hpp.

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

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

+ Here is the call graph for this function: