개발 관련/SW, App 관련

Unity Serial 통신 사용하기 추가사항

by 소서리스25 2023. 5. 8.
반응형

Unity Serial 통신 사용하기 추가사항

 

지난번 아래와 같은 포스팅을 진행했었는데, 아무래도 직관적인 확인이 좀 부족한 것 같아 추가적으로 보완하여 필요한 부분만 다시 포스팅한다.

Unity의 Serial 통신 사용하기 (tistory.com)

 

Unity의 Serial 통신 사용하기

Unity의 Serial 통신 설정코드 여러 프로젝트를 진행하면서 가장 많이 공통적으로 들어간 사항이 Unity와 Arduino의 Serial 통신일 것이다. 주로 RS232 통신 방식으로 진행했으며, 9600 bps ~ 19200 bps 정도의

tipon.tistory.com

 

좀 더 직관적인 확인을 위해 Canvas에 on과 off의 2개 버튼을 다음과 같이 만들고, 기존 보내는 "on"과 "off"만 비활성화하였다. 그 외 코드는 크게 달리지는 것은 없다. 대부분 그대로 활용하면 되며 Arduino에서 수신 후 다시 회신하는 부분을 추가하였다. 혹시 모르니 아래와 같이 c# 코드를 다시 확인해 보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.IO.Ports;
using UnityEngine.UI;
 
public class SerialConnect : MonoBehaviour
{
    [Header("Serial Connect")]
    SerialPort sp = new SerialPort();
 
    public int timeOut = 20;
    public bool serialState = false;
    public Text _debugText;
 
    bool _trans = false;
    bool _debugTextState = false;
 
    [Header("Setup File Read")]
    public string[] _readtextData;
    string _filePath = "./setup.ini";
 
    void Awake()
    {
        // 설정파일 불러오기
        ReadTextFile(_filePath);
    }
 
    void Start()
    {
        //  디버그 화면표시 여부
        if (_readtextData[4].Equals("on"))
        {
            Cursor.visible = true;
            _debugTextState = true// DebugText("Log view on");
        }
        else
        {
            Cursor.visible = false;
            _debugText.gameObject.SetActive(false);
        }
 
        if (serialState || _readtextData[0].Equals("on"))
        {
            SerialPort();
            StartCoroutine(StartDelay());
 
            DebugText("Baudrate : " + _readtextData[1+ ", Port : " + _readtextData[2]);
        }
        else
        {
            DebugText("Serial connect off!!!");
        }
    }
 
    // comport 포트번호, bps 전송속도, 데이터 비트, 타임아웃
    void SerialPort()
    {
        sp.PortName = _readtextData[2];
        sp.BaudRate = int.Parse(_readtextData[1]);
        sp.DataBits = 8;
        sp.Parity = Parity.None;
        sp.StopBits = StopBits.One;
        sp.ReadTimeout = int.Parse(_readtextData[3]);
        sp.WriteTimeout = int.Parse(_readtextData[3]);
 
        serialState = true;
 
        sp.Open();
    }
 
    IEnumerator StartDelay()
    {
       // SendData("off"); // 만약에 켜져있었다면 off 초기화
 
        yield return new WaitForSeconds(2);
 
        DebugText("Switch Ready OK...");
 
        // SendData("on");
    }
 
    void Update()
    {
        if (_readtextData[0].Equals("on"))
        {
            if (sp.IsOpen)
            {
                _ReceiveData();
            }
            else
            {
                DebugText("Port not found.");
            }
        }
        else
        {
            DebugText("Not Connected,...");
        }
    }
 
    public void SendData(string sendData)
    {
        if (serialState)
        {
            sp.Write(sendData);
        }
    }
 
 
    void _ReceiveData()
    {
        string temps = "";
 
        try
        {
            char tempB = (char)sp.ReadChar();
 
            while (tempB != 256)
            {
                temps += (char)tempB;
                tempB = (char)sp.ReadChar();
            }
        }
        catch (Exception e)
        {
            // blink
        }
 
        if (temps != "")
        {
            DelayReceiveData(temps);
        }
    }
 
    void DelayReceiveData(string data)
    {
        switch (data)
        {
            case "1":
                // "1" 받았을때 이곳에서 수신 처리하기
                DebugText("Debug Text : '1'을 수신");
                break;
 
            case "2":
                // "2" 받았을때 이곳에서 수신 처리하기
                DebugText("Debug Text : '2'을 수신");
                break;
        }
    }
 
    void OnApplicationQuit()
    {
        SendData("off");
        sp.Close();
    }
 
    void DebugText(string text)
    {
        if (_debugTextState)
            _debugText.text = text;
    }
 
    void ReadTextFile(string filePath)
    {
        StreamReader rd = new StreamReader(filePath);
 
        for (int i = 0; i < _readtextData.Length; i++)
        {
            _readtextData[i] = rd.ReadLine();
 
            if (_readtextData[i].Equals("")) break;
        }
 
        rd.Close();
    }
}
cs

 

 

그리고 Arduino에서 Unity로 회신하는 C 코드는 아래와 같다.

Arduino를 연결하여 컴파일 후 다시 업로드 하자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const int _led = 13;
 
bool _state = true;
String _inString;
 
void setup()
{
  pinMode(_led, OUTPUT);
 
  Serial.begin(9600);
  Serial.println("Start~");
}
 
void loop()
{
  if (Serial.available() > 0)
  {
    _inString = Serial.readString();
 
    if(_inString == "on")
      DelayCheck(true);
    else if(_inString == "off")
      DelayCheck(false);
  }    
  
  delay(20);
}
 
void DelayCheck(bool mode)
{
  if(mode)
  {
    digitalWrite(_led, HIGH);
   Serial.print("1");
  }
  else
  {
    digitalWrite(_led, LOW);
   Serial.print("2");
  }
}
cs

 

다음으로 Serial 스크립트 오브젝트를 다음과 같이 버튼에 연결시켜 준다.

버튼의 입력 string을 on과 off를 각각 넣어준다.

On / Off 버튼 설정
On / Off 버튼 설정

 

 

자 이제 Unity 플레이 버튼을 누르고 정상 작동하는지 확인해 보자.

해당 결과는 아래와 같이 동영상에서 확인할 수 있다.

정상작동 확인

 

반응형

댓글