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




目录
相关文章
|
API C# UED
wpf的PixelLab.Wpf切换效果
wpf的PixelLab.Wpf切换效果
C# WPF定时器
最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来。我们都知道计算机技术发展日新月异,速度惊人的快,你我稍不留神,就会被慢慢淘汰!因此:每日不间断的学习是避免被淘汰的不二法宝。
1893 0
|
C# 编解码 Windows
WPF播放视频
原文:WPF播放视频 在现在的项目中需要使用到播放视频的功能,本来打算使用VLC来做的。后来发现WPF 4.0之后新增了MediaElement类,可以实现视频播放。 ...
2081 0
|
C#
制作WPF时钟之2
原文:制作WPF时钟之2 前段时间写了一篇“制作简单的WPF时钟”,今天再制作了一个更漂亮的WPF时钟,目前仅完成了设计部分,准备将它制作成一个无边框窗体式的时钟。
965 0
|
C# Windows
制作简单的WPF时钟
原文:制作简单的WPF时钟 在很早之前,我曾经写过一个GDI+的时钟,见“C#时钟控件 (C# Clock Control)” http://blog.csdn.net/johnsuna/archive/2006/02/13/597746.aspx及“使用C#编写LED样式时钟控件”(http://blog.csdn.net/johnsuna/archive/2006/02/14/598867.aspx),进入WPF时代了,如何用WPF绘制一个时钟呢? 先看效果: 上面显示的是时间值,下面是图形版的时钟。
948 0
|
C#
WPF获取窗口句柄
原文:WPF获取窗口句柄 通过WPF的互操作帮助类WindowInteropHelper,相关连接:https://msdn.microsoft.com/zh-cn/library/system.windows.
1515 0
|
C#
WPF 窗口
原文:WPF 窗口 在WPF中,经常需要对窗口进行设置,下面讲讲常用的几个设置。 窗口样式 1、无边框窗口 无边框透明窗体 设置 WindowStyle="None"--无边框,如果需要其它按钮,如缩小、放大、收缩、关闭按钮,可以自定义 AllowsTransparency="True"-...
747 0
|
C#
最新用WPF为触摸屏写了一个手写程序,双格输入的
原文:最新用WPF为触摸屏写了一个手写程序,双格输入的 双格输入可以提高手写速度,当前字写完以后可以自动识别提交,写下一个字。
1104 0
|
C# UED
WPF 使用DMSkin for WPF 快速搭建漂亮的WPF程序
原文:WPF 使用DMSkin for WPF 快速搭建漂亮的WPF程序 DMSkin-for-WPF是一个基于WPF的.Net WPF开源界面库,实现了无边框的WPF开发方案,内置部分控件模板. 你可以参照模板自行修改完善。
2058 0
|
C#
WPF 嵌入Winform GDI 、 开启AllowsTransparenc问题
原文:WPF 嵌入Winform GDI 、 开启AllowsTransparenc问题 此文章可以解决2至少2个问题: 1.开启AllowsTransparenc造成的GDI+组件不显示问题 2.WPF 组件无法覆盖嵌入WPF窗口的任何第三方GDI+组件上层   方案1:自制双层 原理:用一个新的窗口来承载GDI+组件,实现 父窗口 拖动、缩放、最小化、最大化 的联动 事件。
1247 0