C#操作串口,帶異常處理,解決連接埠佔用時開啟串口出現異常錯誤,串口關閉時發送資料報錯

來源:互聯網
上載者:User

 

using System;

namespace chuankou
{
///
/// Class1 的摘要說明。
///
class send
{
///
/// 應用程式的主進入點。
///
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此處添加代碼以啟動應用程式
//
chuankou.CommPort ss_port = new chuankou.CommPort();
ss_port.PortNum = "COM1"; //連接埠號碼
ss_port.BaudRate = 19200; //串口通訊傳輸速率
ss_port.ByteSize = 8; //資料位元
ss_port.Parity = 0; //同位
ss_port.StopBits = 1;//停止位
ss_port.ReadTimeout = 1000; //讀逾時
try
{
if (ss_port.Opened)
  {
   ss_port.Close();
   ss_port.Open(); //開啟串口
  }
else
{
  ss_port.Open();//開啟串口
}
//return true;
}
catch(Exception e)
{
        Console.WriteLine("錯誤:" + e.Message);
//return false;
}
try
{
        ss_port.Write(System.Text.Encoding.Default.GetBytes("xxxxxxxxxxxxx"));
}
catch(Exception e)
{
        Console.WriteLine("錯誤:" + e.Message);
//return false;
}
Console.WriteLine("輸出完畢");
Console.ReadLine();

}
}

}

類檔案

using System;
using System.Runtime.InteropServices;

namespace chuankou
{
///
/// io 的摘要說明。
///
class CommPort
{

public string PortNum;
public int BaudRate;
public byte ByteSize;
public byte Parity; // 0-4=no,odd,even,mark,space
public byte StopBits; // 0,1,2 = 1, 1.5, 2
public int ReadTimeout;

//comm port win32 file handle
private int hComm = -1;

public bool Opened = false;

//win32 api constants
private const uint GENERIC_READ = 0x80000000;
private const uint GENERIC_WRITE = 0x40000000;
private const int OPEN_EXISTING = 3;
private const int INVALID_HANDLE_VALUE = -1;

[StructLayout(LayoutKind.Sequential)]
public struct DCB
{
//taken from c struct in platform sdk
public int DCBlength; // sizeof(DCB)
public int BaudRate; // 指定當前傳輸速率 current baud rate
// these are the c struct bit fields, bit twiddle flag to set
public int fBinary; // 指定是否允許二進位模式,在windows95中必須主TRUE binary mode, no EOF check
public int fParity; // 指定是否允許同位 enable parity checking
public int fOutxCtsFlow; // 指定CTS是否用於檢測發送控制,當為TRUE是CTS為OFF,發送將被掛起。 CTS output flow control

public int fOutxDsrFlow; // 指定CTS是否用於檢測發送控制 DSR output flow control
public int fDtrControl; // DTR_CONTROL_DISABLE值將DTR置為OFF, DTR_CONTROL_ENABLE值將DTR置為ON, DTR_CONTROL_HANDSHAKE允許DTR"握手" DTR flow control type

public int fDsrSensitivity; // 當該值為TRUE時DSR為OFF時接收的位元組被忽略 DSR sensitivity
public int fTXContinueOnXoff; // 指定當接收緩衝區已滿,並且驅動程式已經發送出XoffChar字元時發送是否停止。TRUE時,在接收緩衝區接收到緩衝區已滿的位元組XoffLim且驅動程式已經發送出XoffChar字元中止接收位元組之後,發送繼續進行。 FALSE時,在接收緩衝區接收到代表緩衝區已空的位元組XonChar且驅動程式已經發送出恢複發送的XonChar之後,發送繼續進行。XOFF continues Tx

public int fOutX; // TRUE時,接收到XoffChar之後便停止發送接收到XonChar之後將重新開始 XON/XOFF out flow control

public int fInX; // TRUE時,接收緩衝區接收到代表緩衝區滿的XoffLim之後,XoffChar發送出去接收緩衝區接收到代表緩衝區空的XonLim之後,XonChar發送出去 XON/XOFF in flow control

public int fErrorChar; // 該值為TRUE且fParity為TRUE時,用ErrorChar 成員指定的字元代替同位錯誤的接收字元 enable error replacement

public int fNull; // eTRUE時,接收時去掉空(0值)位元組 enable null stripping
public int fRtsControl; // RTS flow control
/*RTS_CONTROL_DISABLE時,RTS置為OFF
  RTS_CONTROL_ENABLE時, RTS置為ON
   RTS_CONTROL_HANDSHAKE時,
   當接收緩衝區小於半滿時RTS為ON
    當接收緩衝區超過四分之三滿時RTS為OFF
   RTS_CONTROL_TOGGLE時,
   當接收緩衝區仍有剩餘位元組時RTS為ON ,否則預設為OFF*/

public int fAbortOnError; // TRUE時,有錯誤發生時中止讀和寫操作 abort on error
public int fDummy2; // 未使用 reserved

public uint flags;
public ushort wReserved; // 未使用,必須為0 not currently used
public ushort XonLim; // 指定在XON字元發送這前接收緩衝區中可允許的最小位元組數 transmit XON threshold
public ushort XoffLim; // 指定在XOFF字元發送這前接收緩衝區中可允許的最小位元組數 transmit XOFF threshold
public byte ByteSize; // 指定連接埠當前使用的資料位元 number of bits/byte, 4-8
public byte Parity; // 指定連接埠當前使用的同位方法,可能為:EVENPARITY,MARKPARITY,NOPARITY,ODDPARITY 0-4=no,odd,even,mark,space

public byte StopBits; // 指定連接埠當前使用的停止位元,可能為:ONESTOPBIT,ONE5STOPBITS,TWOSTOPBITS 0,1,2 = 1, 1.5, 2

public char XonChar; // 指定用於發送和接收字元XON的值 Tx and Rx XON character
public char XoffChar; // 指定用於發送和接收字元XOFF值 Tx and Rx XOFF character
public char ErrorChar; // 本字元用來代替接收到的同位發生錯誤時的值 error replacement character
public char EofChar; // 當沒有使用二進位模式時,本字元可用來指示資料的結束 end of input character
public char EvtChar; // 當接收到此字元時,會產生一個事件 received event character
public ushort wReserved1; // 未使用 reserved; do not use
}

[StructLayout(LayoutKind.Sequential)]
private struct COMMTIMEOUTS
{
public int ReadIntervalTimeout;
public int ReadTotalTimeoutMultiplier;
public int ReadTotalTimeoutConstant;
public int WriteTotalTimeoutMultiplier;
public int WriteTotalTimeoutConstant;
}

[StructLayout(LayoutKind.Sequential)]
private struct OVERLAPPED
{
public int Internal;
public int InternalHigh;
public int Offset;
public int OffsetHigh;
public int hEvent;
}

[DllImport("kernel32.dll")]
private static extern int CreateFile(
string lpFileName, // 要開啟的串口名稱
uint dwDesiredAccess, // 指定串口的訪問方式,一般設定為可讀可寫方式
int dwShareMode, // 指定串口的共用模式,串口不能共用,所以設定為0
int lpSecurityAttributes, // 設定串口的安全屬性,WIN9X下不支援,應設為NULL
int dwCreationDisposition, // 對於串口通訊,建立方式只能為OPEN_EXISTING
int dwFlagsAndAttributes, // 指定串口屬性與標誌,設定為FILE_FLAG_OVERLAPPED(重疊I/O操作),指定串口以非同步方式通訊
int hTemplateFile // 對於串口通訊必須設定為NULL
);
[DllImport("kernel32.dll")]
private static extern bool GetCommState(
int hFile, //通訊裝置控制代碼
ref DCB lpDCB // 裝置控制塊DCB
);
[DllImport("kernel32.dll")]
private static extern bool BuildCommDCB(
string lpDef, // 裝置控制字元串
ref DCB lpDCB // 裝置控制塊
);
[DllImport("kernel32.dll")]
private static extern bool SetCommState(
int hFile, // 通訊裝置控制代碼
ref DCB lpDCB // 裝置控制塊
);
[DllImport("kernel32.dll")]
private static extern bool GetCommTimeouts(
int hFile, // 通訊裝置控制代碼 handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // 逾時時間 time-out values
);
[DllImport("kernel32.dll")]
private static extern bool SetCommTimeouts(
int hFile, // 通訊裝置控制代碼 handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // 逾時時間 time-out values
);
[DllImport("kernel32.dll")]
private static extern bool ReadFile(
int hFile, // 通訊裝置控制代碼 handle to file
byte[] lpBuffer, // 資料緩衝區 data buffer
int nNumberOfBytesToRead, // 多少位元組等待讀取 number of bytes to read
ref int lpNumberOfBytesRead, // 讀取多少位元組 number of bytes read
ref OVERLAPPED lpOverlapped // 溢出緩衝區 overlapped buffer
);
[DllImport("kernel32.dll")]
private static extern bool WriteFile(
int hFile, // 通訊裝置控制代碼 handle to file
byte[] lpBuffer, // 資料緩衝區 data buffer
int nNumberOfBytesToWrite, // 多少位元組等待寫入 number of bytes to write
ref int lpNumberOfBytesWritten, // 已經寫入多少位元組 number of bytes written
ref OVERLAPPED lpOverlapped // 溢出緩衝區 overlapped buffer
);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(
int hObject // handle to object
);
[DllImport("kernel32.dll")]
private static extern uint GetLastError();

public void Open()
{

DCB dcbCommPort = new DCB();
COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();

// 開啟串口 OPEN THE COMM PORT.
hComm = CreateFile(PortNum ,GENERIC_READ | GENERIC_WRITE,0, 0,OPEN_EXISTING,0,0);
// 如果串口沒有開啟,就開啟 IF THE PORT CANNOT BE OPENED, BAIL OUT.
if(hComm == INVALID_HANDLE_VALUE)
{
throw(new ApplicationException("非法操作,不能開啟串口!"));
}

// 設定通訊逾時時間 SET THE COMM TIMEOUTS.
GetCommTimeouts(hComm,ref ctoCommPort);
ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout;
ctoCommPort.ReadTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(hComm,ref ctoCommPort);

// 設定串口 SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
GetCommState(hComm, ref dcbCommPort);
dcbCommPort.BaudRate=BaudRate;
dcbCommPort.flags=0;
//dcb.fBinary=1;
dcbCommPort.flags|=1;
if (Parity>0)
{
//dcb.fParity=1
dcbCommPort.flags|=2;
}
dcbCommPort.Parity=Parity;
dcbCommPort.ByteSize=ByteSize;
dcbCommPort.StopBits=StopBits;
if (!SetCommState(hComm, ref dcbCommPort))
{
//uint ErrorNum=GetLastError();
throw(new ApplicationException("非法操作,不能開啟串口!"));
}
//unremark to see if setting took correctly
//DCB dcbCommPort2 = new DCB();
//GetCommState(hComm, ref dcbCommPort2);
Opened = true;
}

public void Close()
{
if (hComm!=INVALID_HANDLE_VALUE)
{
CloseHandle(hComm);
}
}

public byte[] Read(int NumBytes)
{
byte[] BufBytes;
byte[] OutBytes;
BufBytes = new byte[NumBytes];
if (hComm!=INVALID_HANDLE_VALUE)
{
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesRead=0;
ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort);
OutBytes = new byte[BytesRead];
Array.Copy(BufBytes,OutBytes,BytesRead);
}
else
{
throw(new ApplicationException("串口未開啟!"));
}
return OutBytes;
}

public void Write(byte[] WriteBytes)
{
if (hComm!=INVALID_HANDLE_VALUE)
{
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesWritten = 0;
WriteFile(hComm,WriteBytes,WriteBytes.Length,ref BytesWritten,ref ovlCommPort);
}
else
{
throw(new ApplicationException("串口未開啟!"));
}
}
}

class HexCon
{
// 把十六進位字串轉換成位元組型和把位元組型轉換成十六進位字串 converter hex string to byte and byte to hex string
public static string ByteToString(byte[] InBytes)
{
string StringOut="";
foreach (byte InByte in InBytes)
{
StringOut=StringOut + String.Format("{0:X2} ",InByte);
}
return StringOut;
}
public static byte[] StringToByte(string InString)
{
string[] ByteStrings;
ByteStrings = InString.Split(" ".ToCharArray());
byte[] ByteOut;
ByteOut = new byte[ByteStrings.Length-1];
for (int i = 0;i==ByteStrings.Length-1;i++)
{
ByteOut[i] = Convert.ToByte(("0x" + ByteStrings[i]));
}
return ByteOut;
}
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.