logo elektroda
logo elektroda
X
logo elektroda

Conversion of data from char to int array after reading from UART in Arduino

Maryush 1341 11
ADVERTISEMENT
Treść została przetłumaczona polish » english Zobacz oryginalną wersję tematu
  • #1 17241759
    Maryush
    Level 22  
    Posts: 884
    Help: 2
    Rate: 90
    Welcome,

    I have this difficulty, I read the characters coming from the UART and write them to an array of characters defined as char value [] , the array stores values such as voltage, current and power. There are always 9 characters in the array, 3 for each of the given quantities. I want to take 3 characters out of this array and convert them to an int variable in a way I don't know yet. How can I do this? I am writing the program in arduino.
  • ADVERTISEMENT
  • #3 17242995
    Maryush
    Level 22  
    Posts: 884
    Help: 2
    Rate: 90
    This has been successfully done, I am at the stage of converting a string variable to a float. And now after the conversion I have the variable A=27.500, I would like the variable A to have the form and be displayed as A=27.5, that is without these two unnecessary zeros. How can they be removed?
  • ADVERTISEMENT
  • #5 17243045
    Maryush
    Level 22  
    Posts: 884
    Help: 2
    Rate: 90
    I only want to display two decimal places.
  • #6 17243050
    witoldwitoldowicz
    Level 28  
    Posts: 698
    Help: 163
    Rate: 60
    So
    String text= String(A, 2);
  • ADVERTISEMENT
  • #7 17243055
    Maryush
    Level 22  
    Posts: 884
    Help: 2
    Rate: 90
    And what would the function look like if I just wanted to remove those two zeros at the end?
  • ADVERTISEMENT
  • #8 17243103
    witoldwitoldowicz
    Level 28  
    Posts: 698
    Help: 163
    Rate: 60
    Code: C / C++
    Log in, to see the code
    .
  • #9 17243176
    Maryush
    Level 22  
    Posts: 884
    Help: 2
    Rate: 90
    Thank you very much for the code. I've switched from bascom to arduino and somehow can't shift my thinking. Apparently the syntax of this function is simple, but I can't quite understand the mechanism in which it works and in effect removes those unnecessary zeros. Could I still ask for an explanation of how this code works? So briefly.
  • Helpful post
    #10 17243203
    witoldwitoldowicz
    Level 28  
    Posts: 698
    Help: 163
    Rate: 60
    if( if it has something after the comma
    while( as long as the last character is '0'
    remove remove last character
  • #11 17243218
    Maryush
    Level 22  
    Posts: 884
    Help: 2
    Rate: 90
    That's right, thank you for your help.

    One more question, why does this function subtract a one from the length of the string variable if the last character is to be removed?
  • #12 17243933
    krzbor
    Level 29  
    Posts: 1731
    Help: 40
    Rate: 1044
    Maryush wrote:
    .
    Still a question, why is a one subtracted from the length of the string variable in this function if the last character is to be removed?
    .
    Because "length" gives the length of the string, and the elements are indexed from 0. Example: for the string abc, "a" has index 0, "b" - 1, "c"-2, so the last character has index 2, but the length of the text is 3.

Topic summary

✨ The discussion addresses converting a subset of characters read from UART into integer variables in Arduino. The initial solution involves copying three characters into a String object and using the String.toInt() function for conversion. Further elaboration covers converting the resulting string to a float and formatting the output to display a specific number of decimal places. To remove trailing zeros after the decimal point, a method using String manipulation is proposed: converting the float to a String, checking for a decimal point, and iteratively removing trailing '0' characters from the end of the string. The explanation clarifies that string indices start at zero, so removing the last character involves subtracting one from the string length to access the correct index. The discussion references Arduino String class functions such as toInt() and String(val, decimalPlaces) for formatting numeric output.
Generated by the language model.

FAQ

TL;DR: Need to parse UART digits and display floats cleanly? Use "String(A, 2)" to show 2 decimal places; trim trailing zeros if needed. [Elektroda, witoldwitoldowicz, post #17243050] Why it matters: This FAQ helps Arduino users turn UART ASCII readings into ints/floats and display them without unwanted zeros.

Quick Facts

How do I convert three ASCII digits from a UART char array into an int in Arduino?

Copy the three characters into a temporary String, then call toInt() to get a number. This approach is fast and readable. It matches fixed-width fields like 3-digit values. 3-step How-To:
  1. String s = String(buf + start).substring(0, 3)
  2. long n = s.toInt()
  3. Use n as your integer This suits 3-digit slices for voltage/current/power. [Elektroda, witoldwitoldowicz, post #17241848]

What’s the quickest way to display a float with exactly two decimal places?

Use the String constructor with precision: String(A, 2). It converts the float to text with two decimals. This is ideal for UI output and logs. You can then print or display the resulting String. "String text= String(A, 2);" demonstrates the exact call. [Elektroda, witoldwitoldowicz, post #17243050]

How can I remove trailing zeros so 27.500 prints as 27.5?

Convert the value to a String, check for '.', then remove trailing '0' characters. Keep looping until the last character is no longer '0'. Add a final check if you want to remove a trailing '.' too. "while( as long as the last character is '0' )" describes the core idea. [Elektroda, witoldwitoldowicz, post #17243203]

Why do examples use length-1 to access the last character of a String?

String indices start at 0, but length gives a count starting at 1. For "abc", indices are 0:'a', 1:'b', 2:'c'. The last index is therefore length-1. Use that index when trimming or peeking the final character. [Elektroda, krzbor, post #17243933]

How do I split a 9-character UART payload into three values?

Treat the payload as three fixed fields. Slice [0..2] for voltage, [3..5] for current, and [6..8] for power. Convert each 3-character slice using String(...).toInt(). This works because the packet length is 9 (3 characters per value). [Elektroda, Maryush, post #17241759]

What happens if String.toInt() fails to find digits?

String.toInt() returns 0 when no valid conversion can be performed. This is a common failure signal, so 0 can mean either a real zero or an error. Validate your slice contains digits (and an optional leading '-') before conversion. Or use a sentinel or bounds check to distinguish cases. [String.toInt()]

Can I limit trimming to zeros only when a decimal point exists?

Yes. First confirm the String contains '.' using indexOf('.'). Then loop removing trailing '0' characters. This prevents deleting zeros from integer strings. Optionally, if the last char becomes '.', remove it too. [Elektroda, witoldwitoldowicz, post #17243103]

Is there a one-liner to print two decimal places without building a String?

Yes. Use Serial.print(A, 2) or Serial.println(A, 2) to print a float with two decimals. This avoids intermediate Strings and reduces memory churn. It’s handy for quick debugging or streaming over USB/UART. [Serial.print()]

How should I slice substrings correctly when grabbing three digits?

Use substring(start, end) with end exclusive. For characters at positions 3, 4, 5 call substring(3, 6). Then convert the result with toInt(). Remember zero-based indexing when computing start and end. [StringObject]

My sensor uses a decimal comma. How can I parse that on Arduino?

Replace commas with dots before converting. For example: s.replace(',', '.'); then parse with toFloat() or manage the integer and fractional parts. This normalization step makes parsing consistent across locales. [StringObject]

Should I use Serial.parseInt() instead of manual slicing?

Use Serial.parseInt() when numbers are separated by non-digits or whitespace. It scans the stream for the next integer automatically. Manual slicing is better when your packet is fixed-width, like 3-digit fields. Choose based on your input format. [Serial.parseInt()]

Will building Strings for parsing impact memory on Arduino Uno?

The Uno has 2 KB of SRAM, so frequent or large String operations can consume memory quickly. Prefer short-lived, fixed-size operations when possible. For stable streams with fixed-width fields, slice and convert promptly. Monitor free memory during development. [Arduino Uno Rev3]
Generated by the language model.
ADVERTISEMENT