아두이노 코딩 중 경험상 많이 쓰이는 함수를 정리하려고 한다.
이유는 ... '다시는 잊어버리지 말자' 라는 이유도 있고 필요할 때 다시 찾아보기 위해서이다.
1. substring(...)
[StringObject Function]
Description
Get a substring of a String. The starting index is inclusive (the corresponding character is included in the substring), but the optional ending index is exclusive (the corresponding character is not included in the substring). If the ending index is omitted, the substring continues to the end of the String.
Syntax
string.substring(from)
string.substring(from, to)
Parameters
string
: a variable of type String
from
: the index to start the substring at
to
(optional): the index to end the substring before
Returns
The substring.
(참조: https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/substring/)
*substring 함수는 문자열을 자르기 위해서 사용되고, 범위를 지정하여 자를 수 있다.
1) 매개변수 두개를 사용하는 방법
매개변수 from에는 시작할 문자열의 번호에서 to까지, 예를들면 (3,4)라면 3번째부터 4번째 문자열을 잘라서 출력한다.
String str = "abcdefgh";
String result = str.substring(3,5);
Serial.println(result);
결과: de
2)매개변수 한개를 사용하는 방법
매개변수 from에 3을 입력하면 3번째 문자열부터 통째로 잘라서 출력해준다.
String str = "abcdefgh";
String result = str.substring(3);
Serial.println(result);
결과: "defgh"
2. sprintf (...)
숫자를 문자열로 출력할 때 자리수를 맞춰 출력해야할 때가 많다. 그럴 때 가장 많이 쓰이는 함수이다.
예를들면 숫자 5를 00005 처럼 5자리를 맞춰 출력해야할 때를 말한다.
먼저 char형 buffer 변수를 선언하고 sprintf의 첫번 매개변수에 저장하고 두번째 매개변수에는 형식을 놓고, 세번째 매개변수에는 변수를 넣는다.
sprintf(버퍼, "형식", 변수)
char buf[5];
int n = 5;
sprintf(buf, "%05d", n);
Serial.println(buf);
결과: "00005"
'ARDUINO' 카테고리의 다른 글
[arduino] 아두이노용 5v 릴레이 (0) | 2018.11.23 |
---|