x


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.

more ▼

asked Jan 09 '12 at 11:14 PM

IanS gravatar image

IanS
1 2 3 4

I have gotten the application to connect to the serial device, but now the device is returning garbage characters.

Jan 12 '12 at 06:21 PM IanS
(comments are locked)
10|3000 characters needed characters left

0 answers: sort voted first
Be the first one to answer this question
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x4146
x953
x27
x24

asked: Jan 09 '12 at 11:14 PM

Seen: 587 times

Last Updated: Jan 12 '12 at 06:21 PM