Data and receiving data in WPF implementation

Original: WPF implementation and serial port to send data and receive data

< svg xmlns="http://www.w3.org/2000/svg" style="display: none;">

Send data and receive with serial port Data, here is a simple demo. This demo can realize pressing the hardware button, the light is on, and the light status data is sent. And several lights can be turned on at the same time, and the status data of the lights can be sent over. On the PC side, click the button to make the hardware light on.
Here are 4 lights, the data sent over: 0 means dark, 1 means bright. For example: 1010 means that the 1st and 3rd lights are on, and the 2nd and 4th lights are dim.
Send the past data: 0 means light 1 is on, 1 means light 1 is off, 2 means light 2 is on, 3 means light 2 is off, 4 means light 3 is on, 5 means light 3 is off, 6 is 4 No. light is on, 7 means No. 4 light is off.
Layout code:

<Grid>
        <TextBox HorizontalAlignment="Left" Height="23"  Margin="112,59,0,0" TextWrapping="Wrap" Name= "txtSend" VerticalAlignment="Top" Width="120 "/>
        <TextBox HorizontalAlignment="Left" Height="23"  Margin="112,113,0,0" TextWrapping="Wrap" Name="txtReceive" VerticalAlignment="Top" Width="120"< /span>/>
        <Button Content="Send" Name="btnSend"  HorizontalAlignment="Left" Margin="83,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend_Click"< /span>/>
        <Button Content="send" Name="btnSend1"  HorizontalAlignment="Left" Margin="143,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend1_Click"< /span>/>
        <Button Content="Send" Name="btnSend2"  HorizontalAlignment="Left" Margin="203,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend2_Click"< /span>/>
        <Button Content="send" Name="btnSend3"  HorizontalAlignment="Left" Margin="263,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend3_Click"< /span>/>


        <Label Name="one" Background ="Red" HorizontalAlignment="Left" Margin=" 84,190,0,0" VerticalAlignment="Top" Height="24" Width= "28"/>
        <Label Name="two" Background ="Red" HorizontalAlignment="Left" Margin=" 144,190,0,0" VerticalAlignment="Top" Height="24" Width= "28"/>
        <Label Name="three" Background ="Red" HorizontalAlignment="Left" Margin=" 204,190,0,0" VerticalAlignment="Top" Height="24" Width= "28"/>
        <Label Name="four" Background ="Red" HorizontalAlignment="Left" Margin=" 264,190,0,0" VerticalAlignment="Top" Height="24" Width= "28"/>



    Grid>

Background code:
First

private SerialPort Sp = new SerialPort();
        public delegate void HandleInterfaceUpdataDelegate(string text);
        private HandleInterfaceUpdataDelegate interfaceUpdataHandle;

        String[] arr = {"0", "0", "0", "0" };//used to store the status of the lights on the hardware span>

Secondly, add a parameter for changing the serial port in the Loaded event:

//change the parameter
            Sp.PortName = "COM3";
            Sp.BaudRate = 115200;
            Sp.Parity = Parity.None;
            Sp.StopBits = StopBits.One; 
Write monitoring and sending data events:
private void Serial()
        {
            Sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);
            if (!Sp.IsOpen)
            {
                Sp.Open();
            }
            //Send data in bytes
            SendBytesData(Sp);
        }

        //Send binary data
        private void SendBytesData(SerialPort Sp)
        {

            byte[] bytesSend = System.Text.Encoding.Default.GetBytes(txtSend.Text);
            Sp.Write(bytesSend, 0, bytesSend.Length);

        }



        public void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
           /* byte[] readBuffer = new byte[Sp.ReadBufferSize]; Sp.Read(readBuffer, 0, readBuffer.Length); //Dispatcher.Invoke(interfaceUpdataHandle, new string[] {Encoding.UTF8.GetString(readBuffer)}); Dispatcher.Invoke(interfaceUpdataHandle, new string[] {Encoding.ASCII.GetString(readBuffer) }); //Dispatcher.Invoke(interfaceUpdateHandle, new string[] {Encoding.ASCII .GetString(buf) });*/

            SerialPort serialPort = (SerialPort)(sender);
            System.Threading.Thread.Sleep(100);//Delay for a while to prevent the hardware sending rate from not keeping up Cached data clutter caused by cached data
            int n = serialPort.BytesToRead;//Write it down first to avoid certain reasons, man-made reasons, and operate several times Long time, inconsistent cache
            byte[] buf = new byte[ n];//Declare a temporary array to store the current serial port data
            //received_count += n;//Increase the received count 
            serialPort.Read(buf, 0, n);//Read buffered data 
            //Because you want to access ui resources, you need to use invoke to synchronize ui
            interfaceUpdataHandle = new HandleInterfaceUpdataDelegate(UpdateTextBox);//Instantiate the delegate object
            // Dispatcher.Invoke(interfaceUpdateHandle, new string[] {Encoding.ASCII.GetString(buf) });
            Dispatcher.Invoke(interfaceUpdataHandle, new string[] {Encoding.ASCII.GetString(buf) });

            //serialPort.Close();




        }

        private void UpdateTextBox(string text)
        {
            txtReceive.Text = text;

            String Receive = Convert.ToString(text);
            if (Receive != "")
            {
                // MessageBox.Show("receive", Receive);
                String Receive1 = Receive.Substring(0, 1);
                String Receive2 = Receive.Substring(1, 1);
                String Receive3 = Receive.Substring(2, 1);
                String Receive4 = Receive.Substring(3, 1);
                if (Receive1 == 1.ToString())
                {
                    one.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[0] = 1.ToString();
                }
                else
                {
                    one.Background = new SolidColorBrush(Colors.Red);
                    arr[0] = 0.ToString();
                }
                if (Receive2 == 1.ToString())
                {
                    two.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[1] = 1.ToString();
                }
                else
                {
                    two.Background = new SolidColorBrush(Colors.Red);
                    arr[1] = 0.ToString();
                }
                if (Receive3 == 1.ToString())
                {
                    three.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[2] = 1.ToString();
                }
                else
                {
                    three.Background = new SolidColorBrush(Colors.Red);
                    arr[2] = 0.ToString();
                }
                if (Receive4 == 1.ToString())
                {
                    four.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[3] = 1.ToString();
                }
                else
                {
                    four.Background = new SolidColorBrush(Colors.Red);
                    arr[3] = 0.ToString();
                }
                //String abc = Convert.ToString(arr);
                //MessageBox.Show("abc", abc);

                // MessageBox.Show("arr", arr);
            }
        }

Add the last button click event:

private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            if (arr[0] == 0.ToString())
            {
                txtSend.Text = "0";
                Serial();
            }
            else
            {
                txtSend.Text = "1";
                Serial();
            }
        }

        private void btnSend1_Click(object sender, RoutedEventArgs e)
        {
            if (arr[1] == 0.ToString())
            {
                txtSend.Text = "2";
                Serial();
            }
            else
            {
                txtSend.Text = "3";
                Serial();
            }
        }

        private void btnSend2_Click(object sender, RoutedEventArgs e)
        {
            if (arr[2] == 0.ToString())
            {
                txtSend.Text = "4";
                Serial();
            }
            else
            {
                txtSend.Text = "5";
                Serial();

            }
        }

        private void btnSend3_Click(object sender, RoutedEventArgs e)
        {
            if (arr[3] == 0.ToString())
            {
                txtSend.Text = "6";
                Serial();
            }
            else
            {
                txtSend.Text = "7";
                Serial();
            }
        }

If you want to monitor the data at the beginning of the program, add it to Loaded: Serial();
Complete background code:

< span class="hljs-keyword">public partial class MainWindow: Window
    {

        private SerialPort Sp = new SerialPort();
        public delegate void HandleInterfaceUpdataDelegate(string text);
        private HandleInterfaceUpdataDelegate interfaceUpdataHandle;

        String[] arr = {"0", "0", "0", "0" };//used to store the status of the lights on the hardware span>
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //Change parameters
            Sp.PortName = "COM3";
            Sp.BaudRate = 115200;
            Sp.Parity = Parity.None;
            Sp.StopBits = StopBits.One;

            Serial();
        }

        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            if (arr[0] == 0.ToString())
            {
                txtSend.Text = "0";
                Serial();
            }
            else
            {
                txtSend.Text = "1";
                Serial();
            }
        }

        private void btnSend1_Click(object sender, RoutedEventArgs e)
        {
            if (arr[1] == 0.ToString())
            {
                txtSend.Text = "2";
                Serial();
            }
            else
            {
                txtSend.Text = "3";
                Serial();
            }
        }

        private void btnSend2_Click(object sender, RoutedEventArgs e)
        {
            if (arr[2] == 0.ToString())
            {
                txtSend.Text = "4";
                Serial();
            }
            else
            {
                txtSend.Text = "5";
                Serial();

            }
        }

        private void btnSend3_Click(object sender, RoutedEventArgs e)
        {
            if (arr[3] == 0.ToString())
            {
                txtSend.Text = "6";
                Serial();
            }
            else
            {
                txtSend.Text = "7";
                Serial();
            }
        }

        private void Serial()
        {
            Sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);
            if (!Sp.IsOpen)
            {
                Sp.Open();
            }
            //Send data in bytes
            SendBytesData(Sp);
        }

        //Send binary data
        private void SendBytesData(SerialPort Sp)
        {

            byte[] bytesSend = System.Text.Encoding.Default.GetBytes(txtSend.Text);
            Sp.Write(bytesSend, 0, bytesSend.Length);

        }



        public void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
           /* byte[] readBuffer = new byte[Sp.ReadBufferSize]; Sp.Read(readBuffer, 0, readBuffer.Length); //Dispatcher.Invoke(interfaceUpdataHandle, new string[] {Encoding.UTF8.GetString(readBuffer)}); Dispatcher.Invoke(interfaceUpdataHandle, new string[] {Encoding.ASCII.GetString(readBuffer) }); //Dispatcher.Invoke(interfaceUpdateHandle, new string[] {Encoding.ASCII .GetString(buf) });*/

            SerialPort serialPort = (SerialPort)(sender);
            System.Threading.Thread.Sleep(100);//Delay for a while to prevent the hardware sending rate from not keeping up Cached data clutter caused by cached data
            int n = serialPort.BytesToRead;//Write it down first to avoid certain reasons, man-made reasons, and operate several times Long time, inconsistent cache
            byte[] buf = new byte[ n];//Declare a temporary array to store the current serial port data
            //received_count += n;//Increase the received count 
            serialPort.Read(buf, 0, n);//Read buffered data 
            //Because you want to access ui resources, you need to use invoke to synchronize ui
            interfaceUpdataHandle = new HandleInterfaceUpdataDelegate(UpdateTextBox);//Instantiate the delegate object
            // Dispatcher.Invoke(interfaceUpdateHandle, new string[] {Encoding.ASCII.GetString(buf) });
            Dispatcher.Invoke(interfaceUpdataHandle, new string[] {Encoding.ASCII.GetString(buf) });

            //serialPort.Close();




        }

        private void UpdateTextBox(string text)
        {
            txtReceive.Text = text;

            String Receive = Convert.ToString(text);
            if (Receive != "")
            {
                // MessageBox.Show("receive", Receive);
                String Receive1 = Receive.Substring(0, 1);
                String Receive2 = Receive.Substring(1, 1);
                String Receive3 = Receive.Substring(2, 1);
                String Receive4 = Receive.Substring(3, 1);
                if (Receive1 == 1.ToString())
                {
                    one.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[0] = 1.ToString();
                }
                else
                {
                    one.Background = new SolidColorBrush(Colors.Red);
                    arr[0] = 0.ToString();
                }
                if (Receive2 == 1.ToString())
                {
                    two.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[1] = 1.ToString();
                }
                else
                {
                    two.Background = new SolidColorBrush(Colors.Red);
                    arr[1] = 0.ToString();
                }
                if (Receive3 == 1.ToString())
                {
                    three.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[2] = 1.ToString();
                }
                else
                {
                    three.Background = new SolidColorBrush(Colors.Red);
                    arr[2] = 0.ToString();
                }
                if (Receive4 == 1.ToString())
                {
                    four.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[3] = 1.ToString();
                }
                else
                {
                    four.Background = new SolidColorBrush(Colors.Red);
                    arr[3] = 0.ToString();
                }
                //String abc = Convert.ToString(arr);
                //MessageBox.Show("abc", abc);

                // MessageBox.Show("arr", arr);
            }
        }


    }

In this way, the btn and hardware buttons can control the lights to turn on and off at the same time. If reprinted, please indicate the reprinting place.

To send and receive data with the serial port, here is a simple demo. This demo can realize pressing the hardware button, the light is on, and the sending The light status data is here. And several lights can be turned on at the same time, and the status data of the lights can be sent over. On the PC side, click the button to make the hardware light on.
Here are 4 lights, the data sent over: 0 means dark, 1 means bright. For example: 1010 means that the 1st and 3rd lights are on, and the 2nd and 4th lights are dim.
Send the past data: 0 means light 1 is on, 1 means light 1 is off, 2 means light 2 is on, 3 means light 2 is off, 4 means light 3 is on, 5 means light 3 is off, 6 is 4 No. light is on, 7 means No. 4 light is off.
Layout code:

<Grid>
        <TextBox HorizontalAlignment="Left" Height="23"  Margin="112,59,0,0" TextWrapping="Wrap" Name= "txtSend" VerticalAlignment="Top" Width="120 "/>
        <TextBox HorizontalAlignment="Left" Height="23"  Margin="112,113,0,0" TextWrapping="Wrap" Name="txtReceive" VerticalAlignment="Top" Width="120"< /span>/>
        <Button Content="Send" Name="btnSend"  HorizontalAlignment="Left" Margin="83,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend_Click"< /span>/>
        <Button Content="send" Name="btnSend1"  HorizontalAlignment="Left" Margin="143,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend1_Click"< /span>/>
        <Button Content="Send" Name="btnSend2"  HorizontalAlignment="Left" Margin="203,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend2_Click"< /span>/>
        <Button Content="send" Name="btnSend3"  HorizontalAlignment="Left" Margin="263,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend3_Click"< /span>/>


        <Label Name="one" Background ="Red" HorizontalAlignment="Left" Margin=" 84,190,0,0" VerticalAlignment="Top" Height="24" Width= "28"/>
        <Label Name="two" Background ="Red" HorizontalAlignment="Left" Margin=" 144,190,0,0" VerticalAlignment="Top" Height="24" Width= "28"/>
        <Label Name="three" Background ="Red" HorizontalAlignment="Left" Margin=" 204,190,0,0" VerticalAlignment="Top" Height="24" Width= "28"/>
        <Label Name="four" Background ="Red" HorizontalAlignment="Left" Margin=" 264,190,0,0" VerticalAlignment="Top" Height="24" Width= "28"/>



    Grid>

Background code:
First

private SerialPort Sp = new SerialPort();
        public delegate void HandleInterfaceUpdataDelegate(string text);
        private HandleInterfaceUpdataDelegate interfaceUpdataHandle;

        String[] arr = {"0", "0", "0", "0" };//used to store the status of the lights on the hardware span>

Secondly, add a parameter for changing the serial port in the Loaded event:

//change the parameter
            Sp.PortName = "COM3";
            Sp.BaudRate = 115200;
            Sp.Parity = Parity.None;
            Sp.StopBits = StopBits.One; 
Write monitoring and sending data events:
private void Serial()
        {
            Sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);
            if (!Sp.IsOpen)
            {
                Sp.Open();
            }
            //用字节的形式发送数据
            SendBytesData(Sp);
        }

        //发送二进制数据
        private void SendBytesData(SerialPort Sp)
        {

            byte[] bytesSend = System.Text.Encoding.Default.GetBytes(txtSend.Text);
            Sp.Write(bytesSend, 0, bytesSend.Length);

        }



        public void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
           /* byte[] readBuffer = new byte[Sp.ReadBufferSize]; Sp.Read(readBuffer, 0, readBuffer.Length); //Dispatcher.Invoke(interfaceUpdataHandle, new string[]{ Encoding.UTF8.GetString(readBuffer)}); Dispatcher.Invoke(interfaceUpdataHandle, new string[] { Encoding.ASCII.GetString(readBuffer) }); //Dispatcher.Invoke(interfaceUpdateHandle, new string[] { Encoding.ASCII.GetString(buf) });*/

            SerialPort serialPort = (SerialPort)(sender);
            System.Threading.Thread.Sleep(100);//延缓一会,用于防止硬件发送速率跟不上缓存数据导致的缓存数据杂乱
            int n = serialPort.BytesToRead;//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致 
            byte[] buf = new byte[n];//声明一个临时数组存储当前来的串口数据 
            //received_count += n;//增加接收计数 
            serialPort.Read(buf, 0, n);//读取缓冲数据 
            //因为要访问ui资源,所以需要使用invoke方式同步ui
            interfaceUpdataHandle = new HandleInterfaceUpdataDelegate(UpdateTextBox);//实例化委托对象
            // Dispatcher.Invoke(interfaceUpdateHandle, new string[] { Encoding.ASCII.GetString(buf) });
            Dispatcher.Invoke(interfaceUpdataHandle, new string[] { Encoding.ASCII.GetString(buf) });

            //serialPort.Close();




        }

        private void UpdateTextBox(string text)
        {
            txtReceive.Text = text;

            String Receive = Convert.ToString(text);
            if (Receive != "")
            {
                // MessageBox.Show("receive", Receive);
                String Receive1 = Receive.Substring(0, 1);
                String Receive2 = Receive.Substring(1, 1);
                String Receive3 = Receive.Substring(2, 1);
                String Receive4 = Receive.Substring(3, 1);
                if (Receive1 == 1.ToString())
                {
                    one.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[0] = 1.ToString();
                }
                else
                {
                    one.Background = new SolidColorBrush(Colors.Red);
                    arr[0] = 0.ToString();
                }
                if (Receive2 == 1.ToString())
                {
                    two.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[1] = 1.ToString();
                }
                else
                {
                    two.Background = new SolidColorBrush(Colors.Red);
                    arr[1] = 0.ToString();
                }
                if (Receive3 == 1.ToString())
                {
                    three.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[2] = 1.ToString();
                }
                else
                {
                    three.Background = new SolidColorBrush(Colors.Red);
                    arr[2] = 0.ToString();
                }
                if (Receive4 == 1.ToString())
                {
                    four.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[3] = 1.ToString();
                }
                else
                {
                    four.Background = new SolidColorBrush(Colors.Red);
                    arr[3] = 0.ToString();
                }
                //String abc = Convert.ToString(arr);
                //MessageBox.Show("abc", abc);

                // MessageBox.Show("arr", arr);
            }
        }

最后button点击事件添加:

private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            if (arr[0] == 0.ToString())
            {
                txtSend.Text = "0";               
                Serial();
            }
            else
            {
                txtSend.Text = "1";
                Serial();
            }
        }

        private void btnSend1_Click(object sender, RoutedEventArgs e)
        {
            if (arr[1] == 0.ToString())
            {
                txtSend.Text = "2";
                Serial();
            }
            else
            {
                txtSend.Text = "3";
                Serial();
            }
        }

        private void btnSend2_Click(object sender, RoutedEventArgs e)
        {
            if (arr[2] == 0.ToString())
            {
                txtSend.Text = "4";
                Serial();
            }
            else
            {
                txtSend.Text = "5";
                Serial();

            }
        }

        private void btnSend3_Click(object sender, RoutedEventArgs e)
        {
            if (arr[3] == 0.ToString())
            {
                txtSend.Text = "6";
                Serial();
            }
            else
            {
                txtSend.Text = "7";
                Serial();
            }
        }

要想在程序开始时就可以监听数据,在其Loaded里面添加上: Serial();
完整后台代码:

public partial class MainWindow : Window
    {

        private SerialPort Sp = new SerialPort();
        public delegate void HandleInterfaceUpdataDelegate(string text);
        private HandleInterfaceUpdataDelegate interfaceUpdataHandle;

        String[] arr = { "0", "0", "0", "0" };//用于存储硬件上面灯状态
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //更改参数
            Sp.PortName = "COM3";
            Sp.BaudRate = 115200;
            Sp.Parity = Parity.None;
            Sp.StopBits = StopBits.One;

            Serial();
        }

        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            if (arr[0] == 0.ToString())
            {
                txtSend.Text = "0";               
                Serial();
            }
            else
            {
                txtSend.Text = "1";
                Serial();
            }
        }

        private void btnSend1_Click(object sender, RoutedEventArgs e)
        {
            if (arr[1] == 0.ToString())
            {
                txtSend.Text = "2";
                Serial();
            }
            else
            {
                txtSend.Text = "3";
                Serial();
            }
        }

        private void btnSend2_Click(object sender, RoutedEventArgs e)
        {
            if (arr[2] == 0.ToString())
            {
                txtSend.Text = "4";
                Serial();
            }
            else
            {
                txtSend.Text = "5";
                Serial();

            }
        }

        private void btnSend3_Click(object sender, RoutedEventArgs e)
        {
            if (arr[3] == 0.ToString())
            {
                txtSend.Text = "6";
                Serial();
            }
            else
            {
                txtSend.Text = "7";
                Serial();
            }
        }

        private void Serial()
        {
            Sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);
            if (!Sp.IsOpen)
            {
                Sp.Open();
            }
            //用字节的形式发送数据
            SendBytesData(Sp);
        }

        //发送二进制数据
        private void SendBytesData(SerialPort Sp)
        {

            byte[] bytesSend = System.Text.Encoding.Default.GetBytes(txtSend.Text);
            Sp.Write(bytesSend, 0, bytesSend.Length);

        }



        public void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
           /* byte[] readBuffer = new byte[Sp.ReadBufferSize]; Sp.Read(readBuffer, 0, readBuffer.Length); //Dispatcher.Invoke(interfaceUpdataHandle, new string[]{ Encoding.UTF8.GetString(readBuffer)}); Dispatcher.Invoke(interfaceUpdataHandle, new string[] { Encoding.ASCII.GetString(readBuffer) }); //Dispatcher.Invoke(interfaceUpdateHandle, new string[] { Encoding.ASCII.GetString(buf) });*/

            SerialPort serialPort = (SerialPort)(sender);
            System.Threading.Thread.Sleep(100);//延缓一会,用于防止硬件发送速率跟不上缓存数据导致的缓存数据杂乱
            int n = serialPort.BytesToRead;//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致 
            byte[] buf = new byte[n];//声明一个临时数组存储当前来的串口数据 
            //received_count += n;//增加接收计数 
            serialPort.Read(buf, 0, n);//读取缓冲数据 
            //因为要访问ui资源,所以需要使用invoke方式同步ui
            interfaceUpdataHandle = new HandleInterfaceUpdataDelegate(UpdateTextBox);//实例化委托对象
            // Dispatcher.Invoke(interfaceUpdateHandle, new string[] { Encoding.ASCII.GetString(buf) });
            Dispatcher.Invoke(interfaceUpdataHandle, new string[] { Encoding.ASCII.GetString(buf) });

            //serialPort.Close();




        }

        private void UpdateTextBox(string text)
        {
            txtReceive.Text = text;

            String Receive = Convert.ToString(text);
            if (Receive != "")
            {
                // MessageBox.Show("receive", Receive);
                String Receive1 = Receive.Substring(0, 1);
                String Receive2 = Receive.Substring(1, 1);
                String Receive3 = Receive.Substring(2, 1);
                String Receive4 = Receive.Substring(3, 1);
                if (Receive1 == 1.ToString())
                {
                    one.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[0] = 1.ToString();
                }
                else
                {
                    one.Background = new SolidColorBrush(Colors.Red);
                    arr[0] = 0.ToString();
                }
                if (Receive2 == 1.ToString())
                {
                    two.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[1] = 1.ToString();
                }
                else
                {
                    two.Background = new SolidColorBrush(Colors.Red);
                    arr[1] = 0.ToString();
                }
                if (Receive3 == 1.ToString())
                {
                    three.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[2] = 1.ToString();
                }
                else
                {
                    three.Background = new SolidColorBrush(Colors.Red);
                    arr[2] = 0.ToString();
                }
                if (Receive4 == 1.ToString())
                {
                    four.Background = new SolidColorBrush(Colors.MediumAquamarine);
                    arr[3] = 1.ToString();
                }
                else
                {
                    four.Background = new SolidColorBrush(Colors.Red);
                    arr[3] = 0.ToString();
                }
                //String abc = Convert.ToString(arr);
                //MessageBox.Show("abc", abc);

                // MessageBox.Show("arr", arr);
            }
        }


    }

这样可以实现btn和硬件本身按钮同时控制灯亮灯灭。若转载请注明转载处。

Leave a Comment

Your email address will not be published.