C # programming of Serial Communication (Modified Version)

Source: Internet
Author: User

This is a serial communication class that is down from the Internet. It is found that the close function forgot to set the Opened attribute to false.
In addition, the following functions for converting string to byte [] and byte [] to string are incorrectly deleted.
The modified serial communication class is as follows:
In the next article, I will paste all the code of the main program of my test program
It can be brave enough to implement serial communication.

Using System;
Using System. Runtime. InteropServices;

Namespace BusApp
{
/// <Summary>
///
/// </Summary>
Public class mycom
{
Public mycom ()
{
//
// TODO: add the constructor logic here
//
}
Public int PortNum; // 1, 2, 3, 4
Public int BaudRate; // random, 2400, 4800,9600
Public byte ByteSize; // 8 bits
Public byte Parity; // 0-4 = no, odd, even, mark, space
Public byte StopBits; // 0, 1, 2 = 1, 1.5, 2
Public int ReadTimeout; // 10
 
// 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)]
Private struct DCB
{
// Taken from c struct in platform sdk
Public int DCBlength; // sizeof (DCB)
Public int BaudRate; // current baud rate
Public int fBinary; // binary mode, no EOF check
Public int fParity; // enable parity checking
Public int fOutxCtsFlow; // CTS output flow control
Public int fOutxDsrFlow; // DSR output flow control
Public int fDtrControl; // DTR flow control type
Public int fdsrsensiti.pdf; // DSR sensiti.pdf
Public int fTXContinueOnXoff; // XOFF continues Tx
Public int fOutX; // XON/XOFF out flow control
Public int fInX; // XON/XOFF in flow control
Public int fErrorChar; // enable error replacement
Public int fNull; // enable null stripping
Public int fRtsControl; // RTS flow control
Public int fAbortOnError; // abort on error
Public int fDummy2; // reserved
Public ushort wReserved; // not currently used
Public ushort XonLim; // transmit XON threshold
Public ushort XoffLim; // transmit XOFF threshold
Public byte ByteSize; // number of bits/byte, 4-8
Public byte Parity; // 0-4 = no, odd, even, mark, space
Public byte StopBits; // 0, 1, 2 = 1, 1.5, 2
Public char XonChar; // Tx and Rx XON character
Public char XoffChar; // Tx and Rx XOFF character
Public char ErrorChar; // error replacement character
Public char EofChar; // end of input character
Public char EvtChar; // encoded ed 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, // file name
Uint dwDesiredAccess, // access mode
Int dww.mode, // share mode
Int lpSecurityAttributes, // SD
Int dwCreationDisposition, // how to create
Int dwFlagsAndAttributes, // file attributes
Int hTemplateFile // handle to template file
);
[DllImport ("kernel32.dll")]
Private static extern bool GetCommState (
Int hFile, // handle to communications device
Ref DCB lpDCB // device-control block
);
[DllImport ("kernel32.dll")]
Private static extern bool BuildCommDCB (
String lpDef, // device-control string
Ref DCB lpDCB // device-control block
);
[DllImport ("kernel32.dll")]
Private static extern bool SetCommState (
Int hFile, // handle to communications device
Ref DCB lpDCB // device-control block
);
[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
);
 
Public void Open ()
{

DCB dcbcommp ORT = new DCB ();
COMMTIMEOUTS ctocommp ORT = new COMMTIMEOUTS ();


// Open the comm port.


HComm = CreateFile ("COM" + 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 ("Comm Port Can Not Be Opened "));
}
 
// Set the comm timeouts.

GetCommTimeouts (hComm, ref ctocommp ORT );
Ctocommp ORT. ReadTotalTimeoutConstant = ReadTimeout;
Ctocommp ORT. ReadTotalTimeoutMultiplier = 0;
Ctocommp ORT. WriteTotalTimeoutMultiplier = 0;
Ctocommp ORT. WriteTotalTimeoutConstant = 0;
SetCommTimeouts (hComm, ref ctocommp ORT );
 
// Set baud rate, PARITY, word size, and stop bits.
// There are other ways of doing setting these but this is the easiest.
// If you want to later add code for other baud rates, REMEMBER
// That the argument for BuildCommDCB must be a pointer to a string.
// Also note that BuildCommDCB () defaults to no handshaking.
 
Dcbcommort. DCBlength = Marshal. SizeOf (dcbcommort );
GetCommState (hComm, ref dcbcommp ORT );
Dcbcommp ORT. BaudRate = BaudRate;
Dcbcommp ORT. Parity = Parity;
Dcbcommp ORT. ByteSize = ByteSize;
Dcbcommp ORT. StopBits = StopBits;
SetCommState (hComm, ref dcbcommp ORT );

Opened = true;

}
 
Public void Close ()
{
If (hComm! = INVALID_HANDLE_VALUE)
{
CloseHandle (hComm );
Opened = false;
}
}
 
Public byte [] Read (int NumBytes)
{
Byte [] BufBytes;
Byte [] OutBytes;
BufBytes = new byte [NumBytes];
If (hComm! = INVALID_HANDLE_VALUE)
{
OVERLAPPED ovlcommp ORT = new OVERLAPPED ();
Int BytesRead = 0;
ReadFile (hComm, BufBytes, NumBytes, ref BytesRead, ref ovlcommp ORT );
OutBytes = new byte [BytesRead];
Array. Copy (BufBytes, OutBytes, BytesRead );
}
Else
{
Throw (new ApplicationException ("Comm Port Not Open "));
}
Return OutBytes;
}
 
Public int Write (byte [] WriteBytes)
{
Int BytesWritten = 0;
If (hComm! = INVALID_HANDLE_VALUE)
{
OVERLAPPED ovlcommp ORT = new OVERLAPPED ();
WriteFile (hComm, WriteBytes, WriteBytes. Length, ref BytesWritten, ref ovlcommp ORT );
}
Else
{
Throw (new ApplicationException ("Comm Port Not Open "));
}
Return BytesWritten;
}
}
}


From the C #. net java jsp SQL Column

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.