HCI/Unity

[Unity - Arduino] 유니티 - 아두이노간 Serial Port 통신 구현하기

sillon 2024. 9. 27. 17:45
728x90
반응형

지난 포스트에 이어서 유니티와 아두이노 기기간 시리얼 포트 통신을 통해

아두이노의 값을 유니티에서 전송받는 것을 구현할 것이다.

 

참고로 유니티 값을 아두이노로 전송할 수 없으며,

시리얼 통신(Serial Port)는 단방향 (아두이노(전송)) -> 유니티(수신)) 밖에 안됨

 

유니티에서 시리얼 통신을 받기에 앞서 오류가 하나 났었는데, .NET 설정 오류가 있었다.

 

 

Edit ->Project Settings -> Player> Api Compatibiliry Level   .Net Framework 로 설정 

 

그다음  스크립트 생성

 

ArduinoCommunication.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using Unity.VisualScripting;
using UnityEngine;

public class ArduinoCommunication : MonoBehaviour
{
    SerialPort sp = new SerialPort();
    
    void Start()
    {
        sp.PortName = "COM5";
        sp.BaudRate = 115200;
        sp.DataBits = 8;
        sp.Parity = Parity.None;
        sp.StopBits = StopBits.One;
        sp.Open();
    }

    void Update()
    {
        Debug.Log("Hello");
        //sp.Write("H");
    }

    
}

 

이것도 동일하게 아두이노에 연결된 COM5 포트로 연결되는거라, COM5 포트에 연결된 USB를 제거하면

이렇게뜬다.

 

저렇게 해서 아두이노랑 유니티를 둘 다 실행해주면

COM5 포트에서 값을 받아왔다는 의미로, 콘솔창에 Hello 가 계속 뜸

 

그럼 이제 COM5 에서 전송하는 값을 출력해보자

ArduinoCommunication.cs 를 아래와 같이 수정해준다.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using Unity.VisualScripting;
using UnityEngine;

public class ArduinoCommunication : MonoBehaviour
{
     SerialPort sp = new SerialPort();

    void Start()
    {
        sp.PortName = "COM5";
        sp.BaudRate = 115200;
        sp.DataBits = 8;
        sp.Parity = Parity.None;
        sp.StopBits = StopBits.One;

        try
        {
            sp.Open();
            sp.ReadTimeout = 500; // 타임아웃 설정 (ms)
            Debug.Log("Serial port opened successfully.");
        }
        catch (Exception e)
        {
            Debug.LogError("Failed to open serial port: " + e.Message);
        }
    }

    void Update()
    {
        if (sp.IsOpen)
        {
            try
            {
                // 시리얼 포트에서 데이터를 읽어서 출력
                string receivedData = sp.ReadLine(); // 한 줄씩 데이터를 읽음
                Debug.Log("Received data: " + receivedData);
            }
            catch (TimeoutException) // 데이터를 수신하지 못한 경우 타임아웃 예외 처리
            {
                Debug.LogWarning("No data received (timeout).");
            }
            catch (Exception e)
            {
                Debug.LogError("Failed to read from serial port: " + e.Message);
            }
        }
        else
        {
            Debug.LogWarning("Serial port is not open.");
        }
    }

    void OnApplicationQuit()
    {
        if (sp != null && sp.IsOpen)
        {
            sp.Close();
            Debug.Log("Serial port closed.");
        }
    }
}

 

잘뜨고있다 

728x90
반응형