C # receives hexadecimal serial port data (com) and displays the data in textbox.

Source: Internet
Author: User

Static int buffersize = 18; // hexadecimal size (6 bytes)
Byte [] buffer = new Byte [buffersize]; // create a buffer

Private void button#click (object sender, EventArgs e)
{
SerialPort1.Read (buffer, 0, buffersize );
String ss;
Ss = byteToHexStr (buffer); // The byteToHexStr function is used.
TextBox2.Text = ss;
SerialPort1.Close ();
MessageBox. Show ("data received successfully! "," System prompt ");
}

// Convert byte array to hexadecimal string
Public static string byteToHexStr (byte [] bytes)
{
String returnStr = "";
If (bytes! = Null)
{
For (int I = 0; I <bytes. Length; I ++)
{
ReturnStr + = bytes [I]. ToString ("X2 ");
}
}
Return returnStr;
}

Private void Form1_Load (object sender, EventArgs e)
{
SerialPort1.PortName = "COM1 ";
SerialPort1.BaudRate = 9600;
SerialPort1.DataBits = 8; // data bit
SerialPort1.Parity = System. IO. Ports. Parity. None; // No Parity bit
SerialPort1.StopBits = System. IO. Ports. StopBits. One; // a stop bit
SerialPort1.ReadBufferSize = 1024; // size of the receiving buffer
SerialPort1.Encoding = Encoding. BigEndianUnicode;
SerialPort1.Open ();
}

 


From brian0031

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.