2015年11月26日 星期四

Ardunio To Unity (Rs232)

請在Unity Pjcet Assts path Unsing System.Windows.Froms

System.Windows.Form .dll (Download Dll /  Download DLL)

Rs232Vaule (c# ):

using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System;
using System.Windows.Forms;

public class Rs232Vaule : MonoBehaviour {

    public static string[] PORT_NAME;

// Use this for initialization
void Awake () {

        PORT_NAME = SerialPort.GetPortNames();

        foreach (string name in PORT_NAME) {
            Console.WriteLine(name);
        }
        Console.ReadLine();
    }
}


-------------------------------------------------------
ArdunioValue (c#):

using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System;
using System.Windows.Forms;

[RequireComponent(typeof(Rs232Vaule))]

public class ArdunioValue : MonoBehaviour {

    string poritName;
    SerialPort serialPort;

    // Use this for initialization
    void Start() {

        for (int i = 0; i < Rs232Vaule.PORT_NAME.Length; i++)
            poritName = Rs232Vaule.PORT_NAME[i];
        serialPort = single(poritName);
        serialPort.Open();
        serialPort.ReadTimeout = 1;
}

    void OnApplicationQuit() {
        serialPort.Close();
    }

    SerialPort single(string poritName) {
 
        SerialPort serialPort = new SerialPort(poritName, 9600);
        return serialPort;
    }

    void Update() {
        ardunioValue();
    }

    void ardunioValue() {
        if (serialPort.IsOpen) {
            try{
                // Ardunio 功能給 Unity 或 Unity 給 Ardunio
            }catch (Exception e) {
                MessageBox.Show("錯誤: " + e);
            }
        }
    }
}

沒有留言:

張貼留言