c上位机串口通信助手源代码详解

合集下载

上位机-串口通信详解(以RS232为例))

上位机-串口通信详解(以RS232为例))

上位机-串⼝通信详解(以RS232为例))1、什么是串⼝通信?写这个的时候我在想应该怎么解释串⼝通信,因为串⼝通信很多朋友不了解的原因是涉及到硬件的知识,对于没有相关专业知识的朋友很难理解串⼝通信。

所以我这⾥只做部分的解释,需要了解更多硬件相关信息的朋友可以看这篇博⽂:串⼝通信在百度词条上的解释是:串⼝通信(Serial Communications)的概念⾮常简单,串⼝按位(bit)发送和接收的。

简单的解释就是:两个⼈说话,⼀个⼈说,⼀个⼈听。

是的,就是这个么简单。

如果不需要了解硬件,那么我们只需要了解通信,串⼝不需要理解,那是硬件⼯程师需要考虑的事情。

我们今天讲的是上位机与串⼝通信,重点是通信。

2、串⼝通信协议所谓通信协议是指通信双⽅的⼀种约定。

约定包括对数据格式、同步⽅式、传送速度、传送步骤、检纠错⽅式以及控制字符定义等问题做出统⼀规定,通信双⽅必须共同遵守。

串⼝通信协议中,很多朋友很疑惑,RS232,RS485这些协议怎么⽤?但实际上这些准确来说,是⼀种标准。

我们可以直接使⽤这种标准进⾏通信,完全没有任何问题。

还有⼀种⾃定义通信协议,顾名思义,⾃定义通信协议是基于需求编写的,符合RS232等标准的协议。

这部分对于上位机来说,我们只需要得到第三⽅提供的⾃定义通信协议,根据其中的内容进⾏编程即可,具体的功能实现是由硬件⼯程师实现。

在通信协议中,最重要的是端⼝(com)、波特率、数据位、校验位、停⽌位。

3、实现⼀个demo通过上⾯的了解,上位机⼯程师应该有⼀个概念,上位机与串⼝的通信重点是通信,常⽤的通信可以直接使⽤标准的完成,但是如果是属于⾃定义通信协议的,需要提供⾃定义的通信协议。

1)⾸先我们实现⼀个界⾯,如下:2)配置串⼝参数-打开串⼝3)发送数据4)接收数据1、使⽤异步接收数据2、如果需要写完之后直接读,参考以下⽅法:5)效果图:6)基于⾃定义协议的通信(发送和接收都使⽤16进制进⾏)⾸先⾃定义⼀个通信协议:1、使⽤RS232进⾏通信,设定如下:波特率:9600数据位:8停⽌位:1奇偶校验:⽆2、通信协议内容:1)寄存器1 置1 执⾏功能1 地址 0b2)寄存器2 置1 执⾏功能2 地址 1b3)crc校验:将数据+地址等通过与或等操作⽣成的⼀个值(⼀般⾃定义的都会进⾏校验)4)开始位:015)结束位: 056)地址位:0a(根据不同寄存器决定)7)结果位:0e (成功0e,失败00)发送例⼦:执⾏功能101 0b 01 00 00 00 00 00 00 00 06 0e 05解析:01是开始位,0b是对应寄存器1的地址,数据长度是8,没有数据的置00,06是crc校验⽣成值,0e是结果位,05 是结束位。

基于C#的串口通信上位机和下位机源程序

基于C#的串口通信上位机和下位机源程序

基于C#的串口通信上位机和下位机源程序基于单片机串口通信的上位机和下位机实践串口是计算机上一种非常通用设备通信的协议(不要与通用串行总线Universal Serial Bus 或者USB混淆)。

大多数计算机包含两个基于RS232的串口。

串口同时也是仪器仪表设备通用的通信协议;很多GPIB兼容的设备也带有RS-232口。

同时,串口通信协议也可以用于获取远程采集设备的数据。

串口通信的概念非常简单,串口按位(bit)发送和接收字节。

尽管比按字节(byte)的并行通信慢,但是串口可以在使用一根线发送数据的同时用另一根线接收数据。

它很简单并且能够实现远距离通信。

比如IEEE488定义并行通行状态时,规定设备线总常不得超过20米,并且任意两个设备间的长度不得超过2米;而对于串口而言,长度可达1200米。

首先亮出C#的源程序吧。

主要界面:只是作为简单的运用,可以扩展的。

源代码:using System;using System.Collections.Generic;using System.ponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.IO.Ports;using System.Timers;namespace 单片机功能控制{public partial class Form1 : Form{public Form1(){Initializeponent();}SerialPort sp = new SerialPort();private void button1_Click(object sender, EventArgs e) {String str1 = boBox1.Text;//串口号String str2 = boBox2.Text;//波特率String str3 = boBox3.Text;//校验位String str4 = boBox5.Text;//停止位String str5 = boBox4.Text;//数据位Int32 int2 = Convert.ToInt32(str2);//将字符串转为整型Int32 int5 = Convert.ToInt32(str5);//将字符串转为整型groupBox3.Enabled = true;//LED控制界面变可选try{if (button1.Text == "打开串口"){if (str1 == null){MessageBox.Show("请先选择串口!", "Error"); return;}sp.Close();sp = new SerialPort();sp.PortName = boBox1.Text;//串口编号sp.BaudRate = int2;//波特率switch (str4)//停止位{case "1":sp.StopBits = StopBits.One;break;case "1.5":sp.StopBits = StopBits.OnePointFive;break;case "2":sp.StopBits = StopBits.Two;break;default:MessageBox.Show("Error:参数不正确", "Error"); break;}switch (str3){case "NONE":sp.Parity = Parity.None; break;case "ODD":sp.Parity = Parity.Odd; break;case "EVEN":sp.Parity = Parity.Even; break;default:MessageBox.Show("Error:参数不正确", "Error"); break;}sp.DataBits = int5;//数据位sp.Parity = Parity.Even;//设置串口属性sp.Open();//打开串口button1.Text = "关闭串口";textBox1.Text = Convert.T oString(sp.PortName) + "已开启!"; }else{sp.Close();button1.Text = "打开串口";groupBox3.Enabled = false;//LED控制界面变灰色textBox1.Text = Convert.T oString(sp.PortName) + "已关闭!"; }}catch (Exception er){MessageBox.Show("Error:" + er.Message, "Error"); return;}}private void Form1_Load(object sender, EventArgs e){//初始化textBox1.Text = "欢迎使用简易的串口助手!";groupBox3.Enabled = false;//LED控制界面变灰色groupBox6.Enabled = false;groupBox7.Enabled = false;groupBox8.Enabled = false;button3.Enabled = false;button6.Enabled = false;timer1.Start();try{foreach (string in System.IO.Ports.SerialPort.GetPortNames()) //自动获取串行口名称this.boBox1.Items.Add();//默认设置boBox1.SelectedIndex = 0;//选择第一个口boBox2.SelectedIndex = 4;//波特率4800boBox3.SelectedIndex = 0;//校验位NONEboBox4.SelectedIndex = 0;//停止位为1boBox5.SelectedIndex = 0;//数据位为8}catch{MessageBox.Show("找不到通讯端口!", "串口调试助手");}}private void timer1_Tick(object sender, EventArgs e){label6.Text = DateTime.Now.T oString();}private void button2_Click(object sender, EventArgs e){try {if (button2.Text == "开启"){groupBox6.Enabled = true;radioButton1.Checked = false;radioButton2.Checked = false;radioButton3.Checked = false;radioButton4.Checked = false;checkBox1.Checked = false;checkBox2.Checked = false;checkBox3.Checked = false;checkBox5.Checked = false;checkBox6.Checked = false;checkBox7.Checked = false;checkBox8.Checked = false;button3.Enabled = true;textBox2.Text = String.Empty;button2.Text = "关闭";}else{groupBox6.Enabled = false;button3.Enabled = false;button2.Text = "开启";textBox2.Text = String.Empty;}}catch (Exception er){MessageBox.Show("Error:" + er.Message, "Error"); return;}}private void button3_Click(object sender, EventArgs e) {groupBox6.Enabled = true;label7.Text = "已发送";if (textBox2.Text == "")MessageBox.Show("发送失败,请选择发送的数据!");elsesp.WriteLine(textBox2.Text);//往串口写数据}private void checkBox1_CheckedChanged(object sender, EventArgs e){try {if (checkBox1.Checked){checkBox1.Checked = true;checkBox2.Checked = false;checkBox3.Checked = false;checkBox5.Checked = false;checkBox6.Checked = false;checkBox7.Checked = false;checkBox8.Checked = false;label7.Text = "准备发送";textBox2.Text = "1";}}catch (Exception er){MessageBox.Show("Error:" + er.Message, "Error");return;}}private void checkBox2_CheckedChanged(object sender, EventArgs e) {try {if (checkBox2.Checked){checkBox1.Checked = false;checkBox2.Checked = true;checkBox3.Checked = false;checkBox4.Checked = false;checkBox5.Checked = false;checkBox6.Checked = false;checkBox7.Checked = false;checkBox8.Checked = false;label7.Text = "准备发送";textBox2.Text = "2";radioButton1.Checked = false;radioButton2.Checked = false;radioButton3.Checked = false;radioButton4.Checked = false;}}catch (Exception er){MessageBox.Show("Error:" + er.Message, "Error");return;}}private void checkBox3_CheckedChanged(object sender, EventArgs e) {try{if (checkBox3.Checked){checkBox1.Checked = false;checkBox3.Checked = true;checkBox4.Checked = false;checkBox5.Checked = false;checkBox6.Checked = false;checkBox7.Checked = false;checkBox8.Checked = false;radioButton1.Checked = false;radioButton2.Checked = false;radioButton3.Checked = false;radioButton4.Checked = false;label7.Text = "准备发送";textBox2.Text = "3";}}catch (Exception er){MessageBox.Show("Error:" + er.Message, "Error");return;}}private void checkBox4_CheckedChanged(object sender, EventArgs e) {try{if (checkBox4.Checked){checkBox1.Checked = false;checkBox2.Checked = false;checkBox3.Checked = false;checkBox5.Checked = false;checkBox6.Checked = false;checkBox7.Checked = false;checkBox8.Checked = false;radioButton1.Checked = false;radioButton2.Checked = false;radioButton3.Checked = false;radioButton4.Checked = false;label7.Text = "准备发送";textBox2.Text = "4";}}catch (Exception er){MessageBox.Show("Error:" + er.Message, "Error");return;}}private void checkBox5_CheckedChanged(object sender, EventArgs e) {try{if (checkBox5.Checked){checkBox1.Checked = false;checkBox2.Checked = false;checkBox3.Checked = false;checkBox4.Checked = false;checkBox5.Checked = true;checkBox7.Checked = false;checkBox8.Checked = false;radioButton1.Checked = false;radioButton2.Checked = false;radioButton3.Checked = false;radioButton4.Checked = false;label7.Text = "准备发送";textBox2.Text = "5";}}catch (Exception er){MessageBox.Show("Error:" + er.Message, "Error");return;}}private void checkBox6_CheckedChanged(object sender, EventArgs e){try{if (checkBox6.Checked){checkBox1.Checked = false;checkBox2.Checked = false;checkBox3.Checked = false;checkBox4.Checked = false;checkBox5.Checked = false;checkBox6.Checked = true;checkBox8.Checked = false;radioButton1.Checked = false;radioButton2.Checked = false;radioButton3.Checked = false;radioButton4.Checked = false;label7.Text = "准备发送";textBox2.Text = "6";}}catch (Exception er){MessageBox.Show("Error:" + er.Message, "Error");return;}}private void checkBox7_CheckedChanged(object sender, EventArgs e){try{if (checkBox7.Checked){checkBox1.Checked = false;checkBox2.Checked = false;checkBox3.Checked = false;checkBox4.Checked = false;checkBox5.Checked = false;checkBox6.Checked = false;checkBox7.Checked = true;radioButton1.Checked = false;radioButton2.Checked = false;radioButton3.Checked = false;radioButton4.Checked = false;label7.Text = "准备发送";textBox2.Text = "7";}}catch (Exception er){MessageBox.Show("Error:" + er.Message, "Error");return;}}private void checkBox8_CheckedChanged(object sender, EventArgs e) {try{if (checkBox8.Checked){checkBox1.Checked = false;checkBox2.Checked = false;checkBox3.Checked = false;checkBox4.Checked = false;checkBox5.Checked = false;checkBox6.Checked = false;checkBox7.Checked = false;checkBox8.Checked = true;radioButton1.Checked = false;radioButton2.Checked = false;radioButton3.Checked = false;radioButton4.Checked = false;label7.Text = "准备发送";textBox2.Text = "8";}}catch (Exception er){MessageBox.Show("Error:" + er.Message, "Error"); return;}}private void button5_Click(object sender, EventArgs e) { try{if (button5.Text == "开启"){radioButton1.Checked = false;radioButton2.Checked = false;radioButton3.Checked = false;radioButton4.Checked = false;checkBox1.Checked = false;checkBox2.Checked = false;checkBox3.Checked = false;checkBox4.Checked = false;checkBox5.Checked = false;checkBox6.Checked = false;checkBox7.Checked = false;checkBox8.Checked = false;groupBox7.Enabled = true;button6.Enabled = true;textBox2.Text = String.Empty;button5.Text = "关闭";}else{groupBox7.Enabled = false;button6.Enabled = false;button5.Text = "开启";textBox2.Text = String.Empty;}}catch (Exception er){MessageBox.Show("Error:" + er.Message, "Error");return;}}private void button6_Click(object sender, EventArgs e) {label7.Text = "已发送";if (textBox2.Text == "")MessageBox.Show("发送失败。

C语言实现串口通信

C语言实现串口通信

C语言实现串口通信在使用系统调用函数进行串口通信之前,需要打开串口设备并设置相关参数。

打开串口设备可以使用open(函数,设置串口参数可以使用termios结构体和tcsetattr(函数。

以下是一个简单的串口通信接收数据的示例代码:```c#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include <unistd.h>#include <termios.h>int mainint fd; // 串口设备文件描述符char buff[255]; // 存储接收到的数据int len; // 接收到的数据长度//打开串口设备fd = open("/dev/ttyS0", O_RDONLY);if (fd < 0)perror("Failed to open serial port");return -1;}//设置串口参数struct termios options;tcgetattr(fd, &options);cfsetspeed(&options, B1200); // 设置波特率为1200 tcsetattr(fd, TCSANOW, &options);//接收数据while (1)len = read(fd, buff, sizeof(buff)); // 从串口读取数据if (len > 0)buff[len] = '\0'; // 将接收到的数据转为字符串printf("Received data: %s\n", buff);}}//关闭串口设备close(fd);return 0;```这段代码首先通过open(函数打开串口设备文件"/dev/ttyS0",然后使用tcgetattr(函数获取当前设置的串口参数,接着使用cfsetspeed(函数设置波特率为1200,最后使用tcsetattr(函数将设置好的串口参数写回。

c#上位机串口通信助手源代码详解

c#上位机串口通信助手源代码详解

c#上位机串口通信助手源代码实例详解一、功能1软件打开时,自动检测有效COM端口2 软件打开时,自动复原到上次关闭时的状态3 不必关闭串口,即可直接进行更改初始化设置内容(串口号、波特率、数据位、停止位、校验位),可按更改后的信息自动将串口重新打开4 可统计接收字节和发送字节的个数5 接收数据可按16进制数据和非16进制数据进行整体转换6 可将接收到数据进行保存7 可设置自动发送,发送时间可进行实时更改8可按字符串、16进制字节、文件方式进行发送,字符串和16进制字节可分别进行存储,内容互不干扰9 按16进制发送时,可自动校验格式,不会输错10 可清空发送或接收区域的数据二、使用工具Visual Studio2015三、程序详解1 界面创建图1用winform创建如图1所示界面,控件名字分别为:端口号:cbxCOMPort 波特率:cbxBaudRate数据位:cbxDataBits 停止位:cbxStopBits校验位:label5 打开串口按钮:btnOpenCom发送(byte):tbSendCount 接收(byte):tbReceivedCount 清空计数按钮:btnClearCount 按16进制显示:cb16Display接收区清空内容按钮:btnClearReceived 保存数据按钮:btnSaveFile接收数据框:tbReceivedData 发送数据框:tbSendData自动发送:cbAutomaticSend 间隔时间:tbSpaceTime按16进制发送:cb16Send 发送区清空内容按钮:btnClearSend 读入文件按钮:btnReadFile 发送按钮:btnSend2 创建一个方法类按Ctrl+shift+A快捷键创建一个类,名字叫Methods,代码为:using System;using System.Collections;using System.Collections.Generic;using System.IO.Ports;using System.Linq;using System.Text;using System.Threading.Tasks;namespace串口助手sdd{class Methods{//获取有效的COM口public static string[] ActivePorts(){ArrayList activePorts = new ArrayList();foreach (string pname in SerialPort.GetPortNames()){activePorts.Add(Convert.ToInt32(pname.Substring(3)));}activePorts.Sort();string[] mystr = new string[activePorts.Count];int i = 0;foreach (int num in activePorts){mystr[i++] = "COM" + num.ToString();}return mystr;}//16进制字符串转换为byte字符数组public static Byte[] _16strToHex(string strValues){string[] hexValuesSplit = strValues.Split(' ');Byte[] hexValues = new Byte[hexValuesSplit.Length];Console.WriteLine(hexValuesSplit.Length);for (int i = 0; i < hexValuesSplit.Length; i++){hexValues[i] = Convert.ToByte(hexValuesSplit[i], 16);}return hexValues;}//byte数组以16进制形式转字符串public static string ByteTo16Str(byte[] bytes){string recData = null;//创建接收数据的字符串foreach (byte outByte in bytes)//将字节数组以16进制形式遍历到一个字符串内 {recData += outByte.ToString("X2") + " ";}return recData;}//16进制字符串转换字符串public static string _16strToStr(string _16str){string outStr = null;byte[] streamByte = _16strToHex(_16str);outStr = Encoding.Default.GetString(streamByte);return outStr;}}}2 Form1.cs的代码为:using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.IO.Ports;using System.Linq;using System.Text;using System.Text.RegularExpressions;using System.Threading.Tasks;using System.Windows.Forms;using System.IO;using System.Collections;namespace串口助手sdd{public partial class Form1 : Form{//声明变量SerialPort sp = new SerialPort();bool isSetProperty = false;//串口属性设置标志位private enum PortState//声明接口显示状态,枚举型{打开,关闭}string path = AppDomain.CurrentDomain.BaseDirectory + "confing.ini";//声明配置文件路径string tbSendDataStr = "";//发送窗口字符串存储string tbSendData16 = "";//发送窗口16进制存储List<byte> receivedDatas = new List<byte>();//接收数据泛型数组//接收串口数据private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) {byte[] ReceivedData = new byte[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());elsetbReceivedData.Text =Encoding.Default.GetString(receivedDatas.ToArray());sp.DiscardInBuffer();//丢弃接收缓冲区数据}//发送串口数据private void DataSend(){try{if (cb16Send.Checked){byte[] hexBytes = Methods._16strToHex(tbSendData16);sp.Write(hexBytes, 0, hexBytes.Length);tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + hexBytes.Length).ToString();}else{sp.WriteLine(tbSendDataStr);tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + tbSendDataStr.Length).ToString();}}catch (Exception ex){MessageBox.Show(ex.Message.ToString());return;}}//设置串口属性private void SetPortProperty(){sp.PortName = cbxCOMPort.Text.Trim();//设置串口名sp.BaudRate = Convert.ToInt32(cbxBaudRate.Text.Trim());//设置波特率switch (cbxStopBits.Text.Trim())//设置停止位{case"1": sp.StopBits = StopBits.One; break;case"1.5": sp.StopBits = StopBits.OnePointFive; break;case"2": sp.StopBits = StopBits.Two; break;default: sp.StopBits = StopBits.None; break;}sp.DataBits = Convert.ToInt32(cbxDataBits.Text.Trim());//设置数据位switch (cbxParity.Text.Trim())//设置奇偶校验位{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 = 5000;//设置超时时间为5sControl.CheckForIllegalCrossThreadCalls = false;//这个类中我们不检查跨线程的调用是否合法(因为.net 2.0以后加强了安全机制,,不允许在winform中直接跨线程访问控件的属性)//定义DataReceived事件的委托,当串口收到数据后出发事件sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);}//设置端口显示状态private void DisplayPortState(PortState portState){toolStripStatusLabel1.Text = cbxCOMPort.Text + "端口处于" + portState + "状态 " + cbxBaudRate.Text + " " + cbxDataBits.Text + " " + cbxStopBits.Text + " " + cbxParity.Text;}//重新打开串口private void AgainOpenPort(){if (sp.IsOpen){try{sp.Close();SetPortProperty();isSetProperty = true;sp.Open();}catch (Exception){isSetProperty = false;btnOpenCom.Text = "打开串口";DisplayPortState(PortState.关闭);MessageBox.Show("串口无效或已被占用!", "错误提示");return;}DisplayPortState(PortState.打开);}else{DisplayPortState(PortState.关闭);}}public Form1(){InitializeComponent();}//软件启动时加载事件private void Form1_Load(object sender, EventArgs e){#region加载配置文件Hashtable ht = new Hashtable();if (File.Exists(path)){try{string myline = "";string[] str = new string[2];using (StreamReader sr = new StreamReader(path)) {myline = sr.ReadLine();while (myline != null){str = myline.Split('=');ht.Add(str[0], str[1]);myline = sr.ReadLine();}}}catch(Exception ex){MessageBox.Show(ex.Message.ToString());}}#endregion#region设置窗口为固定大小且不可最大化this.MaximumSize = this.Size;this.MinimumSize = this.Size;this.MaximizeBox = false;#endregion#region列出常用的波特率cbxBaudRate.Items.Add("1200");cbxBaudRate.Items.Add("2400");cbxBaudRate.Items.Add("4800");cbxBaudRate.Items.Add("9600");cbxBaudRate.Items.Add("19200");cbxBaudRate.Items.Add("38400");cbxBaudRate.Items.Add("43000");cbxBaudRate.Items.Add("56000");cbxBaudRate.Items.Add("57600");cbxBaudRate.Items.Add("115200");if (ht.ContainsKey("cbxBaudRate"))cbxBaudRate.SelectedIndex =cbxBaudRate.Items.IndexOf(ht["cbxBaudRate"].ToString());elsecbxBaudRate.SelectedIndex = 3;cbxBaudRate.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region列出停止位cbxStopBits.Items.Add("1");cbxStopBits.Items.Add("1.5");cbxStopBits.Items.Add("2");if (ht.ContainsKey("cbxStopBits"))cbxStopBits.SelectedIndex =cbxStopBits.Items.IndexOf(ht["cbxStopBits"].ToString());elsecbxStopBits.SelectedIndex = 0;cbxStopBits.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region列出数据位cbxDataBits.Items.Add("8");cbxDataBits.Items.Add("7");cbxDataBits.Items.Add("6");cbxDataBits.Items.Add("5");if (ht.ContainsKey("cbxDataBits"))cbxDataBits.SelectedIndex =cbxDataBits.Items.IndexOf(ht["cbxDataBits"].ToString());elsecbxDataBits.SelectedIndex = 0;cbxDataBits.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region列出奇偶校验位cbxParity.Items.Add("无");cbxParity.Items.Add("奇校验");cbxParity.Items.Add("偶校验");if (ht.ContainsKey("cbxParity"))cbxParity.SelectedIndex =cbxParity.Items.IndexOf(ht["cbxParity"].ToString());elsecbxParity.SelectedIndex = 0;cbxParity.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region COM口重新加载cbxCOMPort.Items.Clear();//清除当前串口号中的所有串口名称 cbxCOMPort.Items.AddRange(Methods.ActivePorts());if (ht.ContainsKey("cbxCOMPort") &&cbxCOMPort.Items.Contains(ht["cbxCOMPort"].ToString()))cbxCOMPort.SelectedIndex =cbxCOMPort.Items.IndexOf(ht["cbxCOMPort"].ToString());elsecbxCOMPort.SelectedIndex = 0;cbxCOMPort.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region初始化计数器tbSendCount.Text = "0";tbSendCount.ReadOnly = true;tbReceivedCount.Text = "0";tbReceivedCount.ReadOnly = true;#endregion#region初始化当前时间toolStripStatusLabel3.Text = DateTime.Now.ToString();#endregion#region初始化串口状态toolStripStatusLabel1.ForeColor = Color.Blue;if (!isSetProperty)//串口未设置则设置串口属性{SetPortProperty();isSetProperty = true;}try{sp.Open();btnOpenCom.Text = "关闭串口";DisplayPortState(PortState.打开);}catch (Exception){//串口打开失败后,串口属性设置标志位设为falseisSetProperty = false;MessageBox.Show("串口无效或已被占用!", "错误提示"); }#endregion#region初始化间隔时间if (ht.ContainsKey("tbSpaceTime"))tbSpaceTime.Text = ht["tbSpaceTime"].ToString();elsetbSpaceTime.Text = "1000";#endregion#region初始化按16进制显示状态if (ht.ContainsKey("cb16Display") && ht["cb16Display"].ToString() == "True") cb16Display.Checked = true;elsecb16Display.Checked = false;#endregion#region初始化按16进制发送状态if (ht.ContainsKey("cb16Send") && ht["cb16Send"].ToString() == "True")cb16Send.Checked = true;elsecb16Send.Checked = false;#endregion#region初始化发送区文本if(ht.ContainsKey("tbSendData16") && ht.ContainsKey("tbSendDataStr")){tbSendData16 = ht["tbSendData16"].ToString();tbSendDataStr = ht["tbSendDataStr"].ToString();if (cb16Send.Checked)tbSendData.Text = ht["tbSendData16"].ToString();elsetbSendData.Text = ht["tbSendDataStr"].ToString();}#endregiontbSendData.Focus();}//显示当前时间private void timer1_Tick(object sender, EventArgs e){toolStripStatusLabel3.Text = DateTime.Now.ToString();}//点击打开串口按钮private void btnOpenCom_Click(object sender, EventArgs e){if (!sp.IsOpen)//串口没有打开时{if (!isSetProperty)//串口未设置则设置串口属性{SetPortProperty();isSetProperty = true;}try{sp.Open();btnOpenCom.Text = "关闭串口";DisplayPortState(PortState.打开);}catch (Exception){//串口打开失败后,串口属性设置标志位设为falseisSetProperty = false;MessageBox.Show("串口无效或已被占用!", "错误提示"); }}else//串口已经打开{try{sp.Close();isSetProperty = false;btnOpenCom.Text = "打开串口";DisplayPortState(PortState.关闭);}catch (Exception){MessageBox.Show("关闭串口时发生错误", "错误提示"); }}}//发送串口数据private void btnSend_Click(object sender, EventArgs e){if (tbSendData.Text.Trim() == "")//检测发送数据是否为空{MessageBox.Show("请输入要发送的数据!", "错误提示");return;}if (sp.IsOpen){DataSend();}else{MessageBox.Show("串口未打开!", "错误提示");}}//点击端口号选择下拉框按钮private void cbxCOMPort_SelectedIndexChanged(object sender, EventArgs e){AgainOpenPort();}//点击波特率选择下拉框按钮private void cbxBaudRate_SelectedIndexChanged(object sender, EventArgs e) {AgainOpenPort();}//点击数据位选择下拉框按钮private void cbxDataBits_SelectedIndexChanged(object sender, EventArgs e) {AgainOpenPort();}//点击停止位选择下拉框按钮private void cbxStopBits_SelectedIndexChanged(object sender, EventArgs e) {AgainOpenPort();}//点击校验位选择下拉框按钮private void cbxParity_SelectedIndexChanged(object sender, EventArgs e){AgainOpenPort();}//点击数据接收区清空按钮private void btnClearReceived_Click(object sender, EventArgs e){receivedDatas.Clear();tbReceivedData.Text = "";}//点击是否按16进制显示接收数据private void cb16Display_CheckedChanged(object sender, EventArgs e){if (cb16Display.Checked)tbReceivedData.Text = Methods.ByteTo16Str(receivedDatas.ToArray());elsetbReceivedData.Text =Encoding.Default.GetString(receivedDatas.ToArray());//点击是否按16进制发送数据private void cb16Send_CheckedChanged(object sender, EventArgs e){if (cb16Send.Checked){tbSendData.Text = tbSendData16;}else{tbSendData.Text = tbSendDataStr;}}//发送文本框键盘按键检测private void tbSendData_KeyPress(object sender, KeyPressEventArgs e){if (cb16Send.Checked){//正则匹配string pattern = "[0-9a-fA-F]|\b";//\b:退格键Match m = Regex.Match(e.KeyChar.ToString(), pattern);if (m.Success){if(e.KeyChar != '\b'){if (tbSendData.Text.Length % 3 == 2){tbSendData.Text += " ";tbSendData.SelectionStart = tbSendData.Text.Length;}e.KeyChar = Convert.ToChar(e.KeyChar.ToString().ToUpper()); }e.Handled = false;}else{e.Handled = true;}}else{e.Handled = false;}}//点击清空发送内容private void btnClearSend_Click(object sender, EventArgs e){tbSendData.Text = "";if (cb16Send.Checked)tbSendData16 = "";elsetbSendDataStr = "";//点击清空计数器数据private void btnClearCount_Click(object sender, EventArgs e){tbReceivedCount.Text = "0";tbSendCount.Text = "0";}//点击是否设置自动发送private void cbAutomaticSend_CheckedChanged(object sender, EventArgs e) {if (cbAutomaticSend.Checked){timer2.Enabled = true;timer2.Interval = Convert.ToInt32(tbSpaceTime.Text);}else{timer2.Enabled = false;}}//自动发送时间文本框键盘按键检测private void tbSpaceTime_KeyPress(object sender, KeyPressEventArgs e) {//正则匹配string pattern = "[0-9]|\b";Match m = Regex.Match(e.KeyChar.ToString(),pattern);if (m.Success){timer2.Interval = Convert.ToInt32(tbSpaceTime.Text);e.Handled = false;}else{e.Handled = true;}}//串口显示状态private void timer2_Tick(object sender, EventArgs e){if (sp.IsOpen){DataSend();}else{timer2.Enabled = false;cbAutomaticSend.Checked = false;MessageBox.Show("串口未打开!", "错误提示");return;}if (tbSendData.Text.Trim() == "")//检测发送数据是否为空{timer2.Enabled = false;cbAutomaticSend.Checked = false;MessageBox.Show("请输入要发送的数据!", "错误提示");return;}}//关闭窗口时出发的事件private void Form1_FormClosed(object sender, FormClosedEventArgs e){try{using (StreamWriter sw = new StreamWriter(path, false)){sw.WriteLine("cbxCOMPort=" + cbxCOMPort.Text);sw.WriteLine("cbxBaudRate=" + cbxBaudRate.Text);sw.WriteLine("cbxDataBits=" + cbxDataBits.Text);sw.WriteLine("cbxStopBits=" + cbxStopBits.Text);sw.WriteLine("cbxParity=" + cbxParity.Text);sw.WriteLine("cb16Display="+ cb16Display.Checked.ToString()); sw.WriteLine("tbSpaceTime=" + tbSpaceTime.Text);sw.WriteLine("cb16Send=" + cb16Send.Checked.ToString());sw.WriteLine("tbSendDataStr=" + tbSendDataStr);sw.WriteLine("tbSendData16=" + tbSendData16);sp.Close();}}catch(Exception ex){MessageBox.Show(ex.Message.ToString());}}//发送文本框按键抬起时出发的事件private void tbSendData_KeyUp(object sender, KeyEventArgs e){if (cb16Send.Checked){tbSendData16 = tbSendData.Text.Trim();}else{tbSendDataStr = tbSendData.Text;}}//点击读入文件按钮private void btnReadFile_Click(object sender, EventArgs e){openFileDialog1.Filter = "所有文件(*.*)|*.*";//文件筛选器的设定openFileDialog1.FilterIndex = 1;openFileDialog1.Title = "选择文件";openFileDialog1.FileName = "";openFileDialog1.ShowHelp = true;if(openFileDialog1.ShowDialog() == DialogResult.OK){using (FileStream fs = newFileStream(openFileDialog1.FileName,FileMode.Open)){byte[] bufferByte = new byte[fs.Length];fs.Read(bufferByte, 0, Convert.ToInt32(fs.Length));sp.Write(bufferByte, 0, bufferByte.Length);tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + bufferByte.Length).ToString();}}}//点击保存数据按钮private void btnSaveFile_Click(object sender, EventArgs e){saveFileDialog1.Filter = "所有文件(*.*)|*.*";if(saveFileDialog1.ShowDialog() == DialogResult.OK){string fName = saveFileDialog1.FileName;using(FileStream fs = File.Open(fName, FileMode.Append)){fs.Write(receivedDatas.ToArray(), 0, receivedDatas.Count);}}}}}需要源代码或有疑问的c#爱好者们,欢迎加入c#技术交流群(33647125),附加信息为”我以下载此文档”,进群后找群主索要源代码或进行技术交流。

易语言串口通讯modbus协议模块上位机必备例子源代码

易语言串口通讯modbus协议模块上位机必备例子源代码

易语言串口通讯modbus协议模块上位机必备例子源代码1.引言1.1 概述在编写易语言串口通讯modbus协议模块上位机必备例子源代码之前,我们首先需要了解一些基本概念和背景知识。

本文介绍了该例子的目的和结构,以及引言、正文和结论三个主要部分的内容。

1.1概述Modbus协议是一种常用的串行通信协议,广泛应用于工业自动化领域。

它被设计用于在不同设备之间进行数据传输和通信。

Modbus协议简洁明了,易于实现和部署,因此被许多工业设备和上位机所采用。

易语言是一种面向过程的编程语言,易于学习和使用。

它提供了丰富的库和模块,方便我们进行串口通讯编程。

易语言的特点是语法简单易懂,同时也支持调用其他语言编写的DLL函数,可以实现更加复杂的功能。

本例子的目标是演示如何使用易语言编写一个串口通讯的Modbus 协议模块,并结合上位机的必备功能来实现数据的读写和显示。

在正文部分,我们将介绍Modbus协议的简要概述,包括其通信方式、数据格式、功能码等。

同时,我们还将介绍易语言中的串口通讯模块及其基本用法。

在结论部分,我们将提供一些实例源代码示例,以便读者更好地理解和使用这个例子。

此外,我们还将列举一些上位机必备的功能,以供读者参考和扩展应用。

通过这个例子,读者可以学习到如何使用易语言进行串口通讯编程,并了解Modbus协议在实际应用中的运用。

同时,读者也可以根据自己的需求和实际情况,对例子进行二次开发和改进,以适应不同的应用场景。

在下一节中,我们将详细介绍Modbus协议的相关知识,以便读者更好地理解本例子的内容和实现。

文章结构部分主要是对整篇文章的组织和安排进行介绍,以下是1.2 文章结构的内容:1.2 文章结构本文主要分为三个部分,包括引言、正文和结论,具体如下:1. 引言部分介绍了本文的概述、文章结构和目的。

在概述中,我们对易语言串口通讯modbus协议模块上位机必备例子源代码进行了简要介绍,指出了本文的主要内容和目标。

c上位机串口通信助手源代码详解

c上位机串口通信助手源代码详解

For personal use only in study andresearch; not for commercial usec#上位机串口通信助手源代码实例详解一、功能1软件打开时,自动检测有效COM端口2 软件打开时,自动复原到上次关闭时的状态3 不必关闭串口,即可直接进行更改初始化设置内容(串口号、波特率、数据位、停止位、校验位),可按更改后的信息自动将串口重新打开4 可统计接收字节和发送字节的个数5 接收数据可按16进制数据和非16进制数据进行整体转换6 可将接收到数据进行保存7 可设置自动发送,发送时间可进行实时更改8可按字符串、16进制字节、文件方式进行发送,字符串和16进制字节可分别进行存储,内容互不干扰9 按16进制发送时,可自动校验格式,不会输错10 可清空发送或接收区域的数据二、使用工具Visual Studio2015三、程序详解1 界面创建图1用winform创建如图1所示界面,控件名字分别为:端口号:cbxCOMPort 波特率:cbxBaudRate数据位:cbxDataBits 停止位:cbxStopBits校验位:label5 打开串口按钮:btnOpenCom发送(byte):tbSendCount 接收(byte):tbReceivedCount 清空计数按钮:btnClearCount 按16进制显示:cb16Display接收区清空内容按钮:btnClearReceived 保存数据按钮:btnSaveFile接收数据框:tbReceivedData 发送数据框:tbSendData自动发送:cbAutomaticSend 间隔时间:tbSpaceTime按16进制发送:cb16Send 发送区清空内容按钮:btnClearSend 读入文件按钮:btnReadFile 发送按钮:btnSend2 创建一个方法类按Ctrl+shift+A快捷键创建一个类,名字叫Methods,代码为:using System;using System.Collections;using System.Collections.Generic;using System.IO.Ports;using System.Linq;using System.Text;using System.Threading.Tasks;namespace串口助手sdd{class Methods{//获取有效的COM口public static string[] ActivePorts(){ArrayList activePorts = new ArrayList();foreach (string pname in SerialPort.GetPortNames()){activePorts.Add(Convert.ToInt32(pname.Substring(3)));}activePorts.Sort();string[] mystr = new string[activePorts.Count];int i = 0;foreach (int num in activePorts){mystr[i++] = "COM" + num.ToString();}return mystr;}//16进制字符串转换为byte字符数组public static Byte[] _16strToHex(string strValues){string[] hexValuesSplit = strValues.Split(' ');Byte[] hexValues = new Byte[hexValuesSplit.Length];Console.WriteLine(hexValuesSplit.Length);for (int i = 0; i < hexValuesSplit.Length; i++){hexValues[i] = Convert.ToByte(hexValuesSplit[i], 16);}return hexValues;}//byte数组以16进制形式转字符串public static string ByteTo16Str(byte[] bytes){string recData = null;//创建接收数据的字符串foreach (byte outByte in bytes)//将字节数组以16进制形式遍历到一个字符串内 {recData += outByte.ToString("X2") + " ";}return recData;}//16进制字符串转换字符串public static string _16strToStr(string _16str){string outStr = null;byte[] streamByte = _16strToHex(_16str);outStr = Encoding.Default.GetString(streamByte);return outStr;}}}2 Form1.cs的代码为:using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.IO.Ports;using System.Linq;using System.Text;using System.Text.RegularExpressions;using System.Threading.Tasks;using System.Windows.Forms;using System.IO;using System.Collections;namespace串口助手sdd{public partial class Form1 : Form{//声明变量SerialPort sp = new SerialPort();bool isSetProperty = false;//串口属性设置标志位private enum PortState//声明接口显示状态,枚举型{打开,关闭}string path = AppDomain.CurrentDomain.BaseDirectory + "confing.ini";//声明配置文件路径string tbSendDataStr = "";//发送窗口字符串存储string tbSendData16 = "";//发送窗口16进制存储List<byte> receivedDatas = new List<byte>();//接收数据泛型数组//接收串口数据private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) {byte[] ReceivedData = new byte[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());elsetbReceivedData.Text =Encoding.Default.GetString(receivedDatas.ToArray());sp.DiscardInBuffer();//丢弃接收缓冲区数据}//发送串口数据private void DataSend(){try{if (cb16Send.Checked){byte[] hexBytes = Methods._16strToHex(tbSendData16);sp.Write(hexBytes, 0, hexBytes.Length);tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + hexBytes.Length).ToString();}else{sp.WriteLine(tbSendDataStr);tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + tbSendDataStr.Length).ToString();}}catch (Exception ex){MessageBox.Show(ex.Message.ToString());return;}}//设置串口属性private void SetPortProperty(){sp.PortName = cbxCOMPort.Text.Trim();//设置串口名sp.BaudRate = Convert.ToInt32(cbxBaudRate.Text.Trim());//设置波特率switch (cbxStopBits.Text.Trim())//设置停止位{case"1": sp.StopBits = StopBits.One; break;case"1.5": sp.StopBits = StopBits.OnePointFive; break;case"2": sp.StopBits = StopBits.Two; break;default: sp.StopBits = StopBits.None; break;}sp.DataBits = Convert.ToInt32(cbxDataBits.Text.Trim());//设置数据位switch (cbxParity.Text.Trim())//设置奇偶校验位{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 = 5000;//设置超时时间为5sControl.CheckForIllegalCrossThreadCalls = false;//这个类中我们不检查跨线程的调用是否合法(因为.net 2.0以后加强了安全机制,,不允许在winform中直接跨线程访问控件的属性)//定义DataReceived事件的委托,当串口收到数据后出发事件sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);}//设置端口显示状态private void DisplayPortState(PortState portState){toolStripStatusLabel1.Text = cbxCOMPort.Text + "端口处于" + portState + "状态 " + cbxBaudRate.Text + " " + cbxDataBits.Text + " " + cbxStopBits.Text + " " + cbxParity.Text;}//重新打开串口private void AgainOpenPort(){if (sp.IsOpen){try{sp.Close();SetPortProperty();isSetProperty = true;sp.Open();}catch (Exception){isSetProperty = false;btnOpenCom.Text = "打开串口";DisplayPortState(PortState.关闭);MessageBox.Show("串口无效或已被占用!", "错误提示");return;}DisplayPortState(PortState.打开);}else{DisplayPortState(PortState.关闭);}}public Form1(){InitializeComponent();}//软件启动时加载事件private void Form1_Load(object sender, EventArgs e){#region加载配置文件Hashtable ht = new Hashtable();if (File.Exists(path)){try{string myline = "";string[] str = new string[2];using (StreamReader sr = new StreamReader(path)) {myline = sr.ReadLine();while (myline != null){str = myline.Split('=');ht.Add(str[0], str[1]);myline = sr.ReadLine();}}}catch(Exception ex){MessageBox.Show(ex.Message.ToString());}}#endregion#region设置窗口为固定大小且不可最大化this.MaximumSize = this.Size;this.MinimumSize = this.Size;this.MaximizeBox = false;#endregion#region列出常用的波特率cbxBaudRate.Items.Add("1200");cbxBaudRate.Items.Add("2400");cbxBaudRate.Items.Add("4800");cbxBaudRate.Items.Add("9600");cbxBaudRate.Items.Add("19200");cbxBaudRate.Items.Add("38400");cbxBaudRate.Items.Add("43000");cbxBaudRate.Items.Add("56000");cbxBaudRate.Items.Add("57600");cbxBaudRate.Items.Add("115200");if (ht.ContainsKey("cbxBaudRate"))cbxBaudRate.SelectedIndex =cbxBaudRate.Items.IndexOf(ht["cbxBaudRate"].ToString());elsecbxBaudRate.SelectedIndex = 3;cbxBaudRate.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region列出停止位cbxStopBits.Items.Add("1");cbxStopBits.Items.Add("1.5");cbxStopBits.Items.Add("2");if (ht.ContainsKey("cbxStopBits"))cbxStopBits.SelectedIndex =cbxStopBits.Items.IndexOf(ht["cbxStopBits"].ToString());elsecbxStopBits.SelectedIndex = 0;cbxStopBits.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region列出数据位cbxDataBits.Items.Add("8");cbxDataBits.Items.Add("7");cbxDataBits.Items.Add("6");cbxDataBits.Items.Add("5");if (ht.ContainsKey("cbxDataBits"))cbxDataBits.SelectedIndex =cbxDataBits.Items.IndexOf(ht["cbxDataBits"].ToString());elsecbxDataBits.SelectedIndex = 0;cbxDataBits.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region列出奇偶校验位cbxParity.Items.Add("无");cbxParity.Items.Add("奇校验");cbxParity.Items.Add("偶校验");if (ht.ContainsKey("cbxParity"))cbxParity.SelectedIndex =cbxParity.Items.IndexOf(ht["cbxParity"].ToString());elsecbxParity.SelectedIndex = 0;cbxParity.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region COM口重新加载cbxCOMPort.Items.Clear();//清除当前串口号中的所有串口名称 cbxCOMPort.Items.AddRange(Methods.ActivePorts());if (ht.ContainsKey("cbxCOMPort") &&cbxCOMPort.Items.Contains(ht["cbxCOMPort"].ToString()))cbxCOMPort.SelectedIndex =cbxCOMPort.Items.IndexOf(ht["cbxCOMPort"].ToString());elsecbxCOMPort.SelectedIndex = 0;cbxCOMPort.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region初始化计数器tbSendCount.Text = "0";tbSendCount.ReadOnly = true;tbReceivedCount.Text = "0";tbReceivedCount.ReadOnly = true;#endregion#region初始化当前时间toolStripStatusLabel3.Text = DateTime.Now.ToString();#endregion#region初始化串口状态toolStripStatusLabel1.ForeColor = Color.Blue;if (!isSetProperty)//串口未设置则设置串口属性{SetPortProperty();isSetProperty = true;}try{sp.Open();btnOpenCom.Text = "关闭串口";DisplayPortState(PortState.打开);}catch (Exception){//串口打开失败后,串口属性设置标志位设为falseisSetProperty = false;MessageBox.Show("串口无效或已被占用!", "错误提示"); }#endregion#region初始化间隔时间if (ht.ContainsKey("tbSpaceTime"))tbSpaceTime.Text = ht["tbSpaceTime"].ToString();elsetbSpaceTime.Text = "1000";#endregion#region初始化按16进制显示状态if (ht.ContainsKey("cb16Display") && ht["cb16Display"].ToString() == "True") cb16Display.Checked = true;elsecb16Display.Checked = false;#endregion#region初始化按16进制发送状态if (ht.ContainsKey("cb16Send") && ht["cb16Send"].ToString() == "True")cb16Send.Checked = true;elsecb16Send.Checked = false;#endregion#region初始化发送区文本if(ht.ContainsKey("tbSendData16") && ht.ContainsKey("tbSendDataStr")){tbSendData16 = ht["tbSendData16"].ToString();tbSendDataStr = ht["tbSendDataStr"].ToString();if (cb16Send.Checked)tbSendData.Text = ht["tbSendData16"].ToString();elsetbSendData.Text = ht["tbSendDataStr"].ToString();}#endregiontbSendData.Focus();}//显示当前时间private void timer1_Tick(object sender, EventArgs e){toolStripStatusLabel3.Text = DateTime.Now.ToString();}//点击打开串口按钮private void btnOpenCom_Click(object sender, EventArgs e){if (!sp.IsOpen)//串口没有打开时{if (!isSetProperty)//串口未设置则设置串口属性{SetPortProperty();isSetProperty = true;}try{sp.Open();btnOpenCom.Text = "关闭串口";DisplayPortState(PortState.打开);}catch (Exception){//串口打开失败后,串口属性设置标志位设为falseisSetProperty = false;MessageBox.Show("串口无效或已被占用!", "错误提示"); }}else//串口已经打开{try{sp.Close();isSetProperty = false;btnOpenCom.Text = "打开串口";DisplayPortState(PortState.关闭);}catch (Exception){MessageBox.Show("关闭串口时发生错误", "错误提示"); }}}//发送串口数据private void btnSend_Click(object sender, EventArgs e){if (tbSendData.Text.Trim() == "")//检测发送数据是否为空{MessageBox.Show("请输入要发送的数据!", "错误提示");return;}if (sp.IsOpen){DataSend();}else{MessageBox.Show("串口未打开!", "错误提示");}}//点击端口号选择下拉框按钮private void cbxCOMPort_SelectedIndexChanged(object sender, EventArgs e){AgainOpenPort();}//点击波特率选择下拉框按钮private void cbxBaudRate_SelectedIndexChanged(object sender, EventArgs e) {AgainOpenPort();}//点击数据位选择下拉框按钮private void cbxDataBits_SelectedIndexChanged(object sender, EventArgs e) {AgainOpenPort();}//点击停止位选择下拉框按钮private void cbxStopBits_SelectedIndexChanged(object sender, EventArgs e) {AgainOpenPort();}//点击校验位选择下拉框按钮private void cbxParity_SelectedIndexChanged(object sender, EventArgs e){AgainOpenPort();}//点击数据接收区清空按钮private void btnClearReceived_Click(object sender, EventArgs e){receivedDatas.Clear();tbReceivedData.Text = "";}//点击是否按16进制显示接收数据private void cb16Display_CheckedChanged(object sender, EventArgs e){if (cb16Display.Checked)tbReceivedData.Text = Methods.ByteTo16Str(receivedDatas.ToArray());elsetbReceivedData.Text =Encoding.Default.GetString(receivedDatas.ToArray());//点击是否按16进制发送数据private void cb16Send_CheckedChanged(object sender, EventArgs e){if (cb16Send.Checked){tbSendData.Text = tbSendData16;}else{tbSendData.Text = tbSendDataStr;}}//发送文本框键盘按键检测private void tbSendData_KeyPress(object sender, KeyPressEventArgs e){if (cb16Send.Checked){//正则匹配string pattern = "[0-9a-fA-F]|\b";//\b:退格键Match m = Regex.Match(e.KeyChar.ToString(), pattern);if (m.Success){if(e.KeyChar != '\b'){if (tbSendData.Text.Length % 3 == 2){tbSendData.Text += " ";tbSendData.SelectionStart = tbSendData.Text.Length;}e.KeyChar = Convert.ToChar(e.KeyChar.ToString().ToUpper()); }e.Handled = false;}else{e.Handled = true;}}else{e.Handled = false;}}//点击清空发送内容private void btnClearSend_Click(object sender, EventArgs e){tbSendData.Text = "";if (cb16Send.Checked)tbSendData16 = "";elsetbSendDataStr = "";//点击清空计数器数据private void btnClearCount_Click(object sender, EventArgs e){tbReceivedCount.Text = "0";tbSendCount.Text = "0";}//点击是否设置自动发送private void cbAutomaticSend_CheckedChanged(object sender, EventArgs e) {if (cbAutomaticSend.Checked){timer2.Enabled = true;timer2.Interval = Convert.ToInt32(tbSpaceTime.Text);}else{timer2.Enabled = false;}}//自动发送时间文本框键盘按键检测private void tbSpaceTime_KeyPress(object sender, KeyPressEventArgs e) {//正则匹配string pattern = "[0-9]|\b";Match m = Regex.Match(e.KeyChar.ToString(),pattern);if (m.Success){timer2.Interval = Convert.ToInt32(tbSpaceTime.Text);e.Handled = false;}else{e.Handled = true;}}//串口显示状态private void timer2_Tick(object sender, EventArgs e){if (sp.IsOpen){DataSend();}else{timer2.Enabled = false;cbAutomaticSend.Checked = false;MessageBox.Show("串口未打开!", "错误提示");return;}if (tbSendData.Text.Trim() == "")//检测发送数据是否为空{timer2.Enabled = false;cbAutomaticSend.Checked = false;MessageBox.Show("请输入要发送的数据!", "错误提示");return;}}//关闭窗口时出发的事件private void Form1_FormClosed(object sender, FormClosedEventArgs e){try{using (StreamWriter sw = new StreamWriter(path, false)){sw.WriteLine("cbxCOMPort=" + cbxCOMPort.Text);sw.WriteLine("cbxBaudRate=" + cbxBaudRate.Text);sw.WriteLine("cbxDataBits=" + cbxDataBits.Text);sw.WriteLine("cbxStopBits=" + cbxStopBits.Text);sw.WriteLine("cbxParity=" + cbxParity.Text);sw.WriteLine("cb16Display="+ cb16Display.Checked.ToString()); sw.WriteLine("tbSpaceTime=" + tbSpaceTime.Text);sw.WriteLine("cb16Send=" + cb16Send.Checked.ToString());sw.WriteLine("tbSendDataStr=" + tbSendDataStr);sw.WriteLine("tbSendData16=" + tbSendData16);sp.Close();}}catch(Exception ex){MessageBox.Show(ex.Message.ToString());}}//发送文本框按键抬起时出发的事件private void tbSendData_KeyUp(object sender, KeyEventArgs e){if (cb16Send.Checked){tbSendData16 = tbSendData.Text.Trim();}else{tbSendDataStr = tbSendData.Text;}}//点击读入文件按钮private void btnReadFile_Click(object sender, EventArgs e){openFileDialog1.Filter = "所有文件(*.*)|*.*";//文件筛选器的设定openFileDialog1.FilterIndex = 1;openFileDialog1.Title = "选择文件";openFileDialog1.FileName = "";openFileDialog1.ShowHelp = true;if(openFileDialog1.ShowDialog() == DialogResult.OK){using (FileStream fs = newFileStream(openFileDialog1.FileName,FileMode.Open)){byte[] bufferByte = new byte[fs.Length];fs.Read(bufferByte, 0, Convert.ToInt32(fs.Length));sp.Write(bufferByte, 0, bufferByte.Length);tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + bufferByte.Length).ToString();}}}//点击保存数据按钮private void btnSaveFile_Click(object sender, EventArgs e){saveFileDialog1.Filter = "所有文件(*.*)|*.*";if(saveFileDialog1.ShowDialog() == DialogResult.OK){string fName = saveFileDialog1.FileName;using(FileStream fs = File.Open(fName, FileMode.Append)){fs.Write(receivedDatas.ToArray(), 0, receivedDatas.Count);}}}}}需要源代码或有疑问的c#爱好者们,欢迎加入c#技术交流群(33647125),附加信息为”我以下载此文档”,进群后找群主索要源代码或进行技术交流。

vc++_串口上位机编程实例 附vc串口通信(接收)

vc++_串口上位机编程实例  附vc串口通信(接收)

VC++串口上位机简单例程(源码及详细步骤)VC++编写简单串口上位机程序串口通信,MCU跟PC通信经常用到的一种通信方式,做界面、写上位机程序的编程语言、编译环境等不少,VB、C#、LABVIEW等等,我会的语言很少,C语言用得比较多,但是还没有找到如何用C语言来写串口通信上位机程序的资料,在图书管理找到了用VC++编写串口上位机的资料,参考书籍,用自己相当蹩脚的C++写出了一个简单的串口上位机程序,分享一下,体验一下单片机和PC通信的乐趣。

编译环境:VC++6.0操作系统:VMWare虚拟出来的Windows XP程序实现功能:1、PC初始化COM1口,使用n81方式,波特率57600与单片机通信。

PC的COM口编号可以通过如下方式修改:当然也可以通过上位机软件编写,通过按钮来选择COM端口号,但是此次仅仅是简单的例程,就没有弄那么复杂了。

COM1口可用的话,会提示串口初始化完毕。

否则会提示串口已经打开Port already open,表示串口已经打开,被占用了。

2、点击开始转换,串口会向单片机发送0xaa,单片机串口中断接收到0xaa后启动ADC 转换一次,并把转换结果ADCL、ADCH共两个字节的结果发送至PC,PC进行数值转换后在窗口里显示。

(见文章末尾图)3、为防止串口被一只占用,点击关闭串口可以关闭COM1,供其它程序使用,点击后按钮变为打开串口,点击可重新打开COM1。

程序的编写:1、打开VC++6.0建立基于对话框的MFC应用程序Test,2、在项目中插入MSComm控件:工程->增加到工程->Components and Controls->双击Registered ActiveX Controls->选择Microsoft Communications Control, version 6.0->Insert,按默认值添加,你会发现多了个电话图标,这是增加后串口通信控件。

c#上位机与三菱PLC(FX3U)串口通讯

c#上位机与三菱PLC(FX3U)串口通讯

c#上位机与三菱PLC(FX3U)串⼝通讯项⽬中会经常⽤到上位机与PLC之间的串⼝通信,本⽂介绍⼀下C#如何编写上位机代码与三菱FX3U进⾏通讯1. 第⼀种⽅法是⾃⼰写代码实现,主要代码如下://对PLC的Y7进⾏置1byte[] Y007_ON = { 0x02, 0x37, 0x30, 0x37, 0x30, 0x35, 0x03, 0x30, 0x36 };//选择串⼝参数SerialPort sp = new SerialPort("COM5", 9600, Parity.Even, 7);//打开串⼝sp.Open();//写⼊数据sp.Write(Y007_ON, 0, Y007_ON.Length);//关闭串⼝sp.Close(); 该⽅法的缺点在于我们⾸先要熟悉三菱PLC的通讯协议,然后根据通信规程来编写通信代码 举例说就是要对三菱PLC的Y007⼝进⾏操作,我们需要知道要对三菱PLC发送什么参数,这 ⾥可以参考百度⽂库的⼀篇⽂章: https:///view/157632dad05abe23482fb4daa58da0116c171fa8.html2.使⽤MX COMPONENT软件 2.1 MX Component 是⼀个⼯具,通过使⽤该⼯具,可以在⽆需具备通信协议及模块知 识的状况下实现从计算机⾄三菱PLC的通信。

MX Component的安装使⽤教程⽹上有很多,顺便找⼀下就可以找到合适的,这样 要说明的是MX Component⼯具,使⽤⼿册和编程⼿册都可以在三菱的⽹站上下载。

⼯具下载: https:///fa/zh/download/dwn_idx_softwareDetail.asp?sid=45 ⼿册下载: https:///fa/zh/download/dwn_idx_manual.asp 下载安装之后sample路径(win10,默认安装):C:\MELSEC\Act\Samples 2.2 介绍安装配置好MX Component之后C#使⽤ActUtlType控件进⾏串⼝通信 ⾸先要引⽤,这两个DLL在例程中可以找到//Logical Station Number的值和在MX Component中设置⼀样int logicalStationNumber = 0;//添加axActUtlType对象AxActUtlTypeLib.AxActUtlType axActUtlType = new AxActUtlTypeLib.AxActUtlType();//不加这三句会报//引发类型为“System.Windows.Forms.AxHost+InvalidActiveXStateException”的异常((ponentModel.ISupportInitialize)(axActUtlType)).BeginInit();this.Controls.Add(axActUtlType);((ponentModel.ISupportInitialize)(axActUtlType)).EndInit();//openaxActUtlType.ActLogicalStationNumber = logicalStationNumber;axActUtlType.ActPassword = "";axActUtlType.Open();//Y7写⼊1int wirteData = 1;axActUtlType.WriteDeviceRandom("Y7", 1, ref wirteData);//D0写⼊100int wirteData1 = 100;axActUtlType.WriteDeviceRandom("D0", 1, ref wirteData1);//读D0数据int readData;axActUtlType.ReadDeviceRandom("D0", 1, ref readData);//closeaxActUtlType.Close(); 这⾥只是简单介绍,更深⼊的内容还是去看编程⼿册和例程。

VC实现串口通信项目源码

VC实现串口通信项目源码

VC实现串口通信项目源码以下是一个基于VC++实现串口通信的简单项目源码:```#include <windows.h>#include <iostream>using namespace std;//串口通信类class SerialPortprivate:HANDLE hSerial; // 串口句柄public:SerialPorhSerial = NULL;}bool openPort(const char* portName)//打开串口hSerial = CreateFileA(portName,GENERIC_READ,GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);if (hSerial == INVALID_HANDLE_VALUE)cerr << "Failed to open serial port!" << endl;return false;}//配置串口参数DCB dcbSerialParams = { 0 };dcbSerialParams.DCBlength = sizeof(dcbSerialParams);cerr << "Failed to get serial parameters!" << endl; CloseHandle(hSerial);return false;}dcbSerialParams.BaudRate = CBR_9600; // 波特率设置为9600 dcbSerialParams.ByteSize = 8; // 数据位设置为8 dcbSerialParams.StopBits = ONESTOPBIT; // 停止位设置为1 dcbSerialParams.Parity = NOPARITY; // 校验位设置为无cerr << "Failed to set serial parameters!" << endl; CloseHandle(hSerial);return false;}//设置读写超时时间CloseHandle(hSerial);return false;}return true;}bool closePor//关闭串口if (hSerial != NULL && hSerial != INVALID_HANDLE_VALUE) CloseHandle(hSerial);hSerial = NULL;return true;}return false;}bool writeData(const char* data, int dataSize)//向串口写数据DWORD bytesWritten;if (!WriteFile(hSerial, data, dataSize, &bytesWritten, NULL)) cerr << "Failed to write data!" << endl;return false;}if (bytesWritten != dataSize)cerr << "Failed to write all data!" << endl;return false;}return true;}bool readData(char* buffer, int bufferSize)//从串口读数据DWORD bytesRead;if (!ReadFile(hSerial, buffer, bufferSize, &bytesRead, NULL)) cerr << "Failed to read data!" << endl;return false;return true;}};int maiSerialPort serialPort;//打开串口if (!serialPort.openPort("COM1"))return 1;}//从用户输入获取数据char sendBuffer[256];cout << "Enter data to send: ";cin.getline(sendBuffer, sizeof(sendBuffer));//发送数据至串口if (!serialPort.writeData(sendBuffer, strlen(sendBuffer) + 1))serialPort.closePort(;return 1;//从串口接收数据char recvBuffer[256];if (!serialPort.readData(recvBuffer, sizeof(recvBuffer)))serialPort.closePort(;return 1;}//输出接收到的数据cout << "Received data: " << recvBuffer << endl;//关闭串口serialPort.closePort(;return 0;```这个项目实现了一个简单的串口通信程序,通过命令行交互,用户可以输入要发送的数据,程序将数据发送到串口,然后从串口接收并打印接收到的数据。

c语言怎么写串口通信编程

c语言怎么写串口通信编程

c语言怎么写串口通信编程串口通信是一种广泛应用于嵌入式系统和电子设备之间的通信方式。

无论是嵌入式开发还是电子设备控制,串口通信都是常见的需求。

在C语言中,实现串口通信需要通过操作串口的硬件寄存器和使用相应的通信协议来实现数据的发送和接收。

本文将一步一步介绍如何使用C语言编写串口通信程序。

第一步:打开串口要开始串口通信,首先需要打开串口。

在C语言中,可以使用文件操作函数来打开串口设备。

通常,串口设备被命名为/dev/ttyS0,/dev/ttyS1等,具体名称取决于系统。

下面是一个打开串口设备的示例代码:cinclude <stdio.h>include <fcntl.h>include <termios.h>int open_serial_port(const char *port) {int fd = open(port, O_RDWR O_NOCTTYO_NDELAY);if (fd == -1) {perror("open_serial_port");return -1;}设置串口属性struct termios options;tcgetattr(fd, &options);cfmakeraw(&options);cfsetspeed(&options, B9600);tcsetattr(fd, TCSANOW, &options);return fd;}int main() {const char *port = "/dev/ttyS0";int fd = open_serial_port(port);if (fd == -1) {打开串口失败,处理错误return -1;}串口已打开,可以进行数据的读写操作return 0;}在上面的代码中,open_serial_port函数用于打开指定的串口设备并进行一些必要的设置。

C语言串口通信助手代码

C语言串口通信助手代码

该程序全部由C写成没有C++更没用MFC完全是自娱自乐给需要的人一个参考#include "stdafx.h"#include <windowsx.h>#include "resource.h"#include "MainDlg.h"#include <windows.h>#include <stdio.h>#include <stdlib.h>HANDLE hComm;/用于获取串口打开函数的返回值(句柄或错误值) OVERLAPPED m_ov;COMSTAT comstat;DWORD m_dwCommEvents;TCHAR cRecs[200],cSends[100]; 接//收字符串发送字符串char j=0,*cCom; //接收用统计数据大小变量端口选择BOOL WINAPI Main_Proc(HWND hWnd, UINT uMsg, WPARAM wParam,LPARAM lParam){switch(uMsg){HANDLE_MSG(hWnd, WM_INITDIALOG, Main_OnInitDialog);HANDLE_MSG(hWnd, WM_COMMAND, Main_OnCommand);HANDLE_MSG(hWnd,WM_CLOSE, Main_OnClose);}return FALSE;}/* 系统初始化函数*/BOOL Main_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAMlParam){HWND hwndCombo1=GetDlgItem(hwnd,IDC_COMBO1);ComboBox_InsertString(hwndCombo1,-1,TEXT("COM1"));ComboBox_InsertString(hwndCombo1,-1,TEXT("COM2"));ComboBox_InsertString(hwndCombo1,-1,TEXT("COM3"));ComboBox_InsertString(hwndCombo1,-1,TEXT("COM4"));ComboBox_InsertString(hwndCombo1,-1,TEXT("COM5"));ComboBox_SetCurSel(hwndCombo1,0);void CALLBACK TimerProc (HWND hwnd, UINT message, UINT iTimerID,DWORD dwTime);SetTimer(hwnd,1,1000,TimerProc);return TRUE;}/* 监视串口错误时使用的函数*/boolProcessErrorMessage(char* ErrorText)char *Temp = new char[200];LPVOID lpMsgBuf;FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |FORMAT_MESSAGE_FROM_SYSTEM,NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Defaultlanguage(LPTSTR) &lpMsgBuf,0,NULL);sprintf(Temp, "WARNING: %s Failed with the following error:\n%s\nPort: %d\n", (char*)ErrorText, lpMsgBuf, "com2");MessageBox(NULL, Temp, "Application Error", MB_ICONSTOP);LocalFree(lpMsgBuf);delete[] Temp;return true;}boolopenport(char *portname)// 打开串口{hComm = CreateFile(portname, //串口号“ comT “ cc调用方法:bool open;open=openport("com2");GENERIC_READ | GENERIC_WRIT允许读写0, //通讯设备必须以独占方式打开0, // 无安全属性OPEN_EXISTING,通讯设备已存在FILE_FLAG_OVERLAPPED异步I/O0); //通讯设备不能用模板打开if (hComm == INVALID_HANDLE_VALUE如/果被占用或是没有打开时返回的是这个错误代码{CloseHandle(hComm);return FALSE;}elsereturn true;}boolsetupdcb(intrate_arg)// 设置port 的属性{DCB dcb;int rate= rate_arg;memset(&dcb,0,sizeof(dcb));if(!GetCommState(hComm,&dcb))〃获取当前DCB配置return FALSE;// set DCB to configure the serial portdcb.DCBlength = sizeof(dcb);dcb.BaudRate = rate;dcb.Parity = NOPARITY; 奇// 偶校验值0~4分别对应无校验、奇校验、偶校验、校验置位、校验清零dcb.fParity = 0; //为1的话激活奇偶校验检查dcb.StopBits = ONESTOPBIT停止位个数,0~2分别对应1位、1.5位、2位停止位dcb.ByteSize = 8; //数据位数dcb.fOutxCtsFlow = 0;dcb.fOutxDsrFlow = 0;dcb.fDtrControl = DTR_CONTROL_DISABLE;dcb.fDsrSensitivity = 0;dcb.fRtsControl = RTS_CONTROL_DISABLE;dcb.fOutX = 0;dcb.fInX = 0;dcb.fErrorChar = 0;dcb.fBinary = 1;dcb.fNull = 0;dcb.fAbortOnError = 0;dcb.wReserved = 0;dcb.XonLim = 2;dcb.XoffLim = 4;dcb.XonChar = 0x13;dcb.XoffChar = 0x19;dcb.EvtChar = 0;// set DCBif(!SetCommState(hComm,&dcb))return false;elsereturn true;}/* 串口读取相关时间设置*/boolsetuptimeout(DWORDReadInterval,DWORDReadTotalMultiplier,DWORDReadTotalconstant,DWORDW riteTotalMultiplier,DWORDWriteTotalconstant){COMMTIMEOUTS timeouts;timeouts.ReadIntervalTimeout=ReadInterval; // 读取两个字节间隔最大值mS 如超过立即返回不再读取timeouts.ReadTotalTimeoutConstant=ReadTotalconstant; //如果同下面一个都为0 则无论是否读到数据都返回// 可以毫秒为单位指定一个乘数,该乘数用来计算读操作的总限时时间timeouts.ReadTotalTimeoutMultiplier=ReadTotalMultiplier; // 以毫秒为单位指定一个常数,用于计算读操作的总限时时间0 表示不限时timeouts.WriteTotalTimeoutConstant=WriteTotalconstant;// 写操作延时同上timeouts.WriteTotalTimeoutMultiplier=WriteTotalMultiplier;if(!SetCommTimeouts(hComm, &timeouts))return false;elsereturn true;}intClearn() // 清除buff 中的内容并返回buff 中现有数据量的大小并读取错误原因{DWORD dwError = 0;DWORD BytesRead = 0;ClearCommError(hComm, &dwError, &comstat);return comstat.cbInQue; // 返回buff 中数据量}/* 串口数据接收读取函数*/void ReceiveChar(){BOOL bRead = TRUE;BOOL bResult = TRUE;DWORD dwError = 0;DWORD BytesRead = 0;char i=0,n;char RXBuff;j=0;while (i-n){n=i;Sleep(10);bResult = ClearCommError(hComm, &dwError, &comstat); i=(char)comstat.cbInQue;}for (;i>0;i--)if (bRead)bResult = ReadFile(hComm, // Handle to COMM port &RXBuff, // RX Buffer Pointer1, // Read one byte&BytesRead, // Stores number of bytes read&m_ov); // pointer to the m_ov structure// printf("%c",RXBuff);cRecs[j++]=(char)RXBuff;if (!bResult){switch (dwError = GetLastError()){case ERROR_IO_PENDING:{bRead = FALSE;break;}default: break;}}elsebRead = TRUE; // close if (bRead)if (!bRead)bRead = TRUE;bResult = GetOverlappedResult(hComm, // Handle to COMM port&m_ov, // Overlapped structure&BytesRead, // Stores number of bytes readTRUE); // Wait flag}}}boolWriteChar(char* m_szWriteBuffer,DWORDm_nToSend) //写字符的函数{BOOL bWrite = TRUE;BOOL bResult = TRUE;DWORD BytesSent = 0;HANDLE m_hWriteEvent;ResetEvent(m_hWriteEvent);if (bWrite){m_ov.Offset = 0;m_ov.OffsetHigh = 0;// Clear bufferbResult = WriteFile(hComm, // Handle to COMM Portm_szWriteBuffer, // Pointer to message buffer in calling finctionm_nToSend, // Length of message to send&BytesSent, // Where to store the number of bytes sent&m_ov ); // Overlapped structureif (!bResult)DWORD dwError = GetLastError();switch (dwError){case ERROR_IO_PENDING:{// continue to GetOverlappedResults()BytesSent = 0;bWrite = FALSE;break;}default:// all other error codesbreak;}}} // end if(bWrite)if (!bWrite){bWrite = TRUE;bResult = GetOverlappedResult(hComm, // Handle to COMM port&m_ov, // Overlapped structure&BytesSent, // Stores number of bytes sentTRUE); // Wait flag// deal with the error codeif (!bResult){printf("GetOverlappedResults() in WriteFile()");}} // end if (!bWrite)// Verify that the data size send equals what we tried to sendif (BytesSent != m_nToSend){printf("WARNING: WriteFile() error.. Bytes Sent: %d; MessageLength: %d\n", BytesSent, strlen((char*)m_szWriteBuffer));}return true;}/*window 时间函数回调*/void CALLBACK TimerProc (HWND hwnd, UINT message, UINT iTimerID,DWORD dwTime){SYSTEMTIME time; /定/ 义机构体变量timeGetLocalTime(&time); // 取系统时间以指针方式TCHAR strTime[256]; //程序只有一个作用wsprintf(strTime,"%04d-%02d-%02d %02d:%02d:%02d",time.wYear, /就/ 是读取系统时间time.wMonth,time.wDay,time.wHour,time.wMinute,time.wSecond);// 然后写进strTimeSetDlgItemText(hwnd,IDC_TIME,strTime); /这/ 个字符串}void Main_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINTcodeNotify) {switch(id){case IDC_SEND:{GetDlgItemText (hwnd,IDC_EDIT2,cSends,sizeof(cSends));un sig ned n二sizeof(cSe nds); 〃n是通知串口将发送字节的长度char send[100];wsprintf (send,"%s",cSends);WriteChar(send,n-1);SetCommMask(hComm, EV_RXCHAR)监视串口是否接收有数据ReceiveChar(); /读取串口sbuff 中数据cRecs[j]='\0'; // 将cRecs转为字符串SetDlgItemText(hwnd,IDC_EDIT1,cRecs);} break;/*case IDC_RECEIVE暂时未用采用直接显示的方式{}break;*/case IDC_CHECK:{intctr;HWND hwndCombo1=GetDlgItem(hwnd,IDC_COMBO1);ctr = ComboBox_GetCurSel(hwndCombo1);switch (ctr){case 0:cCom="com1";break;case 1:cCom="com2";break;case 2:cCom="com3";break;case 3:cCom="com4";break;case 4:cCom="com5";break;default: cCom="com1";break;}if (openport(cCom))Ko t pu/v\q)6o|8!apu3}(pu/v\u aNMH)eso|9UO_uie|/\| p|OA{{ 制eaiq4ine)ep91 / 91{X丄doavxi_39dnd I 丄doavxd_39dndI dV^IOXl^Odnd I dV319Xd_39dnd l ujuj09M)ujuj09e6jndK.. iWWMB ^^lia^-QarpuMM^xe 丄UJ 引Qimes esp K.. 宙17丄ICH—OCirpu/v\U)1xe丄UJ引Qimes0096 重畀徹刑圜口宙刑畀似 //((000 i1021010>20 Oinoeujudrnes^(o096)qopdrnes)j!K H IIV Z I./C丄ICH—OCirpu/v\U)!xe 丄UJ 引Qimes esp{ KO1...?., i ^..t PUMM)xoae6esse|A|■Ci >10.?£丄ICH—OCIlTu/v\Mxe丄ujeWimes }。

vc串口通信编程详解

vc串口通信编程详解

vc串口通信编程详解
串口通信简介
串行接口是一种可以将接受来自CPU的并行数据字符转换为连续的串行数据流发送出去,同时可将接受的串行数据流转换为并行的数据字符供给CPU的器件。

一般完成这种功能的电路,我们称为串行接口电路。

串口通信结构
串口通信是指外设和计算机间,通过数据信号线、地线、控制线等,按位进行传输数据的一种通讯方式。

这种通信方式使用的数据线少,在远距离通信中可以节约通信成本,但其传输速度比并行传输低。

串口是计算机上一种非常通用的设备通信协议。

大多数计算机(不包括笔记本电脑)包含两个基于RS-232的串口。

串口同时也是仪器仪表设备通用的通信协议;很多GPIB兼容的设备也带有RS-232口。

同时,串口通信协议也可以用于获取远程采集设备的数据。

RS-232(ANSI/EIA-232标准)是IBM-PC及其兼容机上的串行连接标准。

可用于许多用途,比如连接鼠标、打印机或者Modem,同时也可以接。

Comassistant串口助手详解和源代码分析

Comassistant串口助手详解和源代码分析

到目前为止还不能在接收编辑框中看到数据,因为我们还没有打开串口,但运行程序不应该有任何错误, 不然,你肯定哪儿没看仔细,因为我是打开 VC6 对照着做一步写一行的,运行试试。没错吧?那么做下一 步: 6.打开串口和设置串口参数 码: // TODO: Add extra initialization here if(m_ctrlComm.GetPortOpen()) m_ctrlComm.SetPortOpen(FALSE); m_ctrlComm.SetCommPort(1); //选择 com1 if( !m_ctrlComm.GetPortOpen()) m_ctrlComm.SetPortOpen(TRUE);//打开串口 else AfxMessageBox("cannot open serial port"); m_ctrlComm.SetSettings("9600,n,8,1"); //波特率 9600,无校验,8 个数据位,1 个停止位 m_ctrlComm.SetInputModel(1); //1:表示以二进制方式检取数据 m_ctrlComm.SetRThreshold(1); //参数 1 表示每当串口接收缓冲区中有多于或等于 1 个字符时将引发一个接收数据的 OnComm 事件 m_ctrlComm.SetInputLen(0); //设置当前接收区数据长度为 0 m_ctrlComm.GetInput();//先预读缓冲区以清除残留数据 现在你可以试试程序了,将串口线接好后(不会接?去看看我写的串口接线基本方法),打开串口调试助 手,并将串口设在 com2,选上自动发送,也可以等会手动发送。再执行你编写的程序,接收框里应该有数 据显示了。 7.发送数据 先为发送按钮添加一个单击消息即 BN_CLICKED 处理函数,打开 ClassWizard->Message 你可以在你需要的时候打开串口, 例如在程序中做一个开始按钮, 在该按钮

c语言串口通信,协议解析写法

c语言串口通信,协议解析写法

c语言串口通信,协议解析写法在C语言中,串口通信通常使用串口库函数进行操作。

常用的串口库函数包括:`open()`: 打开串口设备文件`close()`: 关闭串口设备文件`read()`: 从串口读取数据`write()`: 向串口写入数据`ioctl()`: 对串口进行控制操作在进行串口通信时,需要定义通信协议,包括数据包的格式、数据包的发送和接收方式等。

下面是一个简单的示例,演示如何使用C语言进行串口通信并解析协议:```cinclude <>include <>include <>include <>include <>include <>define SERIAL_PORT "/dev/ttyUSB0" // 串口设备文件路径define BAUD_RATE B9600 // 波特率define PACKET_SIZE 1024 // 数据包大小int main() {int fd; // 串口设备文件描述符struct termios options; // 串口选项结构体char buffer[PACKET_SIZE]; // 数据包缓冲区int bytes_read; // 读取的字节数// 打开串口设备文件fd = open(SERIAL_PORT, O_RDWR O_NOCTTY O_NDELAY); if (fd == -1) {perror("open");exit(1);}// 配置串口选项tcgetattr(fd, &options);cfsetispeed(&options, BAUD_RATE);cfsetospeed(&options, BAUD_RATE);_cflag = (CLOCAL CREAD);_cflag &= ~PARENB; // 无奇偶校验位_cflag &= ~CSTOPB; // 一个停止位_cflag &= ~CSIZE; // 清空数据位掩码_cflag = CS8; // 设置数据位为8位_lflag &= ~(ICANON ECHO ECHOE ISIG); // 非规范模式,禁用回显和中断信号_iflag &= ~(IXON IXOFF IXANY); // 禁用软件流控制_oflag &= ~OPOST; // 不处理输出处理_cc[VMIN] = 1; // 读取至少一个字符_cc[VTIME] = 0; // 不超时tcsetattr(fd, TCSANOW, &options);// 从串口读取数据并解析协议while (1) {bytes_read = read(fd, buffer, PACKET_SIZE);if (bytes_read < 1) {perror("read");exit(1);}// 在这里添加协议解析代码,例如判断数据包的开头和结尾,提取有效数据等。

上位机和下位机通讯代码

上位机和下位机通讯代码

#include <reg51.h>#include <string.h>#define led P1unsigned char RX_FLAG;unsigned char TX_FLAG;unsigned char j=0;//j=0;unsigned char ch[30];unsigned char dda[13];//串口接收中断函数void serial () interrupt 4 using 3{unsigned char chh;if(RI) //接收中断{EA=0;if(TX_FLAG==0){chh=SBUF;if(chh == 0xCC){RX_FLAG = 1;}if(chh == 0xFF){TX_FLAG=1;}}else{led =ch[28];ch[j]=SBUF;j++;if(j==30){j=0;TX_FLAG=0;}dda[0]=ch[1]*256+ch[0]; //整形dda[1]=ch[3]*256+ch[2];dda[2]=ch[5]*256+ch[4];dda[3]=ch[7]*256+ch[6];dda[4]=ch[9]*256+ch[8];dda[5]=ch[10]; //字符dda[6]=ch[11];dda[7]=ch[12];dda[8]=ch[13];dda[9]=(ch[17]*256+ch[16])+(ch[15]*256+ch[14])/1000; //浮点dda[10]=(ch[21]*256+ch[20])+(ch[19]*256+ch[18])/1000;dda[11]=(ch[25]*256+ch[24])+(ch[23]*256+ch[22])/1000;dda[12]=(ch[29]*256+ch[28])+(ch[27]*256+ch[26])/1000;}EA=1;RI=0; //清除接收中断标志位}}void init_serialcomm(void){SCON = 0x50; //SCON: 串口工作方式1,允许接收TMOD |= 0x20; //TMOD: 定时器1的工作方式2PCON |= 0x80; //SMOD=1;TH1 = 0xF4; //Baud:4800 fosc=11.0592MHzIE |= 0x90; //开总中断,开串口中断TR1 = 1; // 开启定时器1}//延时函数void delay (void){unsigned int i;for(i=0;i<5000;i++);}//向串口发送一个字符void send_char_com(unsigned char ch){SBUF=ch;while(TI==0);TI=0;}void send_int_com(unsigned int zhengshu) //发送整型,2字节数{unsigned char gaowei,diwei;diwei=(char) (zhengshu&0xFF);gaowei=(char) (zhengshu>>8);SBUF=diwei;delay();SBUF=gaowei;while(TI==0);TI=0;}void send_float_com( float xiaoshu) //发送浮点,4字节数{unsigned int zz,xx;zz= (int) xiaoshu;xx=(int) ((xiaoshu-zz)*1000);send_int_com(xx);delay();send_int_com(zz);}void main(){init_serialcomm(); //初始化串口while(1){if(RX_FLAG == 1){EA = 0 ; //修正BUG,关闭总中断send_char_com (0xCC);delay();send_int_com(512);delay();send_int_com(1024);delay();send_int_com(j);delay();send_int_com(dda[2]);delay();send_char_com(15);delay();send_char_com(99);delay();send_char_com(128);delay();send_float_com(15.123);delay();send_float_com(22.193);delay();send_float_com(99.886);delay();}EA = 1 ; //打开总中断RX_FLAG = 0;}}。

上位机串口通信python

上位机串口通信python

上位机串口通信python在 Python 中,你可以使用`serial`模块来进行上位机与串口设备之间的通信。

下面是一个简单的示例代码,演示了如何使用`serial`模块发送数据到串口以及从串口接收数据:```pythonimport serial# 打开串口设备,根据实际情况更改端口号和波特率port = 'COM1'baudrate = 9600ser = serial.Serial(port, baudrate)# 发送数据到串口data_to_send = 'Hello,串口!'ser.write(data_to_send.encode())# 从串口接收数据data_received = ser.read().decode()print('接收到的数据:', data_received)# 关闭串口ser.close()```在上述示例中,首先定义了要使用的串口端口号和波特率。

然后使用`serial.Serial()`函数打开串口设备。

接下来,使用`ser.write()`函数发送数据到串口。

发送的数据必须是字节类型,因此如果要发送字符串,需要先使用`encode()`方法将其转换为字节。

然后,使用`ser.read()`函数从串口接收数据。

接收到的数据将以字节类型返回,因此需要使用`decode()`方法将其转换为字符串。

最后,使用`ser.close()`函数关闭串口设备。

请注意,在实际应用中,你可能需要处理串口通信的错误,设置串口的超时等。

你还可以根据需要使用`serial`模块提供的其他功能,例如设置串口的奇偶校验、数据位数等。

希望这个示例对你有所帮助。

如果你有任何进一步的问题,请随时提问。

c#上位机串口通信助手源代码详解

c#上位机串口通信助手源代码详解

c#上位机串口通信助手源代码实例详解一、功能1软件打开时,自动检测有效COM端口2 软件打开时,自动复原到上次关闭时的状态3 不必关闭串口,即可直接进行更改初始化设置内容(串口号、波特率、数据位、停止位、校验位),可按更改后的信息自动将串口重新打开4 可统计接收字节和发送字节的个数5 接收数据可按16进制数据和非16进制数据进行整体转换6 可将接收到数据进行保存7 可设置自动发送,发送时间可进行实时更改8可按字符串、16进制字节、文件方式进行发送,字符串和16进制字节可分别进行存储,内容互不干扰9 按16进制发送时,可自动校验格式,不会输错10 可清空发送或接收区域的数据二、使用工具Visual Studio2015三、程序详解1 界面创建图1用winform创建如图1所示界面,控件名字分别为:端口号:cbxCOMPort 波特率:cbxBaudRate数据位:cbxDataBits 停止位:cbxStopBits校验位:label5 打开串口按钮:btnOpenCom发送(byte):tbSendCount 接收(byte):tbReceivedCount 清空计数按钮:btnClearCount 按16进制显示:cb16Display接收区清空内容按钮:btnClearReceived 保存数据按钮:btnSaveFile接收数据框:tbReceivedData 发送数据框:tbSendData自动发送:cbAutomaticSend 间隔时间:tbSpaceTime按16进制发送:cb16Send 发送区清空内容按钮:btnClearSend 读入文件按钮:btnReadFile 发送按钮:btnSend2 创建一个方法类按Ctrl+shift+A快捷键创建一个类,名字叫Methods,代码为:using System;using System.Collections;using System.Collections.Generic;using System.IO.Ports;using System.Linq;using System.Text;using System.Threading.Tasks;namespace串口助手sdd{class Methods{//获取有效的COM口public static string[] ActivePorts(){ArrayList activePorts = new ArrayList();foreach (string pname in SerialPort.GetPortNames()){activePorts.Add(Convert.ToInt32(pname.Substring(3)));}activePorts.Sort();string[] mystr = new string[activePorts.Count];int i = 0;foreach (int num in activePorts){mystr[i++] = "COM" + num.ToString();}return mystr;}//16进制字符串转换为byte字符数组public static Byte[] _16strToHex(string strValues){string[] hexValuesSplit = strValues.Split(' ');Byte[] hexValues = new Byte[hexValuesSplit.Length];Console.WriteLine(hexValuesSplit.Length);for (int i = 0; i < hexValuesSplit.Length; i++){hexValues[i] = Convert.ToByte(hexValuesSplit[i], 16);}return hexValues;}//byte数组以16进制形式转字符串public static string ByteTo16Str(byte[] bytes){string recData = null;//创建接收数据的字符串foreach (byte outByte in bytes)//将字节数组以16进制形式遍历到一个字符串内 {recData += outByte.ToString("X2") + " ";}return recData;}//16进制字符串转换字符串public static string _16strToStr(string _16str){string outStr = null;byte[] streamByte = _16strToHex(_16str);outStr = Encoding.Default.GetString(streamByte);return outStr;}}}2 Form1.cs的代码为:using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.IO.Ports;using System.Linq;using System.Text;using System.Text.RegularExpressions;using System.Threading.Tasks;using System.Windows.Forms;using System.IO;using System.Collections;namespace串口助手sdd{public partial class Form1 : Form{//声明变量SerialPort sp = new SerialPort();bool isSetProperty = false;//串口属性设置标志位private enum PortState//声明接口显示状态,枚举型{打开,关闭}string path = AppDomain.CurrentDomain.BaseDirectory + "confing.ini";//声明配置文件路径string tbSendDataStr = "";//发送窗口字符串存储string tbSendData16 = "";//发送窗口16进制存储List<byte> receivedDatas = new List<byte>();//接收数据泛型数组//接收串口数据private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) {byte[] ReceivedData = new byte[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());elsetbReceivedData.Text =Encoding.Default.GetString(receivedDatas.ToArray());sp.DiscardInBuffer();//丢弃接收缓冲区数据}//发送串口数据private void DataSend(){try{if (cb16Send.Checked){byte[] hexBytes = Methods._16strToHex(tbSendData16);sp.Write(hexBytes, 0, hexBytes.Length);tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + hexBytes.Length).ToString();}else{sp.WriteLine(tbSendDataStr);tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + tbSendDataStr.Length).ToString();}}catch (Exception ex){MessageBox.Show(ex.Message.ToString());return;}}//设置串口属性private void SetPortProperty(){sp.PortName = cbxCOMPort.Text.Trim();//设置串口名sp.BaudRate = Convert.ToInt32(cbxBaudRate.Text.Trim());//设置波特率switch (cbxStopBits.Text.Trim())//设置停止位{case"1": sp.StopBits = StopBits.One; break;case"1.5": sp.StopBits = StopBits.OnePointFive; break;case"2": sp.StopBits = StopBits.Two; break;default: sp.StopBits = StopBits.None; break;}sp.DataBits = Convert.ToInt32(cbxDataBits.Text.Trim());//设置数据位switch (cbxParity.Text.Trim())//设置奇偶校验位{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 = 5000;//设置超时时间为5sControl.CheckForIllegalCrossThreadCalls = false;//这个类中我们不检查跨线程的调用是否合法(因为.net 2.0以后加强了安全机制,,不允许在winform中直接跨线程访问控件的属性)//定义DataReceived事件的委托,当串口收到数据后出发事件sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);}//设置端口显示状态private void DisplayPortState(PortState portState){toolStripStatusLabel1.Text = cbxCOMPort.Text + "端口处于" + portState + "状态 " + cbxBaudRate.Text + " " + cbxDataBits.Text + " " + cbxStopBits.Text + " " + cbxParity.Text;}//重新打开串口private void AgainOpenPort(){if (sp.IsOpen){try{sp.Close();SetPortProperty();isSetProperty = true;sp.Open();}catch (Exception){isSetProperty = false;btnOpenCom.Text = "打开串口";DisplayPortState(PortState.关闭);MessageBox.Show("串口无效或已被占用!", "错误提示");return;}DisplayPortState(PortState.打开);}else{DisplayPortState(PortState.关闭);}}public Form1(){InitializeComponent();}//软件启动时加载事件private void Form1_Load(object sender, EventArgs e){#region加载配置文件Hashtable ht = new Hashtable();if (File.Exists(path)){try{string myline = "";string[] str = new string[2];using (StreamReader sr = new StreamReader(path)) {myline = sr.ReadLine();while (myline != null){str = myline.Split('=');ht.Add(str[0], str[1]);myline = sr.ReadLine();}}}catch(Exception ex){MessageBox.Show(ex.Message.ToString());}}#endregion#region设置窗口为固定大小且不可最大化this.MaximumSize = this.Size;this.MinimumSize = this.Size;this.MaximizeBox = false;#endregion#region列出常用的波特率cbxBaudRate.Items.Add("1200");cbxBaudRate.Items.Add("2400");cbxBaudRate.Items.Add("4800");cbxBaudRate.Items.Add("9600");cbxBaudRate.Items.Add("19200");cbxBaudRate.Items.Add("38400");cbxBaudRate.Items.Add("43000");cbxBaudRate.Items.Add("56000");cbxBaudRate.Items.Add("57600");cbxBaudRate.Items.Add("115200");if (ht.ContainsKey("cbxBaudRate"))cbxBaudRate.SelectedIndex =cbxBaudRate.Items.IndexOf(ht["cbxBaudRate"].ToString());elsecbxBaudRate.SelectedIndex = 3;cbxBaudRate.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region列出停止位cbxStopBits.Items.Add("1");cbxStopBits.Items.Add("1.5");cbxStopBits.Items.Add("2");if (ht.ContainsKey("cbxStopBits"))cbxStopBits.SelectedIndex =cbxStopBits.Items.IndexOf(ht["cbxStopBits"].ToString());elsecbxStopBits.SelectedIndex = 0;cbxStopBits.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region列出数据位cbxDataBits.Items.Add("8");cbxDataBits.Items.Add("7");cbxDataBits.Items.Add("6");cbxDataBits.Items.Add("5");if (ht.ContainsKey("cbxDataBits"))cbxDataBits.SelectedIndex =cbxDataBits.Items.IndexOf(ht["cbxDataBits"].ToString());elsecbxDataBits.SelectedIndex = 0;cbxDataBits.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region列出奇偶校验位cbxParity.Items.Add("无");cbxParity.Items.Add("奇校验");cbxParity.Items.Add("偶校验");if (ht.ContainsKey("cbxParity"))cbxParity.SelectedIndex =cbxParity.Items.IndexOf(ht["cbxParity"].ToString());elsecbxParity.SelectedIndex = 0;cbxParity.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region COM口重新加载cbxCOMPort.Items.Clear();//清除当前串口号中的所有串口名称 cbxCOMPort.Items.AddRange(Methods.ActivePorts());if (ht.ContainsKey("cbxCOMPort") &&cbxCOMPort.Items.Contains(ht["cbxCOMPort"].ToString()))cbxCOMPort.SelectedIndex =cbxCOMPort.Items.IndexOf(ht["cbxCOMPort"].ToString());elsecbxCOMPort.SelectedIndex = 0;cbxCOMPort.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region初始化计数器tbSendCount.Text = "0";tbSendCount.ReadOnly = true;tbReceivedCount.Text = "0";tbReceivedCount.ReadOnly = true;#endregion#region初始化当前时间toolStripStatusLabel3.Text = DateTime.Now.ToString();#endregion#region初始化串口状态toolStripStatusLabel1.ForeColor = Color.Blue;if (!isSetProperty)//串口未设置则设置串口属性{SetPortProperty();isSetProperty = true;}try{sp.Open();btnOpenCom.Text = "关闭串口";DisplayPortState(PortState.打开);}catch (Exception){//串口打开失败后,串口属性设置标志位设为falseisSetProperty = false;MessageBox.Show("串口无效或已被占用!", "错误提示"); }#endregion#region初始化间隔时间if (ht.ContainsKey("tbSpaceTime"))tbSpaceTime.Text = ht["tbSpaceTime"].ToString();elsetbSpaceTime.Text = "1000";#endregion#region初始化按16进制显示状态if (ht.ContainsKey("cb16Display") && ht["cb16Display"].ToString() == "True") cb16Display.Checked = true;elsecb16Display.Checked = false;#endregion#region初始化按16进制发送状态if (ht.ContainsKey("cb16Send") && ht["cb16Send"].ToString() == "True")cb16Send.Checked = true;elsecb16Send.Checked = false;#endregion#region初始化发送区文本if(ht.ContainsKey("tbSendData16") && ht.ContainsKey("tbSendDataStr")){tbSendData16 = ht["tbSendData16"].ToString();tbSendDataStr = ht["tbSendDataStr"].ToString();if (cb16Send.Checked)tbSendData.Text = ht["tbSendData16"].ToString();elsetbSendData.Text = ht["tbSendDataStr"].ToString();}#endregiontbSendData.Focus();}//显示当前时间private void timer1_Tick(object sender, EventArgs e){toolStripStatusLabel3.Text = DateTime.Now.ToString();}//点击打开串口按钮private void btnOpenCom_Click(object sender, EventArgs e){if (!sp.IsOpen)//串口没有打开时{if (!isSetProperty)//串口未设置则设置串口属性{SetPortProperty();isSetProperty = true;}try{sp.Open();btnOpenCom.Text = "关闭串口";DisplayPortState(PortState.打开);}catch (Exception){//串口打开失败后,串口属性设置标志位设为falseisSetProperty = false;MessageBox.Show("串口无效或已被占用!", "错误提示"); }}else//串口已经打开{try{sp.Close();isSetProperty = false;btnOpenCom.Text = "打开串口";DisplayPortState(PortState.关闭);}catch (Exception){MessageBox.Show("关闭串口时发生错误", "错误提示"); }}}//发送串口数据private void btnSend_Click(object sender, EventArgs e){if (tbSendData.Text.Trim() == "")//检测发送数据是否为空{MessageBox.Show("请输入要发送的数据!", "错误提示");return;}if (sp.IsOpen){DataSend();}else{MessageBox.Show("串口未打开!", "错误提示");}}//点击端口号选择下拉框按钮private void cbxCOMPort_SelectedIndexChanged(object sender, EventArgs e){AgainOpenPort();}//点击波特率选择下拉框按钮private void cbxBaudRate_SelectedIndexChanged(object sender, EventArgs e) {AgainOpenPort();}//点击数据位选择下拉框按钮private void cbxDataBits_SelectedIndexChanged(object sender, EventArgs e) {AgainOpenPort();}//点击停止位选择下拉框按钮private void cbxStopBits_SelectedIndexChanged(object sender, EventArgs e) {AgainOpenPort();}//点击校验位选择下拉框按钮private void cbxParity_SelectedIndexChanged(object sender, EventArgs e){AgainOpenPort();}//点击数据接收区清空按钮private void btnClearReceived_Click(object sender, EventArgs e){receivedDatas.Clear();tbReceivedData.Text = "";}//点击是否按16进制显示接收数据private void cb16Display_CheckedChanged(object sender, EventArgs e){if (cb16Display.Checked)tbReceivedData.Text = Methods.ByteTo16Str(receivedDatas.ToArray());elsetbReceivedData.Text =Encoding.Default.GetString(receivedDatas.ToArray());//点击是否按16进制发送数据private void cb16Send_CheckedChanged(object sender, EventArgs e){if (cb16Send.Checked){tbSendData.Text = tbSendData16;}else{tbSendData.Text = tbSendDataStr;}}//发送文本框键盘按键检测private void tbSendData_KeyPress(object sender, KeyPressEventArgs e){if (cb16Send.Checked){//正则匹配string pattern = "[0-9a-fA-F]|\b";//\b:退格键Match m = Regex.Match(e.KeyChar.ToString(), pattern);if (m.Success){if(e.KeyChar != '\b'){if (tbSendData.Text.Length % 3 == 2){tbSendData.Text += " ";tbSendData.SelectionStart = tbSendData.Text.Length;}e.KeyChar = Convert.ToChar(e.KeyChar.ToString().ToUpper()); }e.Handled = false;}else{e.Handled = true;}}else{e.Handled = false;}}//点击清空发送内容private void btnClearSend_Click(object sender, EventArgs e){tbSendData.Text = "";if (cb16Send.Checked)tbSendData16 = "";elsetbSendDataStr = "";//点击清空计数器数据private void btnClearCount_Click(object sender, EventArgs e){tbReceivedCount.Text = "0";tbSendCount.Text = "0";}//点击是否设置自动发送private void cbAutomaticSend_CheckedChanged(object sender, EventArgs e) {if (cbAutomaticSend.Checked){timer2.Enabled = true;timer2.Interval = Convert.ToInt32(tbSpaceTime.Text);}else{timer2.Enabled = false;}}//自动发送时间文本框键盘按键检测private void tbSpaceTime_KeyPress(object sender, KeyPressEventArgs e) {//正则匹配string pattern = "[0-9]|\b";Match m = Regex.Match(e.KeyChar.ToString(),pattern);if (m.Success){timer2.Interval = Convert.ToInt32(tbSpaceTime.Text);e.Handled = false;}else{e.Handled = true;}}//串口显示状态private void timer2_Tick(object sender, EventArgs e){if (sp.IsOpen){DataSend();}else{timer2.Enabled = false;cbAutomaticSend.Checked = false;MessageBox.Show("串口未打开!", "错误提示");return;}if (tbSendData.Text.Trim() == "")//检测发送数据是否为空{timer2.Enabled = false;cbAutomaticSend.Checked = false;MessageBox.Show("请输入要发送的数据!", "错误提示");return;}}//关闭窗口时出发的事件private void Form1_FormClosed(object sender, FormClosedEventArgs e){try{using (StreamWriter sw = new StreamWriter(path, false)){sw.WriteLine("cbxCOMPort=" + cbxCOMPort.Text);sw.WriteLine("cbxBaudRate=" + cbxBaudRate.Text);sw.WriteLine("cbxDataBits=" + cbxDataBits.Text);sw.WriteLine("cbxStopBits=" + cbxStopBits.Text);sw.WriteLine("cbxParity=" + cbxParity.Text);sw.WriteLine("cb16Display="+ cb16Display.Checked.ToString()); sw.WriteLine("tbSpaceTime=" + tbSpaceTime.Text);sw.WriteLine("cb16Send=" + cb16Send.Checked.ToString());sw.WriteLine("tbSendDataStr=" + tbSendDataStr);sw.WriteLine("tbSendData16=" + tbSendData16);sp.Close();}}catch(Exception ex){MessageBox.Show(ex.Message.ToString());}}//发送文本框按键抬起时出发的事件private void tbSendData_KeyUp(object sender, KeyEventArgs e){if (cb16Send.Checked){tbSendData16 = tbSendData.Text.Trim();}else{tbSendDataStr = tbSendData.Text;}}//点击读入文件按钮private void btnReadFile_Click(object sender, EventArgs e){openFileDialog1.Filter = "所有文件(*.*)|*.*";//文件筛选器的设定openFileDialog1.FilterIndex = 1;openFileDialog1.Title = "选择文件";openFileDialog1.FileName = "";openFileDialog1.ShowHelp = true;if(openFileDialog1.ShowDialog() == DialogResult.OK){using (FileStream fs = newFileStream(openFileDialog1.FileName,FileMode.Open)){byte[] bufferByte = new byte[fs.Length];fs.Read(bufferByte, 0, Convert.ToInt32(fs.Length));sp.Write(bufferByte, 0, bufferByte.Length);tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + bufferByte.Length).ToString();}}}//点击保存数据按钮private void btnSaveFile_Click(object sender, EventArgs e){saveFileDialog1.Filter = "所有文件(*.*)|*.*";if(saveFileDialog1.ShowDialog() == DialogResult.OK){string fName = saveFileDialog1.FileName;using(FileStream fs = File.Open(fName, FileMode.Append)){fs.Write(receivedDatas.ToArray(), 0, receivedDatas.Count);}}}}}需要源代码或有疑问的c#爱好者们,欢迎加入c#技术交流群(33647125),附加信息为”我以下载此文档”,进群后找群主索要源代码或进行技术交流。

c#上位机串口通信助手源代码详解

c#上位机串口通信助手源代码详解

c#上位机串口通信助手源代码实例详解
一、功能
1软件打开时,自动检测有效COM端口
2软件打开时,自动复原到上次关闭时的状态
3不必关闭串口,即可直接进行更改初始化设置内容(串口号、波特率、数据位、停止位、校验位),可按更改后的信息自动将串口重新打开
4
5
6
7
8

9
10
二、
三、
1

端口号:
数据位:
校验位:
发送(byte):tbSendCount接收(byte):tbReceivedCount
清空计数按钮:btnClearCount按16进制显示:cb16Display
接收区清空内容按钮:btnClearReceived保存数据按钮:btnSaveFile
接收数据框:tbReceivedData发送数据框:tbSendData
自动发送:cbAutomaticSend间隔时间:tbSpaceTime
按16进制发送:cb16Send发送区清空内容按钮:btnClearSend
2创建一个方法类
按Ctrl+shift+A快捷键创建一个类,名字叫Methods,代码为:
tbSendData.Text=tbSendDataStr;
}
}
//发送文本框键盘按键检测
privatevoidtbSendData_KeyPress(objectsender,KeyPressEventArgse) {
if(cb16Send.Checked)
{
//正则匹配
stringpattern="[0-9a-fA-F]|\b";//\b:退格键
if(m.Success)。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

c#上位机串口通信助手源代码实例详解一、功能
1软件打开时,自动检测有效COM端口
2 软件打开时,自动复原到上次关闭时的状态
3 不必关闭串口,即可直接进行更改初始化设置内容(串口号、波特率、数据位、
停止位、校验位),可按更改后的信息自动将串口重新打开
4 可统计接收字节和发送字节的个数
5 接收数据可按16进制数据和非16进制数据进行整体转换
6 可将接收到数据进行保存
7 可设置自动发送,发送时间可进行实时更改
8可按字符串、16进制字节、文件方式进行发送,字符串和16进制字节可分别进行存储,内容互不干扰
9 按16进制发送时,可自动校验格式,不会输错
10 可清空发送或接收区域的数据
二、使用工具
Visual Studio2015
三、程序详解
1 界面创建
图1
用winform创建如图1所示界面,控件名字分别为:
端口号:cbxCOMPort 波特率:cbxBaudRate
数据位:cbxDataBits 停止位:cbxStopBits
校验位:label5 打开串口按钮:btnOpenCom
发送(byte):tbSendCount 接收(byte):tbReceivedCount 清空计数按钮:btnClearCount 按16进制显示:cb16Display
接收区清空内容按钮:btnClearReceived 保存数据按钮:btnSaveFile
接收数据框:tbReceivedData 发送数据框:tbSendData
自动发送:cbAutomaticSend 间隔时间:tbSpaceTime
按16进制发送:cb16Send 发送区清空内容按钮:btnClearSend 读入文件按钮:btnReadFile 发送按钮:btnSend
2 创建一个方法类
按Ctrl+shift+A快捷键创建一个类,名字叫Methods,代码为:
using System;
using ;
using ;
using ;
using串口助手sdd
{
class Methods
{
oString();
if
= ());
else
= ();oString();
}
else
{
(tbSendDataStr);
= + .ToString();
}
}
catch (Exception ex)
{
return;
}
}
闭);
("串口无效或已被占用!", "错误提示");
return;
}
DisplayPortState(PortState.打开);
}
else
{
DisplayPortState(PortState.关闭);
}
}
public Form1()
{
InitializeComponent();
}
oString());
else
= 3;
= ;
#endregion
#region列出停止位
"1");
"");
"2");
if ("cbxStopBits"))
= "cbxStopBits"].ToString());
else
= 0;
= ;
#endregion
#region列出数据位
"8");
"7");
"6");
"5");
if ("cbxDataBits"))
= "cbxDataBits"].ToString());
else
= 0;
= ;
#endregion
#region列出奇偶校验位
"无");
"奇校验");
"偶校验");
if ("cbxParity"))
= "cbxParity"].ToString());
else
= 0;
= ;
#endregion
#region COM口重新加载
清除当前串口号中的所有串口名称
if ("cbxCOMPort") && "cbxCOMPort"].ToString())) = "cbxCOMPort"].ToString());
else
= 0;
= ;
#endregion
#region初始化计数器
= "0";
= true;
= "0";
= true;
#endregion
#region初始化当前时间
= #endregion
#region初始化串口状态
= ;
if (!isSetProperty)开);
}
catch (Exception)
{
oString();
else
= "1000";
#endregion
#region初始化按16进制显示状态
if ("cb16Display") && ht["cb16Display"].ToString() == "True") = true;
else
= false;
#endregion
#region初始化按16进制发送状态
if ("cb16Send") && ht["cb16Send"].ToString() == "True")
= true;
else
= false;
#endregion
#region初始化发送区文本
if("tbSendData16") && ("tbSendDataStr"))
{
tbSendData16 = ht["tbSendData16"].ToString();
tbSendDataStr = ht["tbSendDataStr"].ToString();
if
= ht["tbSendData16"].ToString();
else
= ht["tbSendDataStr"].ToString();
}
#endregion
();
}
开);
}
catch (Exception)
{
闭);
}
catch (Exception)
{
("关闭串口时发生错误", "错误提示");
}
}
}
|*.*";
oString();
}
}
}
|*.*";
if() ==
{
string fName = ;
using(FileStream fs = (fName, )
{
(), 0, ;
}
}
}
}
}
需要源代码或有疑问的c#爱好者们,欢迎加入c#技术交流群(),附加信息为”我以下载此文档”,进群后找群主索要源代码或进行技术交流。

相关文档
最新文档