Menu

Reading data from serial (COM) port.

Anonymous
2016-02-04
2016-02-10
  • Anonymous

    Anonymous - 2016-02-04
     

    Last edit: Anonymous 2016-02-04
    • Anonymous

      Anonymous - 2016-02-04

      Hello Stefan,

      amazing product, blazingly fast replies to questions!

      Sorry, here is my post, and actually the Topic should actually be "Writing data to the serial (COM) port.", or maybe more generically "Serial (COM) port" -sorry about that!

      I'm sure I'm doing something wrong, but I read through all the documentation & forum postings I could find, and I still can't get my script to WRITE to the serial port.


      I have 2 COM ports (COM20 and COM30). They exist on the same computer (they are "virtual ports" (http://com0com.sourceforge.net/) and are connected by a "virtual null modem cable".

      I have tested them by running two HyperTerminals, one connected to COM20, and the other to COM30, and I can type data on one HyperTerminal, and see it appear on the other, etc.


      What I'm trying to do is create (via script) a simple simulator the will read a command, and then "echo" back a hard-coded response.

      I have a C# program that replaces one of the HyperTerminals, and I connect it to COM20, and it has the following serial port properties set:

      PortName: >COM20<.
      BaudRate: >9600<.
      Parity: >None<.
      DataBits: >8<.
      StopBits: >One<.
      Handshake: >None<.
      DtrEnable: >False<.
      RtsEnable: >False<.

      I have tested the C# program (COM20) by connecting it to a HyperTerminal (COM30), and they both work to read/write data.


      When I replace the HyperTerminal COM30 with my script, I can get my script to read data from the COM port, successfully, but not WRITE data.

      Here is the latest script I have tried (without success to write data):

      scriptThread.appendTextToConsole('script has started');
      
      function readyReadSlot()
      {
          //scriptThread.appendTextToConsole('received something...');
          if(serialPort.canReadLine())
          {
              var line = serialPort.readLine();
              scriptThread.appendTextToConsole("line received: " + line);
          }
      
          // HERE IS WHERE TRYING TO WRITE DATA.  I know it is getting settings from "main interface", and
          // the main interface is not connected to COM30, but I'm not sure what to do here...?
          var result = scriptThread.sendString("SEND: test string\n");
          scriptThread.appendTextToConsole("result: " + result);
      }
      
      var serialPort = scriptThread.createSerialPort();
      serialPort.readyReadSignal.connect(readyReadSlot);
      serialPort.setPortName("COM30");
      serialPort.setDTR(false);
      if (serialPort.open())
      {
          serialPort.setBaudRate(9600);
          serialPort.setDataBits(8);
          serialPort.setParity("None");
          serialPort.setStopBits("1");
          serialPort.setFlowControl("None");
          serialPort.setDTR(true);
          serialPort.setRTS(true);
          scriptThread.appendTextToConsole("serial port signals:" + serialPort.getSerialPortSignals().toString(16) );
      }
      else
      {
          scriptThread.messageBox("Critical", 'error', 'could not open serial port');
      }
      
      function stopScript() 
      {
          scriptThread.appendTextToConsole("script has been stopped");
      }
      

      Here is the output to the above:

      my C# program output:

      PortName: >COM20<.
      BaudRate: >9600<.
      Parity: >None<.
      DataBits: >8<.
      StopBits: >One<.
      Handshake: >None<.
      DtrEnable: >False<.
      RtsEnable: >False<.
      This was sent from C# program to COM20.
      Something else sent to COM20

      ScriptCommunicator script output:

      script has started
      serial port signals:44
      line received: This was sent from C# program to COM20.
      result: false
      line received: Something else sent to COM20
      result: false


      I have found if I'm connected to COM30 (via the main interface), then

      scriptThread.sendString("SEND: test string\n");

      will work, but I have also found if I have "my own interface" connected via:

      var serialPort = scriptThread.createSerialPort();
      ...
      serialPort.open()

      -then I can't connect via the main interface because I then get the error:

      "could not open serial port: COM30"


      At this point I'm not sure what to do. I'm new to serial port communication, and any help is much appreciated!

      Thanks,
      George Hynes
      02/04/2016 10:29am ET

       

      Last edit: Anonymous 2016-02-04
  • Stefan Zieker

    Stefan Zieker - 2016-02-04

    Hi George ,

    the problem is you create a ComPort in the script (and receive data from in readyReadSlot). But then you try to send data with the main interface (scriptThread.sendString) which is configured by the ScriptCommunicator GUI (keep in mind that serial ports are open exclusivly, therefore the main interface can not access the COM port which you have opened in the script).
    You have 2 possibiliies:

    • change you code: replace scriptThread.sendString with serialPort.write (keep in mind that this function needs a byte array and not a string)
    • or use the main interface (much less code and you can see the data in the consoles):
    function dataReceivedSlot(data)
    {
        scriptThread.appendTextToConsole("data received: " + data);
    
        var string = scriptThread.byteArrayToString(array)
        scriptThread.appendTextToConsole("data string: " + string);
    
        scriptThread.sendString("SEND: test string\n");
    
    }
    //connect the dataReceivedSlot function to the dataReceivedSignal signal
    scriptThread.dataReceivedSignal.connect(dataReceivedSlot)
    

    PS: You can simply convert a string into a byte array by:

    function addStringToArray(array, string)
    {
        for (var i = 0; i < string.length; i++) 
        {
            array.push(string.charCodeAt(i));
        }
    }
    
    var data = Array();
    addStringToArray(data, "SEND: test string\n");
    

    Best regards,
    Stefan

     

    Last edit: Stefan Zieker 2016-02-04
    • Anonymous

      Anonymous - 2016-02-04

      Hi Stefan,

      thank you very much, this is very helpful!

      I took your approach #2 (the main interface), which seems much simpler, and as you say, I can see the data in the consoles.

      Also, I just had to fix one minor typo -I think you meant:

      var string = scriptThread.byteArrayToString(data)


      Here is the complete script:

      scriptThread.appendTextToConsole('script has started');
      
      function dataReceivedSlot(data)
      {
          scriptThread.appendTextToConsole("data received: " + data);
      
          var string = scriptThread.byteArrayToString(data)
          scriptThread.appendTextToConsole("data string: " + string);
      
          scriptThread.sendString("SEND: test string\n");
      
      }
      //connect the dataReceivedSlot function to the dataReceivedSignal signal
      scriptThread.dataReceivedSignal.connect(dataReceivedSlot)
      
      function stopScript() 
      {
          scriptThread.appendTextToConsole("script has been stopped");
      }
      

      Thanks,
      George Hynes
      02/04/2016 2:16pm ET

       
  • Anonymous

    Anonymous - 2016-02-10

    Hi Stefan,

    things seem to be working now, but now I have another problem. I'm not sure what I might have changed, but what I now notice in my "worker script", is every call to:

    scriptThread.sendString("send something...");

    -is sent twice, always...? Meaning the above seems to send:

    send something...send something...


    Here are my serial port settings:

    BaudRate: >115200<.
    Parity: >None<.
    DataBits: >8<.
    StopBits: >One<.
    Handshake: >None<.
    DtrEnable: >False<.
    RtsEnable: >False<.
    ReadBufferSize: >100000<.


    I have no problems other than the above, any suggestions...?

    Thanks,
    George Hynes
    02/10/2016 9:39am ET

     
  • Anonymous

    Anonymous - 2016-02-10

    Hi Stefan,

    here is an update: I exited/restarted all your software:

    ScriptCommunicator 4.00 (the GUI)
    ScriptCommunicator (the tool for loading/unloading scripts)
    ScriptCommunicator script editor

    -and the when I did, the problem (double sending) seems to have gone away.

    I'm using the same scripts, settings, etc., unless something changed that I'm not aware of.

    Thanks,
    George Hynes
    02/10/2016 9:55am ET

     
  • Stefan Zieker

    Stefan Zieker - 2016-02-10

    Hi George,

    can you send me you script please?

    Best regards,
    Stefan

     
  • Stefan Zieker

    Stefan Zieker - 2016-02-10

    Hi George,

    maybe the problem is that you send directly from the dataReceivedSlot.
    If you send for example "Test string" to ScriptCommunicator dataReceivedSlot can be be called once ore several time. For example:
    - first call, data is 'Te"
    - second call, data is"st st"
    - third call, data is "ring"

    In this case you would send your fixed string 3 time.

    Best regards,
    Stefan

     
  • Anonymous

    Anonymous - 2016-02-10

    Hi Stefan,

    here is the script:

    scriptThread.appendTextToConsole('script has started');
    
    var myRXdata = "";
    
    var NEWLINE = String.fromCharCode(13, 10);
    var LINEFEED = String.fromCharCode(10);
    var BACKSPACE = String.fromCharCode(8);
    
    function dataReceivedSlot(dataByteArray)
    {
        scriptThread.appendTextToConsole("data received: " + dataByteArray);
        var dataString2 = scriptThread.byteArrayToString(dataByteArray);
        scriptThread.appendTextToConsole("data string: " + dataString2);    
    
        do
        {   
            if (dataString2.length > 1)
            {
                //this is the case where a complete string of chars + newline was sent:
                myRXdata = dataString2;
            }
    
            if (dataString2 == BACKSPACE)
            {
                if (myRXdata.length > 0)
                {
                    myRXdata = myRXdata.substring(0, myRXdata.length -1);
                }
                break;
            }
    
            if (dataString2.charAt(dataString2.length -1) == LINEFEED)
            {
                myRXdata = myRXdata.trim();
                actOnLineOfData(myRXdata);
                myRXdata = "";
                break;
            }
    
            myRXdata = myRXdata + dataString2;
    
        } while (false)
    
    }
    
    function actOnLineOfData(dataString)
    {
        do
        {
    
            if (dataString == "run test")
            {
                scriptThread.sendString("..");
                scriptThread.sleepFromScript(1000);
                scriptThread.sendString("..");
                scriptThread.sleepFromScript(1000);
                scriptThread.sendString("..");
                scriptThread.sleepFromScript(1000);
                scriptThread.sendString("PASS");
                scriptThread.sendString(NEWLINE);
                break;
            }
    
            if (dataString == "test log")
            {
                scriptThread.sendString("Index / TimeH / TimeL Event");
                scriptThread.sendString(NEWLINE);
                scriptThread.sendString("&H006F : 98d 23:57:19.250 Test Passed, Loaded String I: &HFDDE, 64990");
                scriptThread.sendString(NEWLINE);
                scriptThread.sendString("&H0070 : 98d 23:57:19.875 Test Passed, Heater Current: &H005E, 94");
                scriptThread.sendString(NEWLINE);
    
                break;
            }
    
        } while (false)
    
    }
    
    scriptThread.dataReceivedSignal.connect(dataReceivedSlot)
    
    function stopScript() 
    {
        scriptThread.appendTextToConsole("script has been stopped");
    }
    

    Thanks,
    George Hynes
    02/10/2016 11:35am ET

     
  • Stefan Zieker

    Stefan Zieker - 2016-02-10

    Hi George,

    your script looks OK.
    So you said that your script works correct. And after a specific time or event the send data is doubled and only after a restart of ScriptCommunicator your script works correct again?

    Can you add scriptThread.addMessageToLogAndConsoles(string) for every scriptThread.sendString call (with the corresponding string). Then we can be sure that your send data is doubled by scriptThread.sendString.

    PS: You have to adjust the color for the messages in the settings window (the send color is the same per default).

    It would be good if you can send me the console output if the error occurs.

    Best regards,
    Stefan

     

    Last edit: Stefan Zieker 2016-02-10
  • Anonymous

    Anonymous - 2016-02-10

    Hi Stefan,

    thanks for taking a look at this, and I'm not sure what triggered the problem, but it looks like it was a one-time thing, only.

    I have been running scripts for about a week now, without any problems, but yesterday, I was running scripts, then all of sudden the "double sends", and nothing I changed would fix it.

    The only thing substantial that I recall changing is the baud rate from 9600 -> 115200, around the time of the problem, but this might just be a coincidence. I'm running at 115200 with no problems at all, today.

    This morning, I simply exited all the ScriptCommunicator executables, and restarted everything, and now I don't have the double sends problem anymore.


    Also, I basically already did what you are suggesting with "scriptThread.addMessageToLogAndConsoles(string)" by doing "printf's" (scriptThread.appendTextToConsole()) before/after the scriptThread.sendString() calls, to verify I wasn't calling each scriptThread.sendString(), twice -and I verified this was indeed the case, meaning scriptThread.sendString() was only being called 1 time, but I could see 2 sends received in HyperTerminal (HyperTerminal was on COM20, and ScriptCommunicator was on COM30).


    If the problem occurs again, I will send console output, etc.

    Thanks,
    George Hynes
    02/10/2016 12:32pm ET

     

    Last edit: Anonymous 2016-02-10
  • Stefan Zieker

    Stefan Zieker - 2016-02-10

    Hi George,

    I love this kind of bug :-).

    Thx for reporting it,
    Stefan

     

Anonymous
Anonymous

Add attachments
Cancel





Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.