C#中的Unity:与Arduino的串行通信

时间:2016-04-25 14:54:59

标签: c# .net arduino unity3d

我正在尝试与Arduino进行串行通信,以便在C#中通过Unity控制LED。

以下是从示例链接中复制的代码:

SerialHandler.cs

using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System.Threading;

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

public string portName = "/dev/tty.usbmodem1421";
public int baudRate    = 9600;

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

private string message_;
private bool isNewMessageReceived_ = false;

void Awake()
{
    Open();
}

void Update()
{
    if (isNewMessageReceived_) {
        OnDataReceived(message_);
    }
}

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 {
            if (serialPort_.BytesToRead > 0) {
                message_ = serialPort_.ReadLine();
                isNewMessageReceived_ = true;
            }
        } catch (System.Exception e) {
            Debug.LogWarning(e.Message);
        }
    }
}

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

LedController.cs

using UnityEngine;
using System.Collections;

public class LedController : MonoBehaviour
{
public SerialHandler serialHandler;

void Update()
{
    if ( Input.GetKeyDown(KeyCode.A) ) {
        serialHandler.Write("0");
    }
    if ( Input.GetKeyDown(KeyCode.S) ) {
        serialHandler.Write("1");
    }
}
}

然而,当按下键盘AS来打开/关闭LED时,它不起作用。 我得到了错误信息。

Object reference not set to an instance of an object

如果智慧帮助我,那真是太棒了!

谢谢,

0 个答案:

没有答案