Setting serial RS232 port settings; any in C# alternatives to SerialPort class?

我们两清 提交于 2019-12-13 15:18:37

问题


In my .NET application I need to achieve serial port setup equivalent to this C++ managed code:

::SetCommMask(m_hCOMM, EV_RXCHAR);  
::SetupComm(m_hCOMM, 9*2*128*10, 400);
::PurgeComm(m_hCOMM, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);

COMMTIMEOUTS timeOut;
timeOut.ReadIntervalTimeout        = 3;
timeOut.ReadTotalTimeoutConstant   = 3;
timeOut.ReadTotalTimeoutMultiplier = 1; 
timeOut.WriteTotalTimeoutConstant  = 0;
timeOut.WriteTotalTimeoutMultiplier= 0;
int nRet= ::SetCommTimeouts(m_hCOMM, &timeOut); 

::EscapeCommFunction(m_hCOMM, SETDTR);  
::EscapeCommFunction(m_hCOMM, SETRTS);      

DCB dcb;
memset(&dcb, 0, sizeof(DCB));
dcb.BaudRate= m_nSpeed; 
dcb.ByteSize= 8;
dcb.fParity = FALSE;
dcb.Parity  = NOPARITY;
dcb.StopBits= ONESTOPBIT;
dcb.fBinary = TRUE;


dcb.fDsrSensitivity= FALSE; 

dcb.fOutxDsrFlow= FALSE;        
dcb.fOutxCtsFlow= FALSE;            


dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
dcb.fRtsControl = RTS_CONTROL_TOGGLE;

nRet= ::SetCommState(m_hCOMM, &dcb);

Is it possible at all? How do I approach this problem? Are there any (preferable free) libraries that allow such low level serial port control or should I create my own wrapper on top of Win32 api? Anyone did anything similar or has an idea how to 'glue' win32 serial port api with .net so that I can use neat .NET DataReceived() events ? Or maybe I can create .NET SerialPort instance and then modify it using managed API?


回答1:


The .NET SerialPort class has most of what you need.

p = SerialPort.SerialPort(); //use whichever constructor you need

p.DiscarInBuffer();
p.DiscardOutbuffer();
p.ReadBufferSize = 9*2*128*10;
p.WriteBufferSize = 400;


p.ReadTimeout = 10; //not exactly equivalent to COMMTIMEOUTS
p.WriteTimeout = 0;

p.DtrEnable = true;
p.RtsEnable = true;

p.BaudRate = m_nSpeed;
p.DataBits = 8;
p.Parity = Parity.None;
p.StopBits = StopBits.One;

//I think DSR and CTS states are pollable by app but ignored by driver 


来源:https://stackoverflow.com/questions/2949086/setting-serial-rs232-port-settings-any-in-c-sharp-alternatives-to-serialport-cl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!