- Home /
Trying to read an integer value from ReadLine()
Im connecting my arduino to Unity using System.IO.Ports. However, I have been now dealing with trying to convert the string from the ReadLine() method to an integer, as that is all that is being sent from the arduino (its a distance sensor, giving the distance in cm). I tried the int.Parse method but for some reason that never worked either. Any help would be greatly appreciated.
Here's my C# code:
using UnityEngine;
using System.Collections;
using System.IO.Ports;
public class ArduinoConnect : MonoBehaviour {
SerialPort str= new SerialPort("COM3", 9600);
public GameObject forceObject;
//public static int Dist;
// Use this for initialization
void Start () {
str.Open();
str.ReadTimeout = 1;
}
// Update is called once per frame
void Update () {
if (str.IsOpen) {
try {
//---------START OF TRY---------------------------------------
Debug.Log("Distance: "+ str.ReadLine());
if (int.Parse(str.ReadLine()) () < 20) {
forceObject.rigidbody.constantForce.force=Vector3.up*10000;
}
else {
forceObject.rigidbody.constantForce.force=Vector3.zero;
}
//---------------------END OF TRY--------------------------------------------------
}
catch (System.Exception) {
}
}
}
}
Answer by Dave-Carlile · Feb 16, 2013 at 12:19 PM
I assume your Debug.Log
call displays the distance? It looks like you're reading the line twice. Each time you call str.ReadLine
it's going to read more data. Read it once, do the conversion, and operate on the variable...
int distance = int.Parse(str.ReadLine());
Debug.Log("Distance: " + distance.ToString());
if (distance < 20)
{
...
}
Oh wow this worked perfectly, thanks for the info! Any ideas as to why my if then statement doesn't apply any force to my gameobject?
Your answer
Follow this Question
Related Questions
Arduino with Unity: Bad Framerate! 3 Answers
Unity 3D Set a Default Com Port 0 Answers
Handle input from serial device 0 Answers
Help with Unity communicating with Arduino (serial port communication) 0 Answers
send string to serial port on android 0 Answers