C # Programming serial port (a)

In this chapter we begin serial design applications, designed for serial, before we have explained before, but that time is designed in C ++. C ++ design personal feeling up, although more complicated, but more flexibility. In particular data processing, the use of pointers played a significant role. Of course, this does not mean that C # can not do that, here we take a step by step and share with you:

  1. New Project - WPF Application --- ProjectName .... Create Project
  2. UI Design window design, where we realize a simple serial port configuration reception, so just design an edit box and a button you can:
     1 <Window x:Class="SearilPort.MainWindow"
     2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     4         Title="MainWindow" Height="350" Width="525">
     5     <Grid>
     6         <Button Name="myBtn" Content="Open" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="75" Click="Btn1_Click"/>
     7         <TextBox HorizontalAlignment="Left" VerticalAlignment="Top" Width="400" Height="260" Name="m_textBox1"/>
     8 
     9     </Grid>
    10 </Window>

     

  3. Because C # can be defined directly on the button type of content, so that we do not define two buttons like C ++, the other one is the Open is Closed, we only need to type a key name to operate:  myBtn.Content = " Closed " ;  or  myBtn.Content = " Open " ;  , thus greatly reducing our coding time.
  4. Serial turned implemented by key operation, so we need to add the button click event handler for  the Click = " Btn1_Click " />  , of course, before using the serial port serial port control class need to use the class that contains the namespace  System.IO.Ports ;  , the relevant port before using it must first class that uses the namespace  the using System.IO.Ports; 
  5. Code:
     1  private void Btn1_Click(object sender, RoutedEventArgs e)
     2         {
     3             try
     4             {
     5                 m_textBox1.Text = "reeivcing...\r\n";
     6                 myPort.BaudRate = 9600;
     7                 myPort.DataBits = 8;
     8                 myPort.PortName = "COM1";
     9                 myPort.Open();
    10                 if (myPort.IsOpen==true)
    11                 {
    12                     myBtn.Content = "Closed";
    13                 }
    14                 myPort.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
    15             }
    16             catch(Exception ex)
    17             {
    18                 myPort.Close();
    19                 myBtn.Content = "Open";
    20                 MessageBox.Show(ex.Message+"SearilPort is Closed.");
    21             }
    22         }
    View Code

     Tag  myPort.DataReceived + = new new SerialDataReceivedEventHandler (DataReceived);  refers to creating a custom receiver function, wherein  DataReceived  defined function is received from the name. Of course also possible to directly assign the received data based custom function name, i.e.:  myPort.DataReceived + = DataReceived;  Note that + = operators are representative of the class to create a custom function. For this event class, the government has also given a routine, here for your reference:

     1 using System;
     2 using System.IO.Ports;
     3 
     4 class PortDataReceived
     5 {
     6     public static void Main()
     7     {
     8         SerialPort mySerialPort = new SerialPort("COM1");
     9 
    10         mySerialPort.BaudRate = 9600;
    11         mySerialPort.Parity = Parity.None;
    12         mySerialPort.StopBits = StopBits.One;
    13         mySerialPort.DataBits = 8;
    14         mySerialPort.Handshake = Handshake.None;
    15         mySerialPort.RtsEnable = true;
    16 
    17         mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
    18 
    19         mySerialPort.Open();
    20 
    21         Console.WriteLine("Press any key to continue...");
    22         Console.WriteLine();
    23         Console.ReadKey();
    24         mySerialPort.Close();
    25     }
    26 
    27     private static void DataReceivedHandler(
    28                         object sender,
    29                         SerialDataReceivedEventArgs e)
    30     {
    31         SerialPort sp = (SerialPort)sender;
    32         string indata = sp.ReadExisting();
    33         Console.WriteLine("Data Received:");
    34         Console.Write(indata);
    35     }
    36 }
    SerialPort.DataReceived 事件

    Details Reference Link:  https://docs.microsoft.com/zh-cn/dotnet/api/system.io.ports.serialport.datareceived?view=netframework-4.8

  6. For custom receive event handler, we defined as the received eight bytes, 8 bytes printed in hex format into the edit box, the code:
     1 private void DataReceived(object sender,SerialDataReceivedEventArgs e)
     2         {
     3             try
     4             {
     5                 byte[] inbuf = new byte[8];
     6                 myPort.Read(inbuf, 0, inbuf.Length);
     7                 string str = System.Text.Encoding.Default.GetString(inbuf);
     8                 this.Dispatcher.Invoke(new Action(() =>
     9                     {
    10                         foreach (byte i in inbuf)
    11                         {
    12                             m_textBox1.Text += i.ToString("X2");
    13                         }
    14                         m_textBox1.Text += "\r\n";
    15                     }));
    16             }
    17             catch(Exception ex)
    18             {
    19                 MessageBox.Show(ex.Message);
    20             }
    21         }
    DataReceived

    Because we need to deal with the event thread to print the string edit box, so here we need to delegate this threading operation  the Dispatcher.Invoke ( new new the Action (() => {.....})); 

  7. Complete code:
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 using System.Windows;
     7 using System.Windows.Controls;
     8 using System.Windows.Data;
     9 using System.Windows.Documents;
    10 using System.Windows.Input;
    11 using System.Windows.Media;
    12 using System.Windows.Media.Imaging;
    13 using System.Windows.Navigation;
    14 using System.Windows.Shapes;
    15 using System.IO.Ports;
    16 
    17 namespace SearilPort
    18 {
    19     /// <summary>
    20     /// Interaction logic for MainWindow.xaml
    21     /// </summary>
    22     public partial class MainWindow : Window
    23     {
    24         SerialPort myPort = new SerialPort();
    25         public MainWindow()
    26         {
    27             InitializeComponent();
    28         }
    29 
    30         private void Btn1_Click(object sender, RoutedEventArgs e)
    31         {
    32             try
    33             {
    34                 m_textBox1.Text = "reeivcing...\r\n";
    35                 myPort.BaudRate = 9600;
    36                 myPort.DataBits = 8;
    37                 myPort.PortName = "COM1";
    38                 myPort.Open();
    39                 if (myPort.IsOpen==true)
    40                 {
    41                     myBtn.Content = "Closed";
    42                 }
    43                 myPort.DataReceived += DataReceived;
    44             }
    45             catch(Exception ex)
    46             {
    47                 myPort.Close();
    48                 myBtn.Content = "Open";
    49                 MessageBox.Show(ex.Message+"SearilPort is Closed.");
    50             }
    51         }
    52         private void DataReceived(object sender,SerialDataReceivedEventArgs e)
    53         {
    54             try
    55             {
    56                 byte[] inbuf = new byte[8];
    57                 myPort.Read(inbuf, 0, inbuf.Length);
    58                 string str = System.Text.Encoding.Default.GetString(inbuf);
    59                 this.Dispatcher.Invoke(new Action(() =>
    60                     {
    61                         foreach (byte i in inbuf)
    62                         {
    63                             m_textBox1.Text += i.ToString("X2");
    64                         }
    65                         m_textBox1.Text += "\r\n";
    66                     }));
    67             }
    68             catch(Exception ex)
    69             {
    70                 MessageBox.Show(ex.Message);
    71             }
    72         }
    73     }
    74 }
    View Code

    Outside device connection:

  8. Compile and run:

Since then, we have completed the decoded code sequence from the host via the serial transmission sent to NXP unidirectional basic operation by our application.

In the following sections, we will further improve the program, two-way traffic, while calling aes encryption calligraphy, we generate a serial number after the encryption.

 

End.

Thank you.

 

Guess you like

Origin www.cnblogs.com/lumao1122-Milolu/p/11994578.html