.net – C# SerialPort settings

c#-4.0netserial-port

I'm having trouble in setting up the COM port using the SerialPort class. There are a number of settings that get set differently than I need them to be when I call the SerialPort constructor. Using a port monitor application I have noticed the following:

  1. ReadIntervalTimeout = -1 (should be
    0)
  2. ReadTotalTimeoutMultiplier = -1
    (should be 0)
  3. ReadTotalTimeoutConstant = 1000
    (should be 0)
  4. WriteTotalTimeoutMultiplier = 0 (OK)
  5. WriteTotalTimeoutConstant = 0 (OK)
  6. EoFChar = 26 (should be 0)
  7. ErrorChar = 63 (should be 0)
  8. Break char = 63 (should be 0)
  9. XOn Limit = 1024 (should be 2048)
  10. XOff Limit = 1024 (should be 512)
  11. FlowReplace = 0x87 (should be 0)

How do I change these settings (I'm using C#)?

Best Answer

Those values cannot be set with the SerialPort wrapper class. It is an incomplete wrapper. You can look here for an example of changing the XON and XOFF characters. For the rest you'll have to refer to the DCB documentation.

Updated

The DCB flag values are bit fields in the DCB structure.

DWORD fBinary  :1;            // Bit 0
DWORD fParity  :1;            // Bit 1
DWORD fOutxCtsFlow  :1;       // Bit 2
DWORD fOutxDsrFlow  :1;       // Bit 3
DWORD fDtrControl  :2;        // Bit 4 - 5
DWORD fDsrSensitivity  :1;    // Bit 6
DWORD fTXContinueOnXoff  :1;  // Bit 7
DWORD fOutX  :1;              // Bit 8
DWORD fInX  :1;               // Bit 9
DWORD fErrorChar  :1;         // Bit 10
DWORD fNull  :1;              // Bit 11
DWORD fRtsControl  :2;        // Bit 12 - 13
DWORD fAbortOnError  :1;      // Bit 14
DWORD fDummy2  :17;           // Bit 15 - 31

And in case you were wondering how SetDcbFlag figures out which bits you're manipulating, here it is (courtesy of Reflector):

internal void SetDcbFlag(int whichFlag, int setting)
{
    uint mask;
    if ((whichFlag == 4) || (whichFlag == 12))
        mask = 3;
    else if (whichFlag == 15)
        mask = 0x1ffff;
    else
        mask = 1;
    this.dcb.Flags &= ~(mask << whichFlag);
    this.dcb.Flags |= ((uint)setting << whichFlag);
}

You can see that for Bit #4 or #12 it uses a 2-bit mask, for Bit #15 a 17-bit mask, and for the rest a 1-bit mask.

Related Topic