2013-08-13 14 views
14

Arduinoプログラムで私はGPSを使ってarduinoに座標を送信しています。このため、着信座標は文字列として格納されます。 GPS座標を浮動小数点または整数に変換する方法はありますか?Stringをfloatまたはintに変換するにはどうすればよいですか?

私はint gpslong = atoi(curLongitude)float gpslong = atof(curLongitude)を試みたが、彼らの両方の原因のArduinoがエラーを与える:

error: cannot convert 'String' to 'const char*' for argument '1' to 'int atoi(const char*)' 

誰もが何か提案がありますか?

答えて

22

あなただけStringオブジェクト(例えばcurLongitude.toInt())にtoIntを呼び出すことにより、Stringからintを得ることができます。

あなたがfloatをしたい場合は、toCharArray方法と併せてatofを使用することができます:sscanf(curLongitude, "%i", &gpslong)またはsscanf(curLongitude, "%f", &gpslong)について

char floatbuf[32]; // make this at least big enough for the whole string 
curLongitude.toCharArray(floatbuf, sizeof(floatbuf)); 
float f = atof(floatbuf); 
+1

オーバーライド:が正しくおかげで動作します。この場合、どのようにtoCharArrayを正確に使用しますか?私はそれを把握していないようだ。 – Xjkh3vk

+0

@ Xjkh3vk:例を追加しました。 – nneonneo

0

どのように?文字列の見た目によっては、もちろんフォーマット文字列を変更する必要があるかもしれません。

2

c_str()は、文字列バッファconst char * pointerを提供します。

変換関数を使用することができます:。 ArduinoのIDEでロングに
int gpslong = atoi(curLongitude.c_str())
float gpslong = atof(curLongitude.c_str())

+0

これらはArduino 'String'sであり、C++' string'sではありません。 – nneonneo

0

変換文字列:

//stringToLong.h 

    long stringToLong(String value) { 
     long outLong=0; 
     long inLong=1; 
     int c = 0; 
     int idx=value.length()-1; 
     for(int i=0;i<=idx;i++){ 

      c=(int)value[idx-i]; 
      outLong+=inLong*(c-48); 
      inLong*=10; 
     } 

     return outLong; 
    } 
-2
String stringOne, stringTwo, stringThree; 
int a; 

void setup() { 
    // initialize serial and wait for port to open: 
    Serial.begin(9600); 
    while (!Serial) { 
    ; // wait for serial port to connect. Needed for native USB port only 
    } 

    stringOne = 12; //String("You added "); 
    stringTwo = String("this string"); 
    stringThree = String(); 
    // send an intro: 
    Serial.println("\n\nAdding Strings together (concatenation):"); 
    Serial.println();enter code here 
} 

void loop() { 
    // adding a constant integer to a String: 
    stringThree = stringOne + 123; 
    int gpslong =(stringThree.toInt()); 
    a=gpslong+8; 
    //Serial.println(stringThree); // prints "You added 123" 
    Serial.println(a); // prints "You added 123" 
} 
+2

これは英語版サイトです。また、この回答は有用なものを追加せず、それが何をしているのかを説明しません(そして、非常に複雑です)。 – Clonkex

関連する問題