c#上位机串口通信助手源代码详解Word文档格式.docx

上传人:b****1 文档编号:394344 上传时间:2023-04-28 格式:DOCX 页数:28 大小:56.04KB
下载 相关 举报
c#上位机串口通信助手源代码详解Word文档格式.docx_第1页
第1页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第2页
第2页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第3页
第3页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第4页
第4页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第5页
第5页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第6页
第6页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第7页
第7页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第8页
第8页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第9页
第9页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第10页
第10页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第11页
第11页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第12页
第12页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第13页
第13页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第14页
第14页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第15页
第15页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第16页
第16页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第17页
第17页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第18页
第18页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第19页
第19页 / 共28页
c#上位机串口通信助手源代码详解Word文档格式.docx_第20页
第20页 / 共28页
亲,该文档总共28页,到这儿已超出免费预览范围,如果喜欢就下载吧!
下载资源
资源描述

c#上位机串口通信助手源代码详解Word文档格式.docx

《c#上位机串口通信助手源代码详解Word文档格式.docx》由会员分享,可在线阅读,更多相关《c#上位机串口通信助手源代码详解Word文档格式.docx(28页珍藏版)》请在冰点文库上搜索。

c#上位机串口通信助手源代码详解Word文档格式.docx

接收区清空内容按钮:

btnClearReceived保存数据按钮:

btnSaveFile

接收数据框:

tbReceivedData发送数据框:

tbSendData

自动发送:

cbAutomaticSend间隔时间:

tbSpaceTime

按16进制发送:

cb16Send发送区清空内容按钮:

btnClearSend

读入文件按钮:

btnReadFile发送按钮:

btnSend

2创建一个方法类

按Ctrl+shift+A快捷键创建一个类,名字叫Methods,代码为:

 

usingSystem;

usingSystem.Collections;

usingSystem.Collections.Generic;

usingSystem.IO.Ports;

usingSystem.Linq;

usingSystem.Text;

usingSystem.Threading.Tasks;

namespace串口助手sdd

{

classMethods

{

//获取有效的COM口

publicstaticstring[]ActivePorts()

ArrayListactivePorts=newArrayList();

foreach(stringpnameinSerialPort.GetPortNames())

activePorts.Add(Convert.ToInt32(pname.Substring(3)));

}

activePorts.Sort();

string[]mystr=newstring[activePorts.Count];

inti=0;

foreach(intnuminactivePorts)

mystr[i++]="

COM"

+num.ToString();

returnmystr;

//16进制字符串转换为byte字符数组

publicstaticByte[]_16strToHex(stringstrValues)

string[]hexValuesSplit=strValues.Split('

'

);

Byte[]hexValues=newByte[hexValuesSplit.Length];

Console.WriteLine(hexValuesSplit.Length);

for(inti=0;

i<

hexValuesSplit.Length;

i++)

hexValues[i]=Convert.ToByte(hexValuesSplit[i],16);

returnhexValues;

//byte数组以16进制形式转字符串

publicstaticstringByteTo16Str(byte[]bytes)

stringrecData=null;

//创建接收数据的字符串

foreach(byteoutByteinbytes)//将字节数组以16进制形式遍历到一个字符串内

recData+=outByte.ToString("

X2"

)+"

"

;

returnrecData;

//16进制字符串转换字符串

publicstaticstring_16strToStr(string_16str)

stringoutStr=null;

byte[]streamByte=_16strToHex(_16str);

outStr=Encoding.Default.GetString(streamByte);

returnoutStr;

}

2Form1.cs的代码为:

usingSystem.ComponentModel;

usingSystem.Data;

usingSystem.Drawing;

usingSystem.Text.RegularExpressions;

usingSystem.Windows.Forms;

usingSystem.IO;

publicpartialclassForm1:

Form

//声明变量

SerialPortsp=newSerialPort();

boolisSetProperty=false;

//串口属性设置标志位

privateenumPortState//声明接口显示状态,枚举型

打开,

关闭

stringpath=AppDomain.CurrentDomain.BaseDirectory+"

confing.ini"

//声明配置文件路径

stringtbSendDataStr="

"

//发送窗口字符串存储

stringtbSendData16="

//发送窗口16进制存储

List<

byte>

receivedDatas=newList<

();

//接收数据泛型数组

//接收串口数据

privatevoidsp_DataReceived(objectsender,SerialDataReceivedEventArgse)

byte[]ReceivedData=newbyte[sp.BytesToRead];

//创建接收字节数组

sp.Read(ReceivedData,0,ReceivedData.Length);

//读取所接收到的数据

receivedDatas.AddRange(ReceivedData);

tbReceivedCount.Text=(Convert.ToInt32(tbReceivedCount.Text)+ReceivedData.Length).ToString();

if(cb16Display.Checked)

tbReceivedData.Text=Methods.ByteTo16Str(receivedDatas.ToArray());

else

tbReceivedData.Text=Encoding.Default.GetString(receivedDatas.ToArray());

sp.DiscardInBuffer();

//丢弃接收缓冲区数据

//发送串口数据

privatevoidDataSend()

try

if(cb16Send.Checked)

byte[]hexBytes=Methods._16strToHex(tbSendData16);

sp.Write(hexBytes,0,hexBytes.Length);

tbSendCount.Text=(Convert.ToInt32(tbSendCount.Text)+hexBytes.Length).ToString();

sp.WriteLine(tbSendDataStr);

tbSendCount.Text=(Convert.ToInt32(tbSendCount.Text)+tbSendDataStr.Length).ToString();

catch(Exceptionex)

MessageBox.Show(ex.Message.ToString());

return;

//设置串口属性

privatevoidSetPortProperty()

sp.PortName=cbxCOMPort.Text.Trim();

//设置串口名

sp.BaudRate=Convert.ToInt32(cbxBaudRate.Text.Trim());

//设置波特率

switch(cbxStopBits.Text.Trim())//设置停止位

case"

1"

:

sp.StopBits=StopBits.One;

break;

1.5"

sp.StopBits=StopBits.OnePointFive;

2"

sp.StopBits=StopBits.Two;

default:

sp.StopBits=StopBits.None;

sp.DataBits=Convert.ToInt32(cbxDataBits.Text.Trim());

//设置数据位

switch(cbxParity.Text.Trim())//设置奇偶校验位

无"

sp.Parity=Parity.None;

奇校验"

sp.Parity=Parity.Odd;

偶校验"

sp.Parity=Parity.Even;

sp.ReadTimeout=5000;

//设置超时时间为5s

Control.CheckForIllegalCrossThreadCalls=false;

//这个类中我们不检查跨线程的调用是否合法(因为.net2.0以后加强了安全机制,,不允许在winform中直接跨线程访问控件的属性)

//定义DataReceived事件的委托,当串口收到数据后出发事件

sp.DataReceived+=newSerialDataReceivedEventHandler(sp_DataReceived);

//设置端口显示状态

privatevoidDisplayPortState(PortStateportState)

toolStripStatusLabel1.Text=cbxCOMPort.Text+"

端口处于"

+portState+"

状态"

+cbxBaudRate.Text+"

+cbxDataBits.Text+"

+cbxStopBits.Text+"

+cbxParity.Text;

//重新打开串口

privatevoidAgainOpenPort()

if(sp.IsOpen)

sp.Close();

SetPortProperty();

isSetProperty=true;

sp.Open();

catch(Exception)

isSetProperty=false;

btnOpenCom.Text="

打开串口"

DisplayPortState(PortState.关闭);

MessageBox.Show("

串口无效或已被占用!

"

错误提示"

DisplayPortState(PortState.打开);

publicForm1()

InitializeComponent();

//软件启动时加载事件

privatevoidForm1_Load(objectsender,EventArgse)

#region加载配置文件

Hashtableht=newHashtable();

if(File.Exists(path))

stringmyline="

string[]str=newstring[2];

using(StreamReadersr=newStreamReader(path))

myline=sr.ReadLine();

while(myline!

=null)

str=myline.Split('

='

ht.Add(str[0],str[1]);

catch(Exceptionex)

#endregion

#region设置窗口为固定大小且不可最大化

this.MaximumSize=this.Size;

this.MinimumSize=this.Size;

this.MaximizeBox=false;

#region列出常用的波特率

cbxBaudRate.Items.Add("

1200"

2400"

4800"

9600"

19200"

38400"

43000"

56000"

57600"

115200"

if(ht.ContainsKey("

cbxBaudRate"

))

cbxBaudRate.SelectedIndex=cbxBaudRate.Items.IndexOf(ht["

].ToString());

cbxBaudRate.SelectedIndex=3;

cbxBaudRate.DropDownStyle=ComboBoxStyle.DropDownList;

#region列出停止位

cbxStopBits.Items.Add("

cbxStopBits"

cbxStopBits.SelectedIndex=cbxStopBits.Items.IndexOf(ht["

cbxStopBits.SelectedIndex=0;

cbxStopBits.DropDownStyle=ComboBoxStyle.DropDownList;

#region列出数据位

cbxDataBits.Items.Add("

8"

7"

6"

5"

cbxDataBits"

cbxDataBits.SelectedIndex=cbxDataBits.Items.IndexOf(ht["

cbxDataBits.SelectedIndex=0;

cbxDataBits.DropDownStyle=ComboBoxStyle.DropDownList;

#region列出奇偶校验位

cbxParity.Items.Add("

cbxParity"

cbxParity.SelectedIndex=cbxParity.Items.IndexOf(ht["

cbxParity.SelectedIndex=0;

cbxParity.DropDownStyle=ComboBoxStyle.DropDownList;

#regionCOM口重新加载

cbxCOMPort.Items.Clear();

//清除当前串口号中的所有串口名称

cbxCOMPort.Items.AddRange(Methods.ActivePorts());

cbxCOMPort"

)&

&

cbxCOMPort.Items.Contains(ht["

].ToString()))

cbxCOMPort.SelectedIndex=cbxCOMPort.Items.IndexOf(ht["

cbxCOMPort.SelectedIndex=0;

cbxCOMPort.DropDownStyle=ComboBoxStyle.DropDownList;

#region初始化计数器

tbSendCount.Text="

0"

tbSendCount.ReadOnly=true;

tbReceivedCount.Text="

tbReceivedCount.ReadOnly=true;

#region初始化当前时间

toolStripStatusLabel3.Text=DateTime.Now.ToString();

#region初始化串口状态

toolStripStatusLabel1.ForeColor=Color.Blue;

if(!

isSetProperty)//串口未设置则设置串口属性

关闭串口"

//串口打开失败后,串口属性设置标志位设为false

#region初始化间隔时间

tbSpaceTime"

tbSpaceTime.Text=ht["

].ToString();

tbSpaceTime.Text="

1000"

#region初始化按16进制显示状态

cb16Display"

ht["

].ToString()=="

True"

cb16Display.Checked=true;

cb16Display.Checked=false;

#region初始化按16进制发送状态

cb16Send"

cb16Send.Checked=true;

cb16Send.Checked=false;

#region初始化发送区文本

if(ht.ContainsKey("

tbSendData16"

ht.ContainsKey("

tbSendDataStr"

tbSendData16=ht["

tbSendDataStr=ht["

tbSendData.Text=ht["

tbSendData.Focus();

//显

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 自然科学 > 物理

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2