找传奇、传世资源到传世资源站!

串口通讯库雏形(入门级示例)

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈


from clipboardusing System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using WYZCommunication;using System.Text.RegularExpressions;namespace WYZCommSample01{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string[] ports = System.IO.Ports.SerialPort.GetPortNames(); Array.Sort(ports); comboPort.Items.AddRange(ports); comboPort.SelectedIndex = comboPort.Items.Count > 0 ? 0 : -1; comboBaudrate.SelectedIndex = 0; device.OnRaw = device_OnRaw; //注册具体每个事件 MyDataCollection results = device.Results as MyDataCollection; results.Data1.GetNew = Data1_GetNew; results.Data2.GetNew = Data2_GetNew; } void Data1_GetNew(AnalyzeResult<int> m) { ListViewItem item = new ListViewItem("Data1"); item.SubItems.Add(m.ToString()); item.SubItems.Add(m.Valid ? "Get new" : "Data timeout"); item.SubItems.Add(DateTime.Now.ToString("HH:mm:ss")); listViewData.Invoke((EventHandler)delegate { listViewData.Items.Add(item); listViewData.EnsureVisible(listViewData.Items.Count - 1); }); } void Data2_GetNew(AnalyzeResult<SampleData> m) { ListViewItem item = new ListViewItem("Data2"); item.SubItems.Add(m.ToString()); item.SubItems.Add(m.Valid ? "Get new" : "Data timeout"); item.SubItems.Add(DateTime.Now.ToString("HH:mm:ss")); listViewData.Invoke((EventHandler)delegate { listViewData.Items.Add(item); listViewData.EnsureVisible(listViewData.Items.Count - 1); }); } void device_OnRaw(byte[] bytes) { StringBuilder builder = new StringBuilder(); textBoxRaw.Invoke((EventHandler)delegate { if (checkHex.Checked) { foreach (byte b in bytes) { builder.Append(b.ToString("X2") " "); } } else { builder.Append(device.Comm.Encoding.GetString(bytes)); } textBoxRaw.AppendText(builder.ToString()); }); } WyzComm device = new WyzComm(new SerialPort(), new MyDataCollection()); private void buttonConnect_Click(object sender, EventArgs e) { if (string.Compare(buttonConnect.Tag.ToString(), "OffLine", true) == 0) { SerialPortSetting sps = new SerialPortSetting(); sps.Baudrate = int.Parse(comboBaudrate.Text); sps.Port = int.Parse(Regex.Match(comboPort.Text, @"\d ").Value); if (device.Comm.Open(sps)) { buttonConnect.Text = "Disconnect"; buttonConnect.Tag = "OnLine"; } } else { device.Comm.Close(); buttonConnect.Tag = "OffLine"; buttonConnect.Text = "Connect"; } } private void checkWordWrap_CheckedChanged(object sender, EventArgs e) { textBoxRaw.WordWrap = checkWordWrap.Checked; } }}

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复