原文:WPF内实现与串口发送数据和接收数据

与串口发送数据和接收数据,在此作一个简单的Demo.此Demo可以实现按下硬件按钮,灯亮,发送灯状态数据过来。并且可以实现几个灯同时亮,发送灯的状态数据过来。PC端实现点击按钮让硬件灯亮。

此处为4个灯,发送过来的数据:0代表暗,1代表亮。列如:1010代表1号灯和3号灯亮,2号和4号灯暗。

发送过去的数据:0代表1号灯亮,1代表1号灯灭、2代表2号灯亮,3代表2号灯灭、4代表3号灯亮,5代表3号灯灭、6代表4号灯亮,7代表4号灯灭。

布局代码:

<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)
{
/* 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和硬件本身按钮同时控制灯亮灯灭。

若转载请注明转载处。

WPF内实现与串口发送数据和接收数据的更多相关文章

  1. Java基础知识强化之网络编程笔记06:TCP之TCP协议发送数据 和 接收数据

    1. TCP协议发送数据 和 接收数据 TCP协议接收数据:• 创建接收端的Socket对象• 监听客户端连接.返回一个对应的Socket对象• 获取输入流,读取数据显示在控制台• 释放资源 TCP协 ...

  2. Java基础知识强化之网络编程笔记03:UDP之UDP协议发送数据 和 接收数据

    1. UDP协议发送数据 和 接收数据 UDP协议发送数据: • 创建发送端的Socket对象 • 创建数据,并把数据打包 • 调用Socket对象的发送方法,发送数据包 • 释放资源  UDP协议接 ...

  3. STM32移植RT-Thread后的串口在调试助手上出现:(mq != RT_NULL) assert failed at rt_mq_recv:2085和串口只发送数据不能接收数据问题

    STM32移植RT-Thread后的串口在调试助手上出现:(mq != RT_NULL) assert failed at rt_mq_recv:2085的问题讨论:http://www.rt-thr ...

  4. 如何使用python内置的request发送JSON格式的数据

    使用步骤如下: 一.如果想发送json格式的数据,需要使用request模块中的Request类来创建对象,作为urlopen函数的参数 二.header中添加content-type为applica ...

  5. Java Socket 服务端发送数据 客户端接收数据

    服务端: package com.thinkgem.wlw.modules.api.test.socket; /** * @Author: zhouhe * @Date: 2019/4/8 9:30 ...

  6. 说说ajax上传数据和接收数据

    我是一个脑袋不太灵光的人,所以遇到问题,厚着脸皮去请教大神的时候,害怕被大神鄙视,但是还是被鄙视了.我说自己不要点脸面,那是不可能的,但是,为了能让自己的技术生涯能走的更长远一些,受点白眼,受点嘲笑也 ...

  7. MVC系列学习(五)-传递数据 与 接收数据

    1.控制器向视图传递数据 a.使用ViewData b.使用ViewBag c.使用Model 方式二: d.使用TempData 2.为什么在控制器中设置了一些属性,在视图中可以接受 3.Actio ...

  8. ESP8266服务器模式 发送数据和接收数据 模板1

    功能如下: 1.将客户端发来的数据转发到串口:2.串口数据转发给所有客户端3.可连接4个客户端4.可设置静态IP地址5.指示灯闪烁表示无客户端连接,灯亮代表有客户端连接 /** 功能: 1.将客户端发 ...

  9. ASP.NET 最全的POST提交数据和接收数据 —— (1) 用url传参方式

    //1.对象提交,字典方式 //接口方:public ActionResult GetArry(Car model) public void PostResponse() { HttpWebReque ...

随机推荐

  1. SIMPLE QUERY几个原则

    1.减少查询对象的数据页(db block)数量. 尽量避免使用 * 用准确的列明减少不必要的一些资源浪费.   2.查看是否使用了index. 索引是SQL性能调优的重要手段,下面几个是有索引不能使 ...

  2. YUV与RGB格式转换

    YUV格式具有亮度信息和色彩信息分离的特点,但大多数图像处理操作都是基于RGB格式. 因此当要对图像进行后期处理显示时,需要把YUV格式转换成RGB格式. RGB与YUV的变换公式如下: YUV(25 ...

  3. Spring Tool Suite(STS)加速

    Java开发首选技术是Spring,使用Spring技术首选的开发工具是STS,STS有许多加速spring开发的提示和快捷方式,并将spring的最新技术通过STS快速简单的传递给用户. 但是STS ...

  4. C++实践參考——二进制文件浏览器

    [项目-二进制文件浏览器] (1)做一个相似BinaryViewer的查看二进制文件的程序.输入文件名称后,能够以16进制和ASCII对比的方式列出该文件的内容.能够參考下图: 提示:循环中,一次读入 ...

  5. Android中的消息机制:Handler消息传递机制 分类: H1_ANDROID 2013-10-27 22:54 1755人阅读 评论(0) 收藏

    参考<疯狂android讲义>第2版3.5 P214 一.背景 出于性能优化考虑,Android的UI操作并不是线程安全的,这意味着如果有多个线程并发操作UI组件,可能导致线程安全问题.为 ...

  6. 【9207&&b701】统计数字(NOIP2007)

    问题描述 某次科研调查时得到了n个自然数,每个数均不超过1500000000 (1.5*109).已知不相同的数不超过10000个,现在需要统计这些自然数各自出现的次数,并按照自然数从小到大的顺序输出 ...

  7. 【转】优先队列priority_queue 用法详解

    http://www.cnblogs.com/void/archive/2012/02/01/2335224.html 优先队列是队列的一种,不过它可以按照自定义的一种方式(数据的优先级)来对队列中的 ...

  8. [Ramda] Refactor to Point Free Functions with Ramda using compose and converge

    In this lesson we'll take some existing code and refactor it using some functions from the Ramda lib ...

  9. C++ 与 Java 语言对比

    1 . Java 是完全封装的,而 C++ 的函数是可以定义在 Class 的外部的.从这里就可以看出 C++ 的 OO 思想不够彻底,至少在封装这一点上. 2. C++ 中有拷贝构造函数,可以把一个 ...

  10. WPF实现射线效果动画

    原文:WPF实现射线效果动画 最近的一个项目中有个需求是:从一个点向其它多个点发出射线,要求这些射线同时发出,同时到达. 我就想到了用WPF的动画来实现.WPF中有Line类用于绘制直线,但这个类中好 ...