Get the Data from a Serial Port, Work in VB but in Unity Dont.

  • Re Edit *

Hi Guys Im still stuck with this problem, but now im more conscient about the state of the proyect.
I do an miniapp in Visual Studio, and it worket, its a console app, but she recognized me the data and i can capture it.

I Create a Class in Unity… But guys that doesnt work, the data is null and IDK why.
Please help me! Im Stuck in this since the last friday.

This is my script in Unity:

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


public class ScriptPort : MonoBehaviour{
	public GUIText guiDisplay;
	string data2;
	void Start(){
		InvokeRepeating ("UpdateData",5,5);
	}
	void Upate(){

	}
	void UpdateData(){
		ScriptCOM3 sp = new ScriptCOM3 ();
		sp.OpenPort ();
		data2 = sp.data;
		Debug.Log (data2);
		sp.ClosePort();
	}
}

public class ScriptCOM3 {
	public string data;
	public SerialPort COM3 = new SerialPort();

	public ScriptCOM3() {
		COM3.BaudRate = 9600;
		COM3.DataBits = 8;
		COM3.StopBits = StopBits.One;
		COM3.Parity = Parity.None;
		COM3.PortName = "COM3";
		COM3.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
	}

	public void OpenPort() {
		COM3.Open();
	}

	public void ClosePort() {
		COM3.Close();
	}

	public string ByteToHex(byte[] comByte){
		StringBuilder builder = new StringBuilder(comByte.Length * 3);
		foreach (byte data in comByte)
		{
			builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' '));
		}
		return builder.ToString().ToUpper();
	}

	public void DisplayData(string msg){
		data = msg;
	}
	
	public void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e){
		int bytes = COM3.BytesToRead;
		byte[] comBuffer = new byte[bytes];
		COM3.Read(comBuffer, 0, bytes);
		DisplayData(ByteToHex(comBuffer) + "

");
}
}

How you could see im using another class and then instantiate that class in the Mono behaviour script, but the data is null… Why??

I’m pretty sure you want to do this:

public class ScriptPort : MonoBehaviour
{
    public GUIText guiDisplay;
    string data2;
    ScriptCOM3 sp = new ScriptCOM3 ();
    void Start()
    {
        sp.OpenPort ();
        InvokeRepeating ("UpdateData",5,5);
    }
    
    void OnDestroy()
    {
        sp.ClosePort();
    }
    
    void UpdateData()
    {
        data2 = sp.data;
        Debug.Log (data2);
    }
}

Please visit the following web site to view updates on this issue and comment letting the Unity staff know how important this functionality is to the COM Port and TTY reading community! VOICE YOU OPINION!