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

2024. 9. 27. 17:45·HCI/Graphics
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
반응형

'HCI > Graphics' 카테고리의 다른 글

[Unity] Meta Quest 3 Qculus 연결하기  (1) 2024.10.29
[Unity] Slider 값 .CSV 형태로 저장하기  (0) 2024.10.17
[Unity] bHaptics 슬라이더로 강도(intensity) 조절하기  (1) 2024.10.07
[Unity - ThermoREAL Project] bHaptics Unity 연결하기  (1) 2024.09.24
[Unity - ThermoREAL Project] bHaptics 프로그램을 통해 블루투스 연결하기  (0) 2024.09.24
'HCI/Graphics' 카테고리의 다른 글
  • [Unity] Slider 값 .CSV 형태로 저장하기
  • [Unity] bHaptics 슬라이더로 강도(intensity) 조절하기
  • [Unity - ThermoREAL Project] bHaptics Unity 연결하기
  • [Unity - ThermoREAL Project] bHaptics 프로그램을 통해 블루투스 연결하기
sillon
sillon
꾸준해지려고 합니다..
    반응형
  • sillon
    sillon coding
    sillon
  • 전체
    오늘
    어제
    • menu (614)
      • notice (2)
      • python (68)
        • 자료구조 & 알고리즘 (23)
        • 라이브러리 (19)
        • 기초 (8)
        • 자동화 (14)
        • 보안 (1)
      • coding test - python (301)
        • Programmers (166)
        • 백준 (76)
        • Code Tree (22)
        • 기본기 문제 (37)
      • coding test - C++ (5)
        • Programmers (4)
        • 백준 (1)
        • 기본기문제 (0)
      • 공부정리 (5)
        • 신호처리 시스템 (0)
        • Deep learnig & Machine lear.. (41)
        • Data Science (18)
        • Computer Vision (17)
        • NLP (40)
        • Dacon (2)
        • 모두를 위한 딥러닝 (강의 정리) (4)
        • 모두의 딥러닝 (교재 정리) (9)
        • 통계 (2)
      • HCI (23)
        • Haptics (7)
        • Graphics (11)
        • Arduino (4)
      • Project (21)
        • Web Project (1)
        • App Project (1)
        • Paper Project (1)
        • 캡스톤디자인2 (17)
        • etc (1)
      • OS (10)
        • Ubuntu (9)
        • Rasberry pi (1)
      • App & Web (9)
        • Android (7)
        • javascript (2)
      • C++ (5)
        • 기초 (5)
      • Cloud & SERVER (8)
        • Git (2)
        • Docker (1)
        • DB (4)
      • Paper (7)
        • NLP Paper review (6)
      • 데이터 분석 (0)
        • GIS (0)
      • daily (2)
        • 대학원 준비 (0)
      • 영어공부 (6)
        • job interview (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    백준
    소수
    programmers
    Python
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
sillon
[Unity - Arduino] 유니티 - 아두이노간 Serial Port 통신 구현하기
상단으로

티스토리툴바