2013-08-13 14 views
14

Bir Arduino programında GPS üzerinde çalışıyorum USB aracılığıyla koordinatları arduinoya gönderir. Bu nedenle gelen koordinatlar Dizge olarak saklanır. GPS koordinatlarını bir float veya int'ye dönüştürmenin herhangi bir yolu var mı?Bir String'i bir float veya int'ye nasıl dönüştürürsünüz?

Ben int gpslong = atoi(curLongitude) ve float gpslong = atof(curLongitude) denedim ama her ikisi de neden Arduino bir hata vermek:

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

Herkes herhangi bir öneriniz var mı?

cevap

22

sadece String nesne (örneğin curLongitude.toInt()) üzerinde toInt arayarak bir String bir int alabilirsiniz. Eğer bir float istiyorsanız

, sen toCharArray yöntemle birlikte atof kullanabilirsiniz:

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

toInt düzgün sayesinde çalışıyor. Bu durumda toCarArray'i tam olarak nasıl kullanırım? Bunu anlayamıyorum. – Xjkh3vk

+0

@ Xjkh3vk: bir örnek ekledi. – nneonneo

0

Nasıl yaklaşık sscanf(curLongitude, "%i", &gpslong) veya sscanf(curLongitude, "%f", &gpslong)? Dizelerin nasıl göründüğüne bağlı olarak, elbette biçim dizesini değiştirmeniz gerekebilir.

2

c_str() size dize tampon const char * işaretçi verecektir.
.
Böylece, dönüşüm fonksiyonlarınızı kullanabilirsiniz: Arduino IDE Uzun olarak
int gpslong = atoi(curLongitude.c_str())
float gpslong = atof(curLongitude.c_str())

+0

Bunlar, Arduino 'String's, C++' string's değil. – nneonneo

0

dönüştürme Dize:

//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

Bu yalnızca İngilizce bir sitedir. Ayrıca, bu cevap yararlı bir şey eklemiyor ve ne yaptığını açıklamıyor (ve çok fazla karmaşık). – Clonkex

İlgili konular