WPF 之 串口使用

简介: WPF之串口使用

20210112130130979.jpg


布局代码:


<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"/>
  <Button Content="发送" Name="btnSend" HorizontalAlignment="Left" Margin="83,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend_Click"/>
  <Button Content="发送" Name="btnSend1" HorizontalAlignment="Left" Margin="143,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend1_Click"/>
  <Button Content="发送" Name="btnSend2" HorizontalAlignment="Left" Margin="203,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend2_Click"/>
  <Button Content="发送" Name="btnSend3" HorizontalAlignment="Left" Margin="263,271,0,0" VerticalAlignment="Top" Width="35" Click="btnSend3_Click"/>
  <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>


后台代码:


private SerialPort Sp = new SerialPort();
public delegate void HandleInterfaceUpdataDelegate(string text);
private HandleInterfaceUpdataDelegate interfaceUpdataHandle;
String[] arr = { "0", "0", "0", "0" };//用于存储硬件上面灯状态


Loaded事件添加用于更改串口参数:


 //更改参数
Sp.PortName = "COM3";
Sp.BaudRate = 115200;
Sp.Parity = Parity.None;
Sp.StopBits = StopBits.One;


编写监听和发送数据事件:


编写监听和发送数据事件:
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)
{
    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) });
}
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();
       }
   }
}


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();
     }
 }


完整后台代码:


 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);
            }
        }
    }




目录
相关文章
|
数据可视化 数据挖掘 数据处理
【100天精通Python】Day61:Python 数据分析_Pandas可视化功能:绘制饼图,箱线图,散点图,散点图矩阵,热力图,面积图等(示例+代码)
【100天精通Python】Day61:Python 数据分析_Pandas可视化功能:绘制饼图,箱线图,散点图,散点图矩阵,热力图,面积图等(示例+代码)
1684 0
|
前端开发 JavaScript 开发者
Vite前端构建工具详解
Vite 是一款新兴的前端构建工具,它的出现带来了前端开发体验的革命性变化。本文将介绍 Vite 的基本概念和核心特性,并通过代码实例来演示其强大功能。
416 0
|
监控 API 计算机视觉
OpenCV这么简单为啥不学——1.13图片冷白皮(美白)处理
OpenCV这么简单为啥不学——1.13图片冷白皮(美白)处理
155 0
|
计算机视觉 Python
Opencv学习笔记(四):如何通过cv2或者通过matplotlib来将多张图拼接成一张图输出
这篇文章介绍了如何使用OpenCV和matplotlib将多张图像拼接成一张图进行输出,并比较了两者的效果和使用注意事项。
355 0
Opencv学习笔记(四):如何通过cv2或者通过matplotlib来将多张图拼接成一张图输出
|
机器学习/深度学习 开发者 Python
Python中进行特征重要性分析的9个常用方法
在Python机器学习中,特征重要性分析是理解模型预测关键因素的重要步骤。本文介绍了九种常用方法:排列重要性、内置特征重要性(如`coef_`)、逐项删除法、相关性分析、递归特征消除(RFE)、LASSO回归、SHAP值、部分依赖图和互信息。这些方法适用于不同类型模型和场景,帮助识别关键特征,指导特征选择与模型解释。通过综合应用这些技术,可以提高模型的透明度和预测性能。
1276 0
|
XML 数据格式
XPath解析(一)
XPath解析(一)
170 10
|
JavaScript IDE 测试技术
Rtsp转Flv在浏览器中播放
【2月更文挑战第5天】本文简单介绍如何间接实现在浏览器中播放rtsp的流,涉及技术点和工具较多,本文仅做功能实现思路的梳理和简单的代码实践,后续整理更深入的实现原理。
1299 1
|
存储 传感器 Java
格雷码(Gray Code)
格雷码(Gray Code)是一种二进制编码方式,它使用两种不同状态的信号(通常为 0 和 1)来表示二进制位。与普通的二进制编码不同,格雷码相邻的两个二进制位之间只相差一个比特。例如,对于 4 位二进制数,格雷码可以是 0000、0001、0011、0100、0101、0110、1000、1001、1010、1011、1100、1101、1110 和 1111。
3185 1
|
安全 数据安全/隐私保护 Windows
Windows 用户管理
Windows 用户管理
407 0
|
安全 Android开发 iOS开发
iOS隐私安全:用户协议及隐私政策弹框(包含超链接属性、demo支持中英文切换)
iOS隐私安全:用户协议及隐私政策弹框(包含超链接属性、demo支持中英文切换)
1768 1
iOS隐私安全:用户协议及隐私政策弹框(包含超链接属性、demo支持中英文切换)