Search code examples
c#serial-portteraterm

How to replicate Tera Term SerialPort command in C#?


In Tera Term I'm connecting to a serial device over USB (on startup select radiobutton "serial" and correct port). Once connected I only change the default speed to 115200 (in setup=> serial port).

After this, tera term asks me to fill in commands like so:

Command>

I fill in the device specific command. In this case it's "PC" and I receive an expected response ie. "ABC"


Now I'm trying to do the same in C#. Unfortunately the response I get is always the same as the command I actually type in.

So If I type in "PC", the response is "PC", but I expect "ABC". Other commands have the same problem. Command "?" responds with "?" while I expect "CBA".

If I type in a faulty command => then I get the message "Unknown command" So I suspect the device actually gets the right command.

I'm using the following code:

        SerialPort COMport = new SerialPort(Port_Name, Baud_Rate); //Create a new  SerialPort Object (defaullt setting -> 8N1)
        COMport.DataReceived += new SerialDataReceivedEventHandler(sPort_dataReceived);
        COMport.ErrorReceived += new SerialErrorReceivedEventHandler(sPort_ErrorReceived);


        COMport.BaudRate = 115200;
        COMport.Parity = Parity.None;
        COMport.DataBits = 8;
        COMport.StopBits = StopBits.One;
        COMport.RtsEnable = true;
        COMport.Handshake = Handshake.None;


        COMport.Open();


        COMport.WriteLine(Data);

        Thread.Sleep(1000); // Just discovered after a lot of testing that this is necessary to read the response before the Comport closes

        COMport.Close(); 

Then I do the following:

    private void sPort_dataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        Console.WriteLine("Data Received:");
        Console.Write(indata);

        MessageBox.Show(indata);

    }

I've tried different things, but I can't get this to work. Hopefully it's because I'm new to this. I've never worked with Tera term before.

Thanks in advance,

Some (but definately not all) things I've tried:

tried this guys advise and code: https://www.sparxeng.com/blog/software/must-use-net-system-io-ports-serialport

downloaded and tried from here: https://www.xanthium.in/building-opensource-gui-based-serial-port-communication-program-dot-net-framework-and-arduino#simple-serial-source-code (Although my device is not arduino)

Tried to add "\r\n" : C# Errors with SerialPort WriteLine commands


EDIT EDIT EDIT EDIT

So I found out more. If I use the following code (Write instead of WriteLine), I do get good results but not every time:

Sending the full command now: "Command>PC"

        string Command1 = txtCommand.Text;
        Command1 = Command1 + "\r\n";
        string CommandSent;
        int Length, j = 0;

        Length = Command1.Length;

        for (int i = 0; i < Length; i++)
        {
            CommandSent = Command1.Substring(j, 1);
            ComPort.Write(CommandSent);
            j++;
        }

The first time, now I get good results. The second time I get "Unknow Command", the 3rd time => good results, 4th = "Unknown Command"... etc... It always seems to work 1 time well, then 1 time not.

I can only get it to work consistently if I switch the command formatting:

First time command: "Command>PC"

Second time command: "PC"

Third time command : "Command>PC"

Fourth time command: "PC"

etc...

I've already tried to clear the buffer before sending but no effect.

        ComPort.DiscardInBuffer();
        ComPort.DiscardOutBuffer();

Solution

  • The Newline seemed to be a problem.

    I needed to use Comport.Write (instead of WriteLine). Then Also I needed to append a carriage return "\r" but NO newline '\n' as I previously thought. (the incoming data showed a newline after the "Command>" making it impossible to send another meaningfull command => the cause of this was '\n' => removing it solved the problem)

    This is my current code that seems to work (I no longer need to append "Command>", just sending the command as is):

            if (thecommand == "")
            {
                ComPort.Write("\r"); //start from a clean slate
                return;
            }
    
            ComPort.DiscardInBuffer();
            ComPort.DiscardOutBuffer();
    
            string Command1 = thecommand + "\r";
    
            ComPort.Write(Command1);