C # Use DataReceived to receive serial port data in hexadecimal format)

Source: Internet
Author: User

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;
If (serialPort1.IsOpen)
{
SerialPort1.Close ();
}
TextChanged + = new UpdateTextEventHandler (ChangeText); // Add the event handling method to the event, which is indispensable
Try
{
SerialPort1.Open ();
}
Catch (System. Exception ex)
{
MessageBox. Show (string. Format ("failed to open the serial port. Please check whether it is connected. \ N "+ ex. Message ));
Return;
}
}

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

Private delegate void UpdateTextEventHandler (string text); // defines the delegate

Private event UpdateTextEventHandler textChanged; // defines the event

Private void ChangeText (string text) // event handling method www.2cto.com
{
String text1 = string. Empty;
Text1 = text. Trim (). Substring (10, 1 );
String s1 = string. Empty;
S1 = text. Trim (). Substring (10, 4 );
Int dec1 = Convert. ToInt32 (s1, 16); // enter 10 for the s1 segment.
If (text1 = "0") // Delete 10
{
Decimal dda1 = Math. Round (decimal) dec1/10, 1); // save one small number except 10.
TextBox5.Text = dda1.ToString (CultureInfo. InvariantCulture). Trim ();
}
Else // xor ffff
{
Int d1 = (dec1 ^ Convert. ToInt32 ("FFFF", 16) + 1;
Decimal dd1 = Math. Round (decimal) d1/10, 1); // save one small number except 10.
TextBox5.Text = dd1.ToString (CultureInfo. InvariantCulture). Trim ();
}

String s2 = text. Trim (). Substring (14, 4 );
Int d2 = Convert. ToInt32 (s2, 16); // s2 returns 10 bytes.
Decimal dd2 = Math. Round (decimal) d2/10, 2); // save one small number except 10.
TextBox6.Text = dd2.ToString (CultureInfo. InvariantCulture). Trim ();

String text3 = text. Trim (). Substring (18, 1 );
String s3 = text. Trim (). Substring (18, 4 );
Int dec3 = Convert. ToInt32 (s3, 16); // s3 returns 10 bytes
If (text3 = "0 ")
{
Decimal dda3 = Math. Round (decimal) dec3/10, 1); // save one small number except 10.
TextBox7.Text = dda3.ToString (CultureInfo. InvariantCulture). Trim ();
}
Else // xor ffff
{
Int d3 = (dec3 ^ Convert. ToInt32 ("FFFF", 16) + 1;
Decimal dd3 = Math. Round (decimal) d3/10, 1); // save one small number except 10.
TextBox7.Text = string. Format ("-{0}", dd3.ToString (CultureInfo. InvariantCulture). Trim ());
}
}

Private void serialPort1_DataReceived (object sender, System. IO. Ports. SerialDataReceivedEventArgs e)
{
Thread. Sleep (100); // reading speed is too slow. Adding Sleep to extend the reading time is indispensable.
SerialPort1.Read (buffer, 0, buffersize );
// String text = Encoding. ASCII. GetString (buffer); // ASCII card code
String txt = ByteToHexStr (buffer); // use a function to convert hexadecimal data.
SerialPort1.DiscardInBuffer ();
This. Invoke (textChanged, new string [] {txt}); // call the event through Invoke
}

 


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.