아두이노 시리얼로 LED 출력 제어하기
2019. 7. 8. 11:26ㆍ드론
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int pinLED = 13; | |
int ledStatus = 0; | |
void setup() { | |
// put your setup code here, to run once: | |
Serial.begin(115200); | |
pinMode(pinLED, OUTPUT); | |
Serial.println("usage : write (turn on | turn off)"); | |
} | |
String Serialread() | |
{ | |
String buf =""; | |
char c; | |
while(Serial.available() > 0) { | |
c = Serial.read(); | |
buf.concat(c); | |
delay(10); | |
} | |
return buf; | |
} | |
void loop() { | |
// put your main code here, to run repeatedly: | |
String str = ""; | |
digitalWrite(pinLED, ledStatus); | |
str = Serialread(); | |
if(str == "") { | |
} | |
else if(str == "turn off") { | |
Serial.println(str); | |
ledStatus = 0; | |
} | |
else if(str == "turn on") { | |
Serial.println(str); | |
ledStatus = 1; | |
} | |
else { | |
Serial.println("usage : write (turn on | turn off)"); | |
} | |
} |

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int pinLED = 13; | |
int ledStatus = 0; | |
void setup() { | |
// put your setup code here, to run once: | |
Serial.begin(115200); | |
pinMode(pinLED, OUTPUT); | |
Serial.println("usage : write (turn on | turn off)"); | |
} | |
void loop() { | |
// put your main code here, to run repeatedly: | |
digitalWrite(pinLED, ledStatus); | |
while(Serial.available() > 0) { | |
if(Serial.find("turn on")) { | |
Serial.println("turn on"); | |
ledStatus = 1; | |
} | |
else if(Serial.find("turn off")) { | |
Serial.println("turn off"); | |
ledStatus = 0; | |
} | |
else { | |
Serial.println("usage : write (turn on | turn off)"); | |
} | |
} | |
} |

[+추가] 새 줄로 한다고 정상적으로 동작하지 않는다. 함수 구조 자체가 잘못됐는데, 한 번의 loop 안에서 find를 두 번 호출하기 때문에 버퍼가 두 번 비워지는 것이다. 따라서 정상적인 코드는 아니었기 때문에 오작동이 일어났다. available 안에서 한 번만 find 검사를 하는 것이 올바른 사용법이다. 따라서 첫 번째 방법을 권장하고, 만일 하나의 문장만 비교한다면 두 번째 방법 코드가 더 편리할 것이다
[참고] https://webnautes.tistory.com/629?category=754890
'드론' 카테고리의 다른 글
아두이노 serialEvent 인터럽트 (0) | 2019.07.08 |
---|---|
아두이노 LED 왕복해서 출력 (0) | 2019.07.08 |
아두이노 시리얼 모니터 새 줄과 line ending 없음 차이 (0) | 2019.07.08 |
사용 중인 COM 포트로 변경하기 (0) | 2019.07.08 |
C를 이용한 영화관 관리 프로그램 (0) | 2019.07.04 |