Unity와 chibi:bit의 연계(시리얼 통신)

chibi:bit이란?



chibi:bit은 BBC(영국 방송 협회)가 주체가 되어 만들고 있는 교육용 마이크로 컴퓨터 보드 BBC micro:bit의 호환기입니다.
사양은 micro:bit와 동일합니다. 25개의 LED, 2개의 버튼 스위치 외에, 가속도 센서와 자력 센서, BLE 기능을 탑재한 마이크로 컴퓨터 보드입니다.
micro : bit는 BLE 기능이 일본의 기적이 다니지 않기 때문에 사용할 수 없다. 합니다.
chibi:bit 전용 개발 환경 을 준비하고 있습니다.
물론 micro:bit 개발 환경 으로 쓴 프로그램도 쓸 수 있습니다.

chibi:bit 구입
스위치 과학

Unity와 chibi : bit의 협력



이번에는 chibi : bit의 센서 값을 시리얼 통신으로 Unity에 값을 전송하여 객체를 움직이는 곳까지하고 싶습니다.

개발 환경



・Windows10
· Unity5.5.0

설정



micro:bit 공식 사이트 참조 참조
htps //w w. 미 c로비 t. 이. u k / td / seria l-b et ry
1, 장치 드라이버 설치
사이트의 Download latest driver 를 클릭
2, 터미널 에뮬레이터 설치 (PC 도통 확인시 필요)
Tera Term 다운로드에서 .exe 다운로드
공식적으로는 4.88을 인스톨 해라고 써 있습니다만, 우리는 최신의 4.93에서도 움직였습니다.

chibi : bit 측 구현



chibi:bit 전용 개발 환경 를 엽니다.
프로그램은 블록 에디터를 사용하지 않고 직접 JavaScript를 작성하도록 합니다. 이유는 블록 에디터라고 캐스트를 사용할 수 없었기 때문에
코드는 쉽게 쓰면
//アップデート
basic.forever(() => {
serial.writeLine("pitch=" + input.rotation(Rotation.Pitch))//ジャイロセンサーのピッチを送信
serial.writeLine("roll=" + input.rotation(Rotation.Roll))//ジャイロセンサーのロールを送信
})
에서 hex 파일을 다운로드하고 chibi : bit를 usb 연결하고 저장 장치로 PC에 나오면 방금 전
다운로드 한 hex 파일을 복사하여 구워냅니다.

시리얼 통신 동작 확인



설치 프로그램에서 설치한 Tera Term 시작
1, 파일→새 연결을 선택 TCP/IP와 시리얼 항목이 있으므로 시리얼을 선택하고 OK를 클릭
덧붙여서 포트 번호는 나중에 Unity의 구현에서 사용하므로 메모 해 둔다

2, 설정 → 시리얼 포트 설정을 선택해 보 레이트를 「115200」을 선택해 ok를 클릭하면
아래의 이미지에 로그가 나오면 시리얼 통신의 성공이 됩니다


Unity 측 구현



먼저 직렬 통신 수신 부분의 스크립트를 구현합니다.
참고로 한 것
htp // 치 ps. 함몰. 코m/엔트리/2014/07/28/023525

SerialHandler.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
using System.Threading;
using System.Runtime.InteropServices;

public class SerialHandler : MonoBehaviour {
    public delegate void SerialDataReceivedEventHandler(string message);
    public event SerialDataReceivedEventHandler OnDataReceived;

    public string portName = "COM8";
    public int baudRate    = 115200;

    private SerialPort serialPort_;
    private Thread thread_;
    private bool isRunning_ = false;

    public string message_;
    private bool isNewMessageReceived_ = false;


    void Awake()
    {
        Open();

    }

    void Update()
    {
    }

    void OnDestroy()
    {
        Close();
    }

    private void Open()
    {
        serialPort_ = new SerialPort(portName, baudRate, Parity.None, 8, StopBits.One);

        serialPort_.Open();

        isRunning_ = true;

        thread_ = new Thread(Read);
        thread_.Start();
    }

    private void Close()
    {
        isRunning_ = false;

        if (thread_ != null && thread_.IsAlive) {
            thread_.Join();
        }

        if (serialPort_ != null && serialPort_.IsOpen) {
            serialPort_.Close();
            serialPort_.Dispose();
        }
    }

    private void Read()
    {
        while (isRunning_ && serialPort_ != null && serialPort_.IsOpen) {
            try {
                message_ = serialPort_.ReadLine();
                isNewMessageReceived_ = true;
                Debug.LogError(message_);
            } catch (System.Exception e) {
                Debug.LogWarning(e.Message);
            }
        }
    }

    public void Write(string message)
    {
        try {
            serialPort_.Write(message);
            Debug.LogError(message);
        } catch (System.Exception e) {
            Debug.LogWarning(e.Message);
        }
    }
}

여기서 중요한 것은
· public 변수의 string portName을 시리얼 통신의 동작 확인으로 메모 한 것으로 대체
· public 변수의 int baudRate를 115200에 고정

이 스크립트를 적절하게 장면의 객체에 연결

그런 다음 개체에 직렬 통신의 값을 반영하는 스크립트를 구현합니다.
여기에서는 자이로 센서의 값을 물체의 회전에 반영합니다.

ObjRotation.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjRotation : MonoBehaviour {
    
    public SerialHandler _SerialHandler; //SerialHandler.csの参照
    Vector3 rotation;

    // Update is called once per frame
    void Update () {
        objRotation(_SerialHandler.message_);
    }

    void objRotation(string message)
    {
        string[] a;

        a = message.Split("="[0]);
        if(a.Length != 2) return;  
        int v = int.Parse( a[1]);
        switch(a[0])
        {
        case "pitch":
            rotation = new Vector2(v, rotation.y);
            break;
        case "roll":
            rotation = new Vector2( rotation.x, v);
            break;
        }
        Quaternion AddRot = Quaternion.identity;
        AddRot.eulerAngles = new Vector3( -rotation.x, 0, -rotation.y );

        transform.rotation = AddRot;
    }
}

이동하려는 객체에 ObjRotation.cs를 연결하고,

Play하면 에디터상의 오브젝트와 chibi:bit의 움직임이 반영되면 성공입니다.

unity와 chibi : bit의 협력 (직렬 통신) 피 c. 라고 r. 코 m/GbD6m 후우응 x - SASE (@SaseKubrick) 2017년 1월 8일

좋은 웹페이지 즐겨찾기