strncpy

Arduino 사용 사례

Arduino 사용 사례

1. 시리얼 명령어 파싱

시리얼로 "LED:ON:5" 형태의 명령을 받았을 때:

// 수신: "LED:ON:5"
// 의미: LED를 켜라, 5번 핀

char received[20] = "LED:ON:5";
char command[4];
char action[3];

strncpy(command, received, 3);      // "LED" 추출
command[3] = '\0';                   // 널문자 추가 필수!

strncpy(action, received + 4, 2);   // "ON" 추출
action[2] = '\0';

if (strcmp(command, "LED") == 0) {
    if (strcmp(action, "ON") == 0) {
        digitalWrite(5, HIGH);
    }
}

2. LCD에 긴 문자열 일부만 표시

16x2 LCD는 한 줄에 16글자만 표시 가능:

char message[50] = "Temperature: 25.5 degrees Celsius";
char lcdLine[17];  // 16 + 널문자

strncpy(lcdLine, message, 16);
lcdLine[16] = '\0';

lcd.print(lcdLine);  // "Temperature: 25" 출력

3. 센서 데이터에서 값 추출

GPS 데이터에서 시간만 추출:

// GPS 데이터: "$GPGGA,123519,4807.038,N,01131.000,E..."
// 시간(123519)만 추출

char gpsData[100] = "$GPGGA,123519,4807.038,N";
char timeStr[7];

strncpy(timeStr, gpsData + 7, 6);  // 7번째부터 6글자
timeStr[6] = '\0';

Serial.print("시간: ");
Serial.println(timeStr);  // "123519"

4. 통신 패킷에서 헤더/데이터 분리

// 패킷 형식: [헤더 2바이트][데이터 10바이트]
// 예: "ABHELLOWORLD"

char packet[13] = "ABHELLOWORLD";
char header[3];
char data[11];

strncpy(header, packet, 2);     // "AB"
header[2] = '\0';

strncpy(data, packet + 2, 10);  // "HELLOWORLD"
data[10] = '\0';

if (strcmp(header, "AB") == 0) {
    // 유효한 패킷
    processData(data);
}

5. 버퍼 오버플로우 방지

// 위험한 코드 (버퍼 오버플로우 가능)
char dest[10];
strcpy(dest, userInput);  // userInput이 10자 넘으면 위험!

// 안전한 코드
char dest[10];
strncpy(dest, userInput, 9);  // 최대 9자만 복사
dest[9] = '\0';                // 널문자 보장

댓글

댓글 본문
버전 관리
anton
현재 버전
선택 버전
graphittie 자세히 보기