Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by MMil · Apr 03, 2013 at 02:23 AM · slowarduino

Slow reading from Unity via Arduino!! URGENT!

Hi guys, I need some help speeding up the readings in Unity 3D. Thus far I am able to read X and Y values in the Arduino through COM8. The problem occurs when I try and read both values in Unity. It reads fast (when I look at the serial monitor in the arduino IDE) but when I press play in Unity there is a tremendous lag between the time the X and Y values change and the time Unity displays/reads those values.

THE ARDUINO CODE(the necessary part):

     int values[] = {round(X),round(Y)};

     Serial.flush(); 
     Serial.print(values[0]); 
     Serial.print(",");
     Serial.print(values[1]);
     Serial.println();
     delay(10);

and THE UNITY CODE:

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

public class RightWheel : MonoBehaviour {

 public float speed;
 public float MoveBy;
 public int X = 0;
 public int Y = 0;
         
 
 SerialPort sp = new SerialPort("COM8", 9600);

 // Use this for initialization
 void Start () {
     
     sp.Open();
     sp.ReadTimeout = 1;
 
 }
 
 // Update is called once per frame
 void Update () {
     string value = sp.ReadLine(); //Read the information
     string[] vec3 = value.Split(','); 
     X = int.Parse(vec3[0]);
     Y = int.Parse(vec3[1]);
  }

}

Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image mhtraylor · Apr 03, 2013 at 03:13 AM 1
Share

Are you getting any Timeout exceptions thrown? Also, have you considered trying to read this serial port asynchronously? There might be some thread issues.

avatar image MMil · Apr 03, 2013 at 03:22 AM 0
Share

YES,you are right! I have a Timeout exception, it's as follows (as I am unaware what it means):

TimeoutException: The operation has timed-out. System.IO.Ports.WinSerialStream.Read (System.Byte[] buffer, Int32 offset, Int32 count) System.IO.Ports.SerialPort.read_byte () System.IO.Ports.SerialPort.ReadTo (System.String value) System.IO.Ports.SerialPort.ReadLine () (wrapper remoting-invoke-with-check) System.IO.Ports.SerialPort:ReadLine () RightWheel.Update () (at Assets/RightWheel.cs:26)

As for reading it asynchronously, I am unaware of that technique. Thank you for that heads up though, as I've been trying to find different methods of sending multiple values through the serial port. I will look it up, but it would be nice if you had any advice?

avatar image mhtraylor · Apr 03, 2013 at 03:41 AM 2
Share

To debug this, you might want to change your ReadTimeout property to something a bit longer; right now you are ti$$anonymous$$g out if no line is read within 1 millisecond.

I asked about the async possibility because reading from the serial port with ReadLine() will block the main thread, and I believe Unity scripts run in the GUI thread. If this is so, then that might explain some of the lag. Have you checked out the $$anonymous$$SDN documentation on SerialPort? The examples there read the port on a separate thread. Files, ports, etc. are often read/written asynchronously because of this issue, so this would be a good technique to look into.

3 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by Ubahs · Apr 03, 2013 at 05:29 AM

Alongside what mhtraylor said, your Arduino code is delaying for 10 ms and your Unity code is only waiting for 1 ms. That means your Unity code will timeout 10 times for every time it actually gets data (since you're using SerialPort.ReadLine() you'll get a TimeoutException).

If you increase the timeout in Unity to higher, you'll probably end up freezing Unity until the Arduino sends data, which a bad idea. Especially since 10ms is an eternity to a computer. But, if you're not too worried, just changing

  sp.ReadTimeout = 1;

to

  sp.ReadTimeout = 100;

should help you get further.

Alternatively, you could wrap your ReadLine() in a try/catch:

 // Update is called once per frame
 void Update () {
 try
 {
     string value = sp.ReadLine(); //Read the information
     string[] vec3 = value.Split(','); 
     X = int.Parse(vec3[0]);
     Y = int.Parse(vec3[1]);
 }
 catch(TimeoutException) {}

do something async (like mhtraylor suggests), Unity Coroutines might be helpful, pass the data between threads, or just use the SerialPort DataReceived event. Which will call a method every time your Arduino sends data. Example for that event is at: Serial Port DataReceivedEvent

Good luck!

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image pyratej · Feb 17, 2015 at 04:31 AM 0
Share

I'm in the middle of solving this lag issue as well. I would LOVE to use SerialPort DataReceived event but i cannot get it to work for the life of me. Do you have any further info on it?

avatar image Shavik · Feb 26, 2015 at 11:38 PM 0
Share

$$anonymous$$ono does not support SerialPort Events. I'm also trying to work around this.

avatar image kamran-bigdely · Sep 13, 2016 at 12:50 AM 0
Share

me too. I could not get SerialPort DataReceived event to work. By the way, I noticed that I have to set myPort.NewLine = "\n" (it's default value is actually "\r\n" which prevent ReadLine() method to work and lead to TimeoutException).

avatar image
0

Answer by alexLMAD · Apr 21, 2015 at 01:14 PM

try with this in unity, work for me

 if ((cadena=sp.ReadLine()) != null)
                 {
                     data = cadena.Split(',');
                     variable= int.Parse(data[0]);
                     volante = int.Parse(data[1]);
                      freno = int.Parse(data[2]);
                      clutch = int.Parse(data[3]);
                  }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Chevy-Monster · Jan 23, 2016 at 12:23 AM

This is my code for getting six (6) on or off switches from my arduino into unity. The arduino code is sending thestate of 7 switches, sequentially and continuously. Button 9 is a placeholder at the start of the data string, so if SetSwitches() reads anything else first, it's not the beginning of the string of inputs.

 void Update ()
 {        
     if (WalkPort.IsOpen) {

         try {

             Button9 = WalkPort.ReadByte ();
             Button2 = WalkPort.ReadByte ();
             Button3 = WalkPort.ReadByte ();
             Button4 = WalkPort.ReadByte ();
             Button5 = WalkPort.ReadByte ();
             Button6 = WalkPort.ReadByte ();
             Button7 = WalkPort.ReadByte ();                

             SetSwitches ();

         } // <<< -------------------------------- END OF TRY

         catch (System.Exception) {

             throw;

         } // <<< ------------------------------- END OF CATCH

     } // <<< ------------- END OF WalkPort.IsOpen

 } // <<< --- END OF UPDATE
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

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

Answers Answers and Comments

15 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

how can i see serial port speed 1 Answer

New Problem 1 Answer

Is there any way to call CUDAfy.net into Unity? 1 Answer

Using Unity Free Licence in my company 1 Answer

Is there a better way to send data from Arduino to Unity? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges