实例介绍
【实例简介】
【实例截图】
【核心代码】
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO.Ports; using System.Linq; using System.Text; using System.Windows.Forms; namespace COMcommunication { public partial class Form1 : Form { private SerialPort sp = new SerialPort(); bool isHex = false; //十六进制显示标志 bool isOpen = false; // bool isSetProperty = false; //属性设置标志 public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { } private bool CheckSendDate() //检测发送数据是否为空 { if (textBox2.Text.Trim() == "") return false; return true; } private void SetPortProperty() // { sp = new SerialPort(); sp.PortName = comboBox1.Text.Trim(); //设置串口名 sp.BaudRate = Convert.ToInt32(comboBox3.Text.Trim()); //设置串口波特率 string f = comboBox5.Text.Trim(); //设置停止位 switch (f) { //case 0: // sp.StopBits = StopBits.None; // break; case "1": sp.StopBits = StopBits.One; break; //case 15: // sp.StopBits = StopBits.OnePointFive; // break; case "2": sp.StopBits = StopBits.Two; break; //default: // sp.StopBits = StopBits.None; // break; } sp.DataBits = Convert.ToInt16(comboBox4.Text.Trim()); //设置数据位 string parityType = comboBox2.Text.Trim(); //设置奇偶校验 switch (parityType) { case "无校验": sp.Parity = Parity.None; break; case "奇校验": sp.Parity = Parity.Odd; break; case "偶校验": sp.Parity = Parity.Even; break; default: sp.Parity = Parity.None; break; } sp.ReadTimeout = -1; //超时读取时间 sp.RtsEnable = true; // 指示本设备准备好可接收数据 //定义Data Received事件,当串口收到数据后出发事件 sp.DataReceived = new SerialDataReceivedEventHandler(sp_DataReceived); } private void sp_DataReceived(object sender, EventArgs e) { System.Threading.Thread.Sleep(100); //延迟100ms等待接收完成数据 this.Invoke((EventHandler)( delegate { if (isHex == false) { // System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();// 显示汉字与字符 Byte[] readBytes = new Byte[sp.BytesToRead]; sp.Read(readBytes, 0, readBytes.Length); string decodedString = byteToHexStr(readBytes);//utf8.GetString(readBytes); textBox1.Text = decodedString; } else { } } )); } /// <summary> /// 16进制字节数组转字符串 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static string byteToHexStr(byte[] bytes) { string returnStr = ""; if (bytes != null) { for (int i = 0; i < bytes.Length; i ) { returnStr = bytes[i].ToString("X2") ' '; } } return returnStr.Trim(); } private void button2_Click(object sender, EventArgs e) { if (isOpen == false) { //if (!CheckSendDate()) //检测串口设置 //{ // MessageBox.Show("串口未设置", "错误提示"); // return; //} if (isSetProperty == false) // 检测 { SetPortProperty(); isSetProperty = true; } try //打开串口 { sp.Open(); isOpen = true; button2.Text = "关闭串口"; //串口打开后相关的串口设置按钮不再可选择 comboBox1.Enabled = false; comboBox2.Enabled = false; comboBox3.Enabled = false; comboBox4.Enabled = false; comboBox5.Enabled = false; } catch (Exception) { //失败后设置 isSetProperty = false; isOpen = false; MessageBox.Show("串口无效或已经被占用!", "错误提示"); } } else { sp.Close(); isOpen = false; isSetProperty = false; button2.Text = "打开串口"; //重置选择按钮有效 comboBox1.Enabled = true; comboBox2.Enabled = true; comboBox3.Enabled = true; comboBox4.Enabled = true; comboBox5.Enabled = true; } } private void button3_Click(object sender, EventArgs e) { try { //System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(); //byte[] writeBytes = utf8.GetBytes(textBox2.Text); //byte[] writeBytes11 = new Byte[data1.length]; // byte[] writeBytes = HexStringToBytes(textBox2.Text); sp.Write(writeBytes, 0, writeBytes.Length); //发送数据内容 } catch (Exception) { MessageBox.Show("发送数据时发生错误!", "错误提示"); return; } } //将16进制的字符转16进制的字节 public static byte[] HexStringToBytes(string hs) { string[] strArr = hs.Trim().Split(' ');//空格分组7E 30 30 30 31 32 41 35 30 30 30 30 30 30 30 46 44 34 37 0D byte[] b = new byte[strArr.Length]; //逐个字符变为16进制字节数据 for (int i = 0; i < strArr.Length; i ) { b[i] = Convert.ToByte(strArr[i], 16); } //按照指定编码将字节数组变为字符串 return b; } } }
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论