using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO.Ports; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); serialPort1.Open(); } private void Form1_Load(object sender, EventArgs e) { //configuring the serial port serialPort1.PortName = "COM15"; serialPort1.BaudRate = 115200; serialPort1.DataBits = 8; serialPort1.Parity = Parity.None; serialPort1.StopBits = StopBits.One; serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived); } public enum MessageType { Incoming, Outgoing, Normal, Warning, Error }; private byte[] HexToByte(string msg) { //remove any spaces from the string msg = msg.Replace(" ", ""); //create a byte array the length of the //divided by 2 (Hex is 2 characters in length) byte[] comBuffer = new byte[msg.Length / 2]; //loop through the length of the provided string for (int i = 0; i < msg.Length; i += 2) //convert each set of 2 characters to a byte //and add to the array comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16); //return the array byte[] newbuffer = comBuffer; return comBuffer; } private string ByteToHex(byte[] comByte) { //create a new StringBuilder object StringBuilder builder = new StringBuilder(comByte.Length * 3); //loop through each byte in the array foreach (byte data in comByte) //convert the byte to a string and add to the stringbuilder builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' ')); //return the converted value return builder.ToString().ToUpper(); } #region DisplayData private void DisplayData(MessageType type, string msg) { richTextBox1.Invoke(new EventHandler(delegate { richTextBox1.SelectedText = string.Empty; richTextBox1.AppendText(msg); richTextBox1.ScrollToCaret(); })); } #endregion private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { int bytes = serialPort1.BytesToRead; //create a byte array to hold the awaiting data byte[] comBuffer = new byte[bytes]; //read the data and store it serialPort1.Read(comBuffer, 0, bytes); //display the data to the user DisplayData(MessageType.Incoming, ByteToHex(comBuffer) + "\n"); }
DisplayData(MessageType.Incoming, ByteToHex(comBuffer) + "\n");
string substring = string.Empty; if( message.Length > 54) substring = msg.Substring(54, 4); richTextBox1.AppendText(substring);
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)