Search Unity

Writing to serial ports. (arduino)

Discussion in 'Editor & General Support' started by ThaHypnotoad, Jul 14, 2013.

  1. ThaHypnotoad

    ThaHypnotoad

    Joined:
    Feb 1, 2013
    Posts:
    3
    I am attempting to do some force feedback with an arduino and decided to start simply by sending things to it via serial. That on its own gave me problems.

    My script:

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

    public class NewBehaviourScript : MonoBehaviour {

    SerialPort sp = new SerialPort("COM4", 9600);
    // Use this for initialization
    void Start () {
    sp.Open();
    }

    // Update is called once per frame
    void Update () {

    sp.Write("25");


    }
    }

    gave me this error:

    InvalidOperationException: Specified port is not open.
    System.IO.Ports.SerialPort.CheckOpen ()
    System.IO.Ports.SerialPort.Write (System.String str)
    (wrapper remoting-invoke-with-check) System.IO.Ports.SerialPort:Write (string)
    NewBehaviourScript.Update () (at Assets/Scripts/NewBehaviourScript.cs:16)

    tl;dr its telling me that the port isn't open.

    I am using the correct com port and I open the port in the script. I checked that the arduino is in fact on COM4. I have no idea what may be causing this, and I doubt it is something on the arduino side because reading serially from the arduino works perfectly fine when using the Arduino IDEs serial monitor.

    To clear up one more thing: yes, i did change the player settings to use .NET 2.0 instead of .NET 2.0 subset.

    I know my problem is me doing or missing something extremely stupid, but please bear with me.
     
  2. ThaHypnotoad

    ThaHypnotoad

    Joined:
    Feb 1, 2013
    Posts:
    3
  3. Krodil

    Krodil

    Joined:
    Jun 30, 2010
    Posts:
    141
  4. TylerPerry

    TylerPerry

    Joined:
    May 29, 2011
    Posts:
    5,577
    Maybe try sending from a function invokes in start with "InvokeRepeating"? Also are you sure that you don't need more to the new SerialPort? I worked with serial ports a while ago and had more than just the port name and baud rate?

    this is a link to my work with serial ports in Unity (can't be built to webplayer) does that work? I know that works for serial stuff.
     
  5. Cambridgelab

    Cambridgelab

    Joined:
    Jul 21, 2014
    Posts:
    1
  6. ReillyS

    ReillyS

    Joined:
    May 1, 2015
    Posts:
    3
  7. ReillyS

    ReillyS

    Joined:
    May 1, 2015
    Posts:
    3
  8. ReillyS

    ReillyS

    Joined:
    May 1, 2015
    Posts:
    3
unityunity