- Home /
Handle input from serial device
Hello,
For my work i am making a video game that takes input from a serial device. Here is a snippet of my code
using System.IO.Ports;
using UnityEngine;
using System.Collections;
using System;
using System.Threading;
public class serialInputTest : MonoBehaviour {
SerialPort _serialPort = new SerialPort("COM6", 9600);
Thread _readThread;
// Use this for initialization
void Start () {
_serialPort.Parity = Parity.None;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(myFunc);
_serialPort.DtrEnable = true;
// _serialPort.DsrHolding = true;
_serialPort.RtsEnable = true;
_serialPort.ReadTimeout = 1000;
_serialPort.WriteTimeout = 1000;
_serialPort.Open();
_serialPort.Write(("ATC1").ToCharArray(), 0 , 1);
print("I wrote");
//_readThread = new Thread(Read);
//_readThread.Start();a
}
void myFunc(object sender, SerialDataReceivedEventArgs e)
{
print("Something has been recieved");
}
void Read()
{
bool stop = false;
int counter = 0;
while(!stop && counter < 10)
{
try
{
print("i got here");
_serialPort.Write("ATC1");
counter++;
}
catch(Exception e)
{
print("Ian: " + e.Message);
stop = true;
break;
}
}
}
}
That is really just a basic thing i'm just trying to get it to return an ok message or something along those lines. If anyone could help or point in the right direction that would be awesome! I've never done serial port communication so i'm open to any kinda help i can get.
Comment
I have gotten the application to connect to the serial device, but now the device is returning garbage characters.