C # operation serial port

Source: Internet
Author: User
C # Serial Port Operations --

Using system;

Namespace Chuankou
{
///
/// Summary of class1.
///
Class send
{
///
/// Application Program .
///
[Stathread]
Static void main (string [] ARGs)
{
//
// Todo: add Code To start the application
//
Chuankou. comatrix ORT ss_port = new Chuankou. comatrix ORT ();
Ss_port.portnum = "COM1"; // port number
Ss_port.baudrate = 19200; // The baud rate of serial communication.
Ss_port.bytesize = 8; // data bit
Ss_port.parity = 0; // parity
Ss_port.stopbits = 1; // stop bit
Ss_port.readtimeout = 1000; // read timeout
Try
{
If (ss_port.opened)
{
Ss_port.close ();
Ss_port.open (); // open the serial port
}
Else
{
Ss_port.open (); // open the serial port
}
// Return true;
}
Catch (exception E)
{
Console. writeline ("error:" + E. Message );
// Return false;
}
Try
{
Ss_port.write (system. Text. encoding. Default. getbytes ("xxxxxxxxxxxxx "));
}
Catch (exception E)
{
Console. writeline ("error:" + E. Message );
// Return false;
}
Console. writeline ("output finished ");
Console. Readline ();

}
}

}

Class File

Using system;
Using system. runtime. interopservices;

Namespace Chuankou
{
///
/// Io summary.
///
Class commp ORT
{

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; // specifies the current baud rate of the current baud rate
// These are the C struct bit fields, bit twiddle flag to set
Public int fbinary; // specifies whether binary mode is allowed. In Windows 95, the primary value is true binary mode, no EOF check.
Public int fparity; // specifies whether to allow parity check enable parity checking
Public int foutxctsflow; // specifies whether the CTS is used to detect sending control. If the value true indicates that the CTS is off, the sending will be suspended. CTS output flow control
Public int foutxdsrflow; // specifies whether the CTS is used to detect the transmission control DSR output flow control
Public int fdtrcontrol; // The dtr_control_disable Value Sets DTR to off. The dtr_control_enable Value Sets DTR to on, And dtr_control_handshake allows DTR "handshake" DTR Flow Control Type
Public int fdsrsensiti.pdf; // when the value is true, the byte received when the DSR is off is ignored by the DSR sensiti.pdf
Public int ftxcontinueonxoff; // specifies whether to stop sending when the receiving buffer is full and the driver has sent xoffchar characters. True: when the receiving buffer receives the byte xofflim that is full in the buffer and the driver has sent the xoffchar character to abort the receiving byte, the sending continues. If this parameter is set to false, the receiving buffer receives the byte xonchar that indicates that the buffer is empty and the driver sends the xonchar to resume sending. Xoff continues TX
Public int foutx; // true: After xoffchar is received, the system stops sending and receives xonchar, and starts Xon/xoff out flow control again.
Public int finx; // true: After the receiving buffer receives the xofflim that indicates the buffer is full, the xoffchar sends the received buffer to the xonlim that indicates the buffer is empty, xonchar sent out Xon/xoff in Flow Control
Public int ferrorchar; // when this value is true and fparity is true, use the character specified by the errorchar member to replace the receiving character enable error replacement of the parity error.
Public int fnull; // when etrue is received, remove the null (0 value) byte enable null stripping.
Public int frtscontrol; // RTS Flow Control
/* When rts_control_disable is enabled, the value of RTS is set to off.
Rts_control_enable
Rts_control_handshake,
When the receiving buffer is less than half full, the RTS is on.
When the receiving buffer exceeds 3/4 full, the RTS is off.
When rts_control_toggle,
When the receiving buffer still has the remaining bytes, the RTS is on. Otherwise, the default value is off */

Public int fabortonerror; // true: When an error occurs, stop the read and write operations abort on error.
Public int fdummy2; // reserved is not used

Public uint flags;
Public ushort wreserved; // unavailable, must be 0 not currently used
Public ushort xonlim; // specify the minimum number of bytes that can be allowed in the buffer before the Xon character is sent. Transmit Xon threshold
Public ushort xofflim; // specify the minimum number of bytes allowed in the buffer before the xoff character is sent. Transmit xoff threshold
Public byte bytesize; // specify the number of bits/byte, 4-8
Public byte parity of the current port. // specify the port's current parity method, which may be: evenparity, markparity, noparity, oddparity 0-4 = No, odd, even, Mark, space
Public byte stopbits; // specify the number of currently used stopbits of the port, which may be onestopbit, one5stopbits, twostopbits 1.5, 2 = 1, 2
Public char xonchar; // specify the Tx and Rx Xon character values for sending and receiving characters.
Public char xoffchar; // specify the xoff value for sending and receiving characters Tx and Rx xoff character
Public char errorchar; // this character is used to replace the value of error replacement character when an error occurs in the received parity check
Public char eofchar; // when the binary mode is not used, this character can be used to indicate the end Of the data. End of input character
Public char evtchar; // when this character is received, an event named Ed event character
Public ushort wreserved1 is generated; // reserved is not used; 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, // name of the serial port to be opened
Uint dwdesiredaccess, // specifies the serial port access mode, which is generally set to readable and writable.
Int dwsharemode, // specify the serial port sharing mode. The serial port cannot be shared, so it is set to 0.
Int lpsecurityattributes, // sets the Security Attribute of the serial port. This parameter is not supported in Win9x and should be set to null.
Int dwcreationdisposition, // for serial communication, the creation method can only be open_existing
Int dwflagsandattributes, // specify the serial port attribute and flag, set to file_flag_overlapped (overlapping I/O operations), specify the serial port to communicate Asynchronously
Int htemplatefile // for serial communication, it must be set to null
);
[Dllimport ("kernel32.dll")]
Private Static extern bool getcommstate (
Int hfile, // communication device handle
Ref DCB lpdcb // Device Control Block DCB
);
[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, // communication device handle
Ref DCB lpdcb // Device Control Block
);
[Dllimport ("kernel32.dll")]
Private Static extern bool getcommtimeouts (
Int hfile, // communication device handle to comm device
Ref commtimeouts lpcommtimeouts // timeout time-out values
);
[Dllimport ("kernel32.dll")]
Private Static extern bool setcommtimeouts (
Int hfile, // communication device handle to comm device
Ref commtimeouts lpcommtimeouts // timeout time-out values
);
[Dllimport ("kernel32.dll")]
Private Static extern bool readfile (
Int hfile, // communication device handle to file
Byte [] lpbuffer, // data buffer
Int nnumberofbytestoread, // how many bytes are waiting to be read number of bytes to read
Ref int lpnumberofbytesread, // number of bytes read
Ref overlapped lpoverlapped // overflow buffer overlapped Buffer
);
[Dllimport ("kernel32.dll")]
Private Static extern bool writefile (
Int hfile, // communication device handle to file
Byte [] lpbuffer, // data buffer
Int nnumberofbytestowrite, // how many bytes are waiting to be written to number of bytes to write
Ref int lpnumberofbyteswritten, // how many bytes number of bytes written have been written
Ref overlapped lpoverlapped // overflow buffer 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 dcbcommp ORT = new DCB ();
Commtimeouts ctocommp ORT = new commtimeouts ();

// Open the COMM port on the serial port.
Hcomm = createfile (portnum, generic_read | generic_write, 0, 0, open_existing, 0, 0 );
// If the serial port is not enabled, open if the port cannot be opened, bail out.
If (hcomm = invalid_handle_value)
{
Throw (New applicationexception ("illegal operation, cannot open the serial port! "));
}

// set the communication timeout value set the comm timeouts.
getcommtimeouts (hcomm, ref ctocomatrix);
ctocomatrix. readtotaltimeoutconstant = readtimeout;
ctocommp ort. readtotaltimeoutmultiplier = 0;
ctocommp ort. writetotaltimeoutmultiplier = 0;
ctocommp ort. writetotaltimeoutconstant = 0;
setcommtimeouts (hcomm, ref ctocommp ORT);

// Set the serial port set baud rate, parity, word size, and stop bits.
Getcommstate (hcomm, ref dcbcommp ORT );
Dcbcommp ORT. baudrate = baudrate;
Dcbcommp ORT. Flags = 0;
// DCB. fbinary = 1;
Dcbcommp ORT. Flags | = 1;
If (parity> 0)
{
// DCB. fparity = 1
Dcbcommp ORT. Flags | = 2;
}
Dcbcommp ORT. Parity = parity;
Dcbcommp ORT. bytesize = bytesize;
Dcbcommp ORT. stopbits = stopbits;
If (! Setcommstate (hcomm, ref dcbcommp ORT ))
{
// Uint errornum = getlasterror ();
Throw (New applicationexception ("illegal operation, cannot open the serial port! "));
}
// Unremark to see if setting took correctly
// DCB dcbcomatrix ort2 = new DCB ();
// Getcommstate (hcomm, ref dcbcommp ort2 );
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 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 ("the serial port is not enabled! "));
}
Return outbytes;
}

Public void write (byte [] writebytes)
{
If (hcomm! = Invalid_handle_value)
{
Overlapped ovlcommp ORT = new overlapped ();
Int byteswritten = 0;
Writefile (hcomm, writebytes, writebytes. length, ref byteswritten, ref ovlcommp ORT );
}
Else
{
Throw (New applicationexception ("the serial port is not enabled! "));
}
}
}

class hexcon
{< br> // converts a hexadecimal string to a byte string and converts a byte string to a hexadecimal string converter hex string to byte and byte. to hex string
Public static string bytetostring (byte [] inbytes)
{< br> string stringout = "";
foreach (byte inbyte in inbytes)
{< br> stringout = stringout + String. format ("{0: X2}", inbyte);
}< br> return stringout;
}< br> Public static byte [] stringtobyte (string instring)
{< br> string [] bytestrings;
bytestrings = instring. split ("". tochararray ();
byte [] byteout;
byteout = new byte [bytestrings. length-1];
for (INT I = 0; I = bytestrings. length-1; I ++)
{< br> byteout = convert. tobyte ("0x" + bytestrings );
}< br> return byteout;
}< BR >}< br>

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.