sjhs_unitySerial

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports; //시리얼 포트를 사용하기 위한 네임스페이스를 설정해준다.
public class ArduinoSerial : MonoBehaviour {
//시리얼포트 생성. SerialPort(“포트번호”, 통신속도); 통신 속도는 보통 9600을 사용함.
//SerialPort sp = new SerialPort(“/dev/tty.usbserial-A602AKQ5”, 9600);
SerialPort sp =newSerialPort(“COM3”,9600); //Windows
void Start () {
sp.Open(); //시리얼 포트 오픈
}
void Update () {
//시리얼 포트가 열려있으면
        if(sp.IsOpen){
            string serialData; //문자열을 저장해두는 string 변수
            try{
                //시리얼에 들어온 값을 문자열 형태로 읽어옴
                serialData = sp.ReadLine();
                Debug.Log(serialData); //값을 콘솔창에 출력
                //C#에서 문자열 분리를 함. 쉼표(,)로 문자를 자른 다음에 //문자열 배열에다가 넣음
                /*
                string[] result = serialData.Split(‘,’);
                if(result[0] == “A”){
                    Debug.Log(“가변저항 : “+int.Parse(result[1])); //문자열을 숫자로 변환
                }
                */
            }catch(System.Exception){ //에러 발생시 처리하는 부분. 예외처리
            }
        }
    }
//어플리케이션을 종료하면
void OnApplicationQuit() {
//시리얼포트를 닫는다.
sp.Close();
}
}