반응형
아두이노에 LED를 연결해서 시리얼로 특정 문자열을 입력하면 켜고 끄는 것을 구현했습니다. 다른 장치들을 더 붙이고 사용 가능한 명령어들을 더 만들면 다양한 활용이 가능할 듯합니다.
실행결과
turn on을 입력하면 LED를 켜줍니다.
led off를 입력하면 LED를 꺼버립니다.
엉뚱한 문자열을 입력하면 입력 가능한 명령들을 알려줍니다.
소스코드
- int ledPIN = 10;
- char ledStatus = LOW;
- void setup() {
- // put your setup code here, to run once:
- Serial.begin(9600);
- pinMode( ledPIN, OUTPUT );
- }
- String readSerial()
- {
- String str = "";
- char ch;
- while( Serial.available() > 0 )
- {
- ch = Serial.read();
- str.concat(ch);
- delay(10);
- }
- return str;
- }
- void loop() {
- // put your main code here, to run repeatedly:
- String str;
- digitalWrite( ledPIN, ledStatus );
- str = readSerial();
- if ( str == "" )
- ;
- else if (str=="turn off")
- {
- Serial.println(str);
- ledStatus = LOW;
- }
- else if (str=="turn on")
- {
- Serial.println(str);
- ledStatus = HIGH;
- }
- else{
- Serial.println( "-----------------" );
- Serial.println( "available command:" );
- Serial.println( "turn on" );
- Serial.println( "turn off" );
- Serial.println( "-----------------" );
- }
- }
참고
http://stackoverflow.com/questions/5697047/convert-serial-read-into-a-useable-string-using-arduino
http://arduino.cc/en/Reference/StringObject
반응형
감사합니다^^