2013-08-13 2 views
14

Arduino 프로그램에서 나는 GPS를 통해 arduino에 USB를 통해 좌표를 보낸다. 이 때문에 들어오는 좌표는 문자열로 저장됩니다. GPS 좌표를 float 또는 int로 변환 할 수있는 방법이 있습니까?String을 float 또는 int로 어떻게 변환합니까?

나는 int gpslong = atoi(curLongitude)float gpslong = atof(curLongitude)을 시도했지만, 그들은 둘 다 원인 아두 이노 오류 줄 :

이 가
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를 사용할 수 있습니다

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

toInt 제대로 감사를 작동합니다. 이 경우 toCharArray를 얼마나 정확하게 사용합니까? 나는 그것을 알아낼 수 없습니다. – Xjkh3vk

+0

@ Xjkh3vk : 예를 추가했습니다. – nneonneo

0

방법에 대한 sscanf(curLongitude, "%i", &gpslong) 또는 sscanf(curLongitude, "%f", &gpslong)을? 문자열의 모양에 따라 형식 문자열을 수정해야 할 수도 있습니다.

2

c_str()은 문자열 버퍼 const char * pointer를 제공합니다.
.
변환 기능을 사용할 수 있습니다. 아두 이노 IDE에서 롱
int gpslong = atoi(curLongitude.c_str())
float gpslong = atof(curLongitude.c_str())

+0

이것들은 Arduino'String'이 아니라 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

관련 문제