简体   繁体   中英

Cannot convert TCL serial com to C#

I'm trying to convert TCL code, used to communicate with a serial port to a "robot", to C#. But for some reason my commands are not getting responses.

This is the serial com init in TCL:

proc openUart {} {
    set robot::fd_ [open COM${robot::port_num}: w+]
    fconfigure $robot::fd_ -mode 9600,e,7,1
    fconfigure $robot::fd_ -blocking 0
    fconfigure $robot::fd_ -buffering none
    fileevent $robot::fd_ readable ""
}

A "command" is sent like this:

proc SendCmd {command} {
        set commandlen [string length $command]
        for {set i 0} {$i < $commandlen} {incr i} { 
            set letter [string index $command $i]
            after 10
            puts -nonewline $robot::fd_ $letter
        }
        after [expr 2 * 10] 
        puts -nonewline $robot::fd_ "\n"
        flush $robot::fd_
}

This is how I translated this to C#. Opening the port:

private void Initialize(string com)
{
    _comPort = new SerialPort(com,9600,Parity.Even,7,StopBits.One)
    {
        Encoding = Encoding.ASCII,
        NewLine = "\n"
    };
    _comPort.Open();
}

And sending a command:

private string SendCommand(Commands cmd)
{
    string commandToWrite = Command(cmd);
    for (int i = 0; i < CommandLen; i++)
    {
        Thread.Sleep(10);
        _comPort.Write(commandToWrite.ToCharArray(), i, 1);
    }
    Thread.Sleep(10 * 2);
    _comPort.Write("\n");
    _comPort.BaseStream.Flush();
}

I connected my PC to the robot with a serial to USB cable and ran both TCL and C# programs - The TCL script turns on a LED on the robot. My C# code doesn't turn the LED on, meaning the robot did not recognize the command.

I'm using the same com port, so I believe the problem is one of these:

  1. I did not initialize the com port correctly in C#. How do you set the blocking and buffering?

  2. Could there be an encoding issue in C#? isn't ASCII the default encoding in TCL?

  3. Could there be a timing difference in how I'm sending the command letter-by-letter between the two languages?

Issue resolved!

I finally looped back the cable into my PC using another serial cable and 2 blue wires, crossing the RX\\TX (thanks don_q for the idea!). Using a simple serial monitor, "UART Terminal", I sniffed the commands, and to my surprise the TCL script was adding a '\\r' before the '\\n'!

So in fact the robot was expecting this command format -

:010508010000F1\r\n

I changed the NewLine property in C# to be "\\r\\n", and now I finish a command by using -

_comPort.WriteLine("");

And now everything works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM