C#串口通信的实例教程


当前第2页 返回上一页

下面结合已有的一款继电器给出串口通信的基本用法,以供参考。

1

2

3

  1 using System;  2 using System.Windows.Forms;  3 using System.IO.Ports;  4 using System.Text;  5   6 namespace Traveller_SerialPortControl  7 {  8     public partial class Form1 : Form  9     { 10         //定义端口类 11         private SerialPort ComDevice = new SerialPort(); 12         public Form1() 13         { 14             InitializeComponent(); 15             InitralConfig(); 16         } 17         /// <summary> 18         /// 配置初始化 19         /// </summary> 20         private void InitralConfig() 21         { 22             //查询主机上存在的串口 23             comboBox_Port.Items.AddRange(SerialPort.GetPortNames()); 24  25             if (comboBox_Port.Items.Count > 0) 26             { 27                 comboBox_Port.SelectedIndex = 0; 28             } 29             else 30             { 31                 comboBox_Port.Text = "未检测到串口"; 32             } 33             comboBox_BaudRate.SelectedIndex = 5; 34             comboBox_DataBits.SelectedIndex = 0; 35             comboBox_StopBits.SelectedIndex = 0; 36             comboBox_CheckBits.SelectedIndex = 0; 37             pictureBox_Status.BackgroundImage = Properties.Resources.red; 38  39             //向ComDevice.DataReceived(是一个事件)注册一个方法Com_DataReceived,当端口类接收到信息时时会自动调用Com_DataReceived方法 40             ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived); 41         } 42  43         /// <summary> 44         /// 一旦ComDevice.DataReceived事件发生,就将从串口接收到的数据显示到接收端对话框 45         /// </summary> 46         /// <param name="sender"></param> 47         /// <param name="e"></param> 48         private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e) 49         { 50             //开辟接收缓冲区 51             byte[] ReDatas = new byte[ComDevice.BytesToRead]; 52             //从串口读取数据 53             ComDevice.Read(ReDatas, 0, ReDatas.Length); 54             //实现数据的解码与显示 55             AddData(ReDatas); 56         } 57  58         /// <summary> 59         /// 解码过程 60         /// </summary> 61         /// <param name="data">串口通信的数据编码方式因串口而异,需要查询串口相关信息以获取</param> 62         public void AddData(byte[] data) 63         { 64             if (radioButton_Hex.Checked) 65             { 66                 StringBuilder sb = new StringBuilder(); 67                 for (int i = 0; i < data.Length; i++) 68                 { 69                     sb.AppendFormat("{0:x2}" + " ", data[i]); 70                 } 71                 AddContent(sb.ToString().ToUpper()); 72             } 73             else if (radioButton_ASCII.Checked) 74             { 75                 AddContent(new ASCIIEncoding().GetString(data)); 76             } 77             else if (radioButton_UTF8.Checked) 78             { 79                 AddContent(new UTF8Encoding().GetString(data)); 80             } 81             else if (radioButton_Unicode.Checked) 82             { 83                 AddContent(new UnicodeEncoding().GetString(data)); 84             } 85             else 86             { 87                 StringBuilder sb = new StringBuilder(); 88                 for (int i = 0; i < data.Length; i++) 89                 { 90                     sb.AppendFormat("{0:x2}" + " ", data[i]); 91                 } 92                 AddContent(sb.ToString().ToUpper()); 93             } 94         } 95  96         /// <summary> 97         /// 接收端对话框显示消息 98         /// </summary> 99         /// <param name="content"></param>100         private void AddContent(string content)101         {102             BeginInvoke(new MethodInvoker(delegate103             {             

104                     textBox_Receive.AppendText(content);             

105             }));106         }107 108         /// <summary>109         /// 串口开关110         /// </summary>111         /// <param name="sender"></param>112         /// <param name="e"></param>113         private void button_Switch_Click(object sender, EventArgs e)114         {115             if (comboBox_Port.Items.Count <= 0)116             {117                 MessageBox.Show("未发现可用串口,请检查硬件设备");118                 return;119             }120 121             if (ComDevice.IsOpen == false)122             {123                 //设置串口相关属性124                 ComDevice.PortName = comboBox_Port.SelectedItem.ToString();125                 ComDevice.BaudRate = Convert.ToInt32(comboBox_BaudRate.SelectedItem.ToString());126                 ComDevice.Parity = (Parity)Convert.ToInt32(comboBox_CheckBits.SelectedIndex.ToString());127                 ComDevice.DataBits = Convert.ToInt32(comboBox_DataBits.SelectedItem.ToString());128                 ComDevice.StopBits = (StopBits)Convert.ToInt32(comboBox_StopBits.SelectedItem.ToString());129                 try130                 {131                     //开启串口132                     ComDevice.Open();133                     button_Send.Enabled = true;134                 }135                 catch (Exception ex)136                 {137                     MessageBox.Show(ex.Message, "未能成功开启串口", MessageBoxButtons.OK, MessageBoxIcon.Error);138                     return;139                 }140                 button_Switch.Text = "关闭";141                 pictureBox_Status.BackgroundImage = Properties.Resources.green;142             }143             else144             {145                 try146                 {147                     //关闭串口148                     ComDevice.Close();149                     button_Send.Enabled = false;150                 }151                 catch (Exception ex)152                 {153                     MessageBox.Show(ex.Message, "串口关闭错误", MessageBoxButtons.OK, MessageBoxIcon.Error);154                 }155                 button_Switch.Text = "开启";156                 pictureBox_Status.BackgroundImage = Properties.Resources.red;157             }158 159             comboBox_Port.Enabled = !ComDevice.IsOpen;160             comboBox_BaudRate.Enabled = !ComDevice.IsOpen;161             comboBox_DataBits.Enabled = !ComDevice.IsOpen;162             comboBox_StopBits.Enabled = !ComDevice.IsOpen;163             comboBox_CheckBits.Enabled = !ComDevice.IsOpen;164         }165 166       167         /// <summary>168         /// 将消息编码并发送169         /// </summary>170         /// <param name="sender"></param>171         /// <param name="e"></param>172         private void button_Send_Click(object sender, EventArgs e)173         {174             if (textBox_Receive.Text.Length > 0)175             {176                 textBox_Receive.AppendText("\n");177             }178 179             byte[] sendData = null;180 181             if (radioButton_Hex.Checked)182             {183                 sendData = strToHexByte(textBox_Send.Text.Trim());184             }185             else if (radioButton_ASCII.Checked)186             {187                 sendData = Encoding.ASCII.GetBytes(textBox_Send.Text.Trim());188             }189             else if (radioButton_UTF8.Checked)190             {191                 sendData = Encoding.UTF8.GetBytes(textBox_Send.Text.Trim());192             }193             else if (radioButton_Unicode.Checked)194             {195                 sendData = Encoding.Unicode.GetBytes(textBox_Send.Text.Trim());196             }197             else198             {199                 sendData = strToHexByte(textBox_Send.Text.Trim());200             }201 202             SendData(sendData);203         }204 205         /// <summary>206         /// 此函数将编码后的消息传递给串口207         /// </summary>208         /// <param name="data"></param>209         /// <returns></returns>210         public bool SendData(byte[] data)211         {212             if (ComDevice.IsOpen)213             {214                 try215                 {216                     //将消息传递给串口217                     ComDevice.Write(data, 0, data.Length);218                     return true;219                 }220                 catch (Exception ex)221                 {222                     MessageBox.Show(ex.Message, "发送失败", MessageBoxButtons.OK, MessageBoxIcon.Error);223                 }224             }225             else226             {227                 MessageBox.Show("串口未开启", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);228             }229             return false;230         }231 232         /// <summary>233         /// 16进制编码234         /// </summary>235         /// <param name="hexString"></param>236         /// <returns></returns>237         private byte[] strToHexByte(string hexString)238         {239             hexString = hexString.Replace(" ", "");240             if ((hexString.Length % 2) != 0) hexString += " ";241             byte[] returnBytes = new byte[hexString.Length / 2];242             for (int i = 0; i < returnBytes.Length; i++)243                 returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Replace(" ", ""), 16);244             return returnBytes;245         }246 247         //以下两个指令是结合一款继电器而设计的248         private void button_On_Click(object sender, EventArgs e)249         {250             textBox_Send.Text = "005A540001010000B0";251         }252 253         private void button_Off_Click(object sender, EventArgs e)254         {255             textBox_Send.Text = "005A540002010000B1";256         }257     }258 }

软件实现基本界面

以上就是C#串口通信的实例教程的详细内容!

返回前面的内容

相关阅读 >>

.net?framework?4.5?五个很棒的特性分享

c#中ini配置文件的图文代码详解

.net 玩单反的技巧

.net core 和 .net .framework 相比哪个速度快?

asp.net开发实用工具

c#之fastsocket实战项目的示例分享

.net下关于log4net的使用方法的图文代码分享

详细了解在.net core 上运行的wordpress

c#中引用类型之特例string的详细介绍

介绍c#中的堆和栈

更多相关阅读请进入《csharp》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...