C # Serial Communication,

Source: Internet
Author: User

C # Serial Communication,

Send data through COM1, and COM2 receives data. After COM2 receives the data sent this time, it sends a message to COM1 to notify COM1 that the data has been sent. After COM1 receives the notification, it sends the next data segment. This ensures that the data sent each time is correctly received.

Code:

Using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. linq; using System. text; using System. windows. forms; using System. IO. ports; using System. threading; using Utils; namespace serial communication {public partial class Form1: Form {# region variable // <summary> // start or stop, true start, false stop /// </summary> public static bool start = true; // <summary> /// Serial Port resources /// </summary> private static SerialPort serialPort1 = null; /// <summary> /// serial port resource /// </summary> private static SerialPort serialPort2 = null; /// <summary> /// number of successes /// </summary> private static int successCount = 0; /// <summary> /// number of failures /// </summary> private static int errorCount = 0; /// <summary> /// the total number of times the previous calculation was performed /// </summary> private static int lastCount = 0; /// <summary> /// timer /// </Summary> private System. windows. forms. timer timer = new System. windows. forms. timer (); # endregion # region Form1 public Form1 () {InitializeComponent () ;}# endregion # region formparts load private void Form1_Load (object sender, EventArgs e) {serialPort1 = new SerialPort ("COM1"); serialPort1.DataReceived + = new SerialDataReceivedEventHandler (serialPort_DataReceived1); serialPort1.Open (); serialPort2 = New SerialPort ("COM2"); centers + = new centers (centers); serialPort2.Open () ;}# endregion # region form=formclosed private void form=formclosed (object sender, FormClosedEventArgs e) {serialPort1.Close (); serialPort1.Dispose (); serialPort2.Close (); serialPort2.Dispose () ;}# endregion # region btnStart_Click private void btnStart_Click (obje Ct sender, EventArgs e) {start = true; SendData (); timer. interval = 500; timer. tick + = new EventHandler (delegate (object obj, EventArgs eventArgs) {if (lastCount = 0) {lastCount = successCount + errorCount ;} else {int cnt = successCount + errorCount-lastCount; cnt = Data. length * cnt/1024 * (1000/timer. interval); double total = (successCount + errorCount) * Data. length/1024.0; InvokeD Elegate invokeDelegate = delegate () {label3.Text = cnt. toString () + "KB/S" + total. toString ("#. 0 ") +" KB ";}; InvokeUtil. invoke (this, invokeDelegate); lastCount = successCount + errorCount ;}}); timer. start () ;}# endregion # region btnStop_Click private void btnStop_Click (object sender, EventArgs e) {start = false; timer. stop (); timer. dispose (); timer = new System. windows. forms. timer () ;}# endr Egion # region receives Serial Data Events /// <summary> // receives Serial Data Events /// </summary> /// <param name = "sender"> </ param> // <param name = "e"> </param> public void serialPort_DataReceived1 (object sender, serialDataReceivedEventArgs e) {if (serialPort1.ReadLine ()! = Null) {successCount ++; SendData ();}} /// <summary> /// receives the serial data event // </summary> /// <param name = "sender"> </param> // <param name = "e"> </param> public void serialPort_DataReceived2 (object sender, serialDataReceivedEventArgs e) {List <byte> bList = new List <byte> (); int I = 0; while (serialPort2.BytesToRead> 0) {byte [] bArr = new byte [serialPort2.BytesToRead]; I + = serialPort2.Read (bArr, 0, bAr R. length); bList. addRange (bArr);} serialPort2.WriteLine ("success"); string s = ASCIIEncoding. UTF8.GetString (bList. toArray (); InvokeDelegate invokeDelegate = delegate () {textBox2.Text = s ;}; InvokeUtil. invoke (this, invokeDelegate); if (s! = Str) {errorCount ++; invokeDelegate = delegate () {label2.Text = errorCount + "Unequal times (failed)" ;}; InvokeUtil. invoke (this, invokeDelegate);} else {invokeDelegate = delegate () {label1.Text = successCount + "equal (successful)" ;}; InvokeUtil. invoke (this, invokeDelegate) ;}# endregion # region sends data private void SendData () {if (start) {Thread thread = new Thread (new ParameterizedThreadStart (delegate (object obj) {InvokeDelegate invokeDelegate = delegate () {textBox1.Text = Str ;}; InvokeUtil. invoke (this, invokeDelegate); serialPort1.Write (Data, 0, Data. length) ;}); thread. start () ;}# endregion # region data private static byte [] data = null; /// <summary> /// Data /// </summary> private static byte [] data {get {if (data = null) {Data = ASCIIEncoding. UTF8.GetBytes (Str);} return data ;}# endregion # region obtains the string private static string str = null; /// <summary> /// string /// </summary> private static string Str {get {if (str = null) {StringBuilder sb = new StringBuilder (); for (int I = 0; I <270; I ++) {sb. append ("computer program");} str = sb. toString () ;}return str ;}# endregion }}View Code

Auxiliary code:

Using System; using System. collections. generic; using System. text; using System. windows. forms; namespace Utils {// <summary> // delegate to the Cross-thread access control /// </summary> public delegate void InvokeDelegate (); /// <summary> /// cross-thread access control class /// </summary> public class InvokeUtil {/// <summary> // cross-thread access control // /</summary> /// <param name = "ctrl"> Form object </param> /// <param name = "de"> DeleGate </param> public static void Invoke (Control ctrl, delegate de) {if (ctrl. isHandleCreated) {ctrl. beginInvoke (de );}}}}View Code

 

Using System; using System. collections. generic; using System. linq; using System. text; using Microsoft. win32; using System. security. permissions; using System. IO. ports; using System. security; namespace Utils {// <summary> // serial port resource tool class /// </summary> public class SerialPortUtil {# region obtains the serial port list of the local machine, including virtual serial port // <summary> // obtain the list of local serial ports, including virtual serial ports // </summary> public static string [] GetCOMList () {List <string> list = New List <string> (); foreach (string portName in SerialPort. getPortNames () {list. add (portName);} return list. toArray ();} # endregion # region obtain the local serial port list from the Registry /// <summary> /// obtain the local serial port list from the Registry /// </summary> public static string [] GetPortNames () {RegistryKey localMachine = null; RegistryKey key2 = null; string [] textArray = null; // here is an asserted to determine whether the registry key has new RegistryPermission (RegistryPermissionAccess. read, @ "HKEY_LOCAL_MACHINE \ HARDWARE \ DEVICEMAP \ SERIALCOMM "). assert (); try {localMachine = Registry. localMachine; key2 = localMachine. openSubKey (@ "HARDWARE \ DEVICEMAP \ SERIALCOMM", false); if (key2! = Null) {string [] valueNames = key2.GetValueNames (); textArray = new string [valueNames. length]; for (int I = 0; I <valueNames. length; I ++) {textArray [I] = (string) key2.GetValue (valueNames [I]) ;}} finally {if (localMachine! = Null) {localMachine. Close ();} if (key2! = Null) {key2.Close ();} CodeAccessPermission. revertAssert () ;}if (textArray = null) {textArray = new string [0] ;}return textArray ;}# endregion }}View Code

 

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.