2016/09/20

Arduino - Converting floating number into string using the dtostrf() function

This is a quick example of how to convert floating number to string in Arduino using the dtostrf() function.

Code




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//#include <stdlib.h>

char char_f[8];
String str_f;
float f;
      
void setup() {
  Serial.begin(9600); // Starts the serial communication
}

void loop() {
  f = 0.0;

  while (f <= 200.00) {
         f = f + 1.11;

         Serial.print("Floating Number:");
         Serial.print(f);
         Serial.print("- ");

         //
         //http://www.atmel.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1ga060c998e77fb5fc0d3168b3ce8771d42.html
         dtostrf(f, 7, 2, char_f);
         
         str_f = "";
         for (int i = 0; i < sizeof(char_f); i++) {
             str_f += char_f[i];
         }

         Serial.print("String Number:");
         Serial.print(str_f);
         Serial.println("-");
         
  }

  f = 0.0;
  
  while (f >= -200.00) {
         f = f - 1.1;

         Serial.print("Floating Number:");
         Serial.print(f);
         Serial.print("- ");

         dtostrf(f, 6, 2, char_f);
         
         str_f = "";
         for (int i = 0; i < sizeof(char_f); i++) {
             str_f += char_f[i];
         }

         Serial.print("String Number:");
         Serial.print(str_f);
         Serial.println("-");
  }
    
}

Output


References:

Converting Float to string and character array in a few simple steps - arduino
http://www.instructables.com/id/Converting-Float-to-string-and-character-array-in-/?ALLSTEPS

Conversion functions for double arguments.
http://www.atmel.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1ga060c998e77fb5fc0d3168b3ce8771d42.html

Float to Binary Conversion
http://www.binaryconvert.com/convert_float.html?decimal=045049

Part 2: Sending numeric data using App Inventor Bluetooth communications
http://appinventor.pevest.com/?p=569

No comments:

Post a Comment