メモ:Unity × Arduino シリアル通信

UnityとArduinoとのシリアル通信メモ

Arduino

void setup() {
  Serial.begin(115200);
}

void loop() {
  if (Serial.available() > 0) {
    int i = Serial.read();
    if (i == 's') {
        Serial.println("s incomoing. create over 64.0000000000000000000000000000000098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321");
    } else {
        Serial.println("unknown incoming!!");
    }
  } else {
    Serial.println("This message is sample.");
  }
  delay(100);
}

 

簡易シリアル通信クラス

using System.IO.Ports;
using System.Collections.Generic;

public class Serial
{
    private SerialPort serial_;
    private Queue<string> messages_ = new Queue<string>();
    private Queue<int> inputs_ = new Queue<int>();

    private bool isRunning_;

    public Serial( string portName, int baudRate = 115200 )
    {
        serial_ = new SerialPort( portName, baudRate, Parity.None, 8, StopBits.One );
        serial_.Open();
        serial_.DtrEnable = false;
        serial_.RtsEnable = true;
        serial_.DiscardInBuffer();
        serial_.ReadTimeout = 5;

        var thread = new System.Threading.Thread( Update );
        thread.Start();
    }

    private void Update()
    {
        UnityEngine.Debug.LogWarning( "Start Serial" );
        isRunning_ = true;

        while ( isRunning_ ) {
            try {
                lock ( inputs_ ) {
                    if ( inputs_.Count > 0 ) {
                        var p = inputs_.Dequeue();
                        byte[] buffer = new byte[1] { (byte) (p & 0xff) };
                        serial_.Write( buffer, 0, buffer.Length );
                    }
                }

                var line = serial_.ReadLine();
                lock ( messages_ ) {
                    messages_.Enqueue( line );
                }
            } catch ( System.Exception e ) {
            }
        }

        serial_.Close();
        serial_ = null;
        UnityEngine.Debug.LogWarning( "Stop Serial" );
    }

    public string Pop()
    {
        lock ( messages_ ) {
            if ( messages_.Count > 0 ) {
                return messages_.Dequeue();
            } else {
                return null;
            }
        }
    }

    public void Send( byte p )
    {
        lock ( inputs_ ) {
            inputs_.Enqueue( p );
        }
    }

    public void Stop()
    {
        isRunning_ = false;
    }
}

 

Unityのシーン

using System.Collections;
using UnityEngine;

public class Main 
    : MonoBehaviour
{
    private Serial serial_;

    void Start()
    {
        if ( serial_ != null ) { serial_.Stop(); }
        serial_ = new Serial( @"COM3" );
    }

    void Update()
    {
        string message = serial_.Pop();
        if ( !string.IsNullOrEmpty( message ) ) {
            Debug.Log( message );
        }

        if ( Input.GetKeyDown( KeyCode.Space ) ) {
            serial_.Send( (byte) 's' );
        }
    }

    void OnDestroy()
    {
        serial_.Stop();
    }
}

 

 

タイトルとURLをコピーしました