串口调试助手源程序
经典串口调试助手源程序及串口通信设置
经典串口调试助手源程序及串口通信设置标题:串口调试助手之经典源程序及通信设置导言:串口调试助手是一种用于串口通信的调试工具,广泛应用于工业控制、测试等领域。
本文将介绍一种基于Windows平台的经典串口调试助手源程序及相关的串口通信设置,旨在帮助读者更好地了解该工具的使用和配置方法。
一、经典串口调试助手源程序1.开发平台:本程序采用C++ Builder 6.0开发。
2.功能概述:(1)串口设置包括设置串口波特率、数据位、校验位、停止位、流控、超时等参数。
(2)发送数据支持以字符串或Hex方式发送数据。
(3)接收数据实时显示串口接收到的数据,并支持数据格式设置。
(4)自动发送数据支持单次或循环发送,可设置发送时间间隔和发送次数。
(5)保存数据支持将接收到的数据保存为文本或二进制文件。
3.源程序结构本程序主要由以下几个模块组成:(1)Main Form:主窗体,包含图形界面显示和基本操作控件。
(2)Serial:串口类,负责串口相关操作,例如打开、关闭、设置参数、发送、接收等。
(3)SaveToFile:文件保存类,负责数据保存到文件中。
(4)Config:配置类,负责程序设置和读取。
(5)Hex:十六进制转换类,用于将字符串转换为Hex格式。
二、串口通信设置1.串口连接串口连接有两种方式:一种是通过RS232串口连接,需要将串口线插入串口,然后将串口线连接到目标设备;另一种是通过USB转串口连接,需要将USB转串口转接器插入计算机USB接口,然后将串口线连接到USB转串口转接器。
2.串口参数设置在使用串口调试助手前,必须先设置串口参数。
打开主窗体后,点击“串口设置”按钮,在弹出的窗口中设置串口的参数,包括波特率、数据位、校验位、停止位、流控和超时等参数。
其中,波特率是指通信时的数据传输速率,常用的有9600、19200、38400、57600、115200等。
数据位是指每次传输的数据位数,常用的有8位、7位、6位等。
串口精灵源代码
for(int i=0;i<len;)
{
char lstr,hstr=str[i];
if(hstr==' ')
{
i++;
continue;
}
i++;
if(i>=len)
break;
lstr=str[i];
//功能:若是在0-F之间的字符,则转换为相应的十六进制字符,否则返回-1
char CSCommTestDlg::ConvertHexChar(char ch)
{
if((ch>='0')&&(ch<='9'))
return ch-0x30;
else if((ch>='A')&&(ch<='F'))
{
// TODO: Add your control notification handler code here
VARIANT variant_inp;
COleSafeArray safearray_inp;
LONG len,k;
BYTE rxdata[2048]; //设置BYTE数组 An 8-bit integerthat is not signed.
写出详细的编程过程,姑且叫串口调试助手源程序V1.0或VC串口通讯源程序吧,
我相信,如果你用VC编程,那么有了这个代码,就可以轻而易举地完成串口编
程任务了。(也许本文过于详细,高手就不用看)
开始吧:
C#串口调试助手
//serialPort1.Parity = (Parity)Enum.Parse(typeof(Parityset), comboBox4.SelectedItem.ToString());
} public enum Parityset {
None, odd, Even, Mark, Space } private void comboBox5_SelectedIndexChanged(object sender, EventArgs e) //停止位 { serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), boBox5.Text); }
serialPort1.BaudRate = int.Parse(comboBox2.Text); serialPort1.DataBits = int.Parse(comboBox3.Text); serialPort1.Parity = (Parity)Enum.Parse(typeof(Parityset),
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) {
textBox3.Text = serialPort.ReadExisting();
label10.Text = (int.Parse(label10.Text.Trim()) + 1).ToString(); //统计接收区 数据 组数
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),附加信息为”我以下载此文档”,进群后找群主索要源代码或进行技术交流。
串口调试助手的使用说明-KC09141402-o04.
串口调试助手的使用重庆城市管理职业学院2016年1月26日串口调试助手的使用开场白对白:这次主要介绍串口调试助手的使用这部分内容,下面,主要从以下几个方面进行介绍,概述,运行界面介绍,参数设置说明,实验。
第3页对白:串口调试助手是一款通过串口进行调试的工具。
在物联网设备的安装调试过程中会经常用到这个小工具。
用串口线将需要调试的设备跟PC相连,这样就可以通过串口调试助手对该设备进行配置。
串口调试助手使用方便,功能也很强大。
第4页对白:接着,对串口调试助手的运行界面做一个介绍,点击串口调试助手进入运行界面,如图所示,这是参数设置区,可以对相关参数进行设置,这是数据发送区,这是数据接收区,在发送区和接收区分别选中十六进制显示,打开串口。
设置好后就可以正常使用串口调试助手了。
第5页对白:下面介绍串口调试助手的参数设置,首先介绍端口,串口调试助手启动后将自动识别所有可用的串口,只需要在下拉框中选择即可。
第6页对白:接着介绍波特率这个参数,它是一个衡量通信速度的参数,表示每秒传送的符号的个数。
高波特率常常用于很近的仪器间的通信。
我们常使用的波特率一般是9600和115200。
第7页对白:接着介绍效验位这个参数,效验是串口通信中一种简单的检错方式。
有四种效验方式:偶效验、奇效验、效验位始终为1和效验位始终为0。
当然没有效验位也是可以的,None即表示没有效验位。
第8页对白:下面介绍另外一个参数数据位,它是衡量通信中实际数据位的参数。
当计算机发送一个信息包,实际的数据不一定是8位的,标准的值是5、7、和8位。
如何设置取决于想传送的信息。
比如,标准的ASCII码是7位,扩展的ASCII 是8位。
第9页对白:下面介绍停止位这个参数,停止位用于表示单个包的最后一位。
典型的值为1,1.5和2位。
停止位不仅仅是表示传输的结束,同时提供计算机校正时钟同步的机会。
停止位的位数越多,不同时钟同步的容忍程度越大,但是数据传输同时也越慢。
串口调试助手源代码
串口调试助手预源代码using System;using System.Collect ion s.Ge neric;using p onen tModel;using System.Data;using System.Draw ing;using System.Linq;using System.Text;using System.Thread in g.Tasks;using System.Wi ndows.Forms;using Syste m.IO;using Syste m.IO .Ports;using System.Thread ing;using DevExpress.XtraEditors;using System.Text.RegularExpressi ons;n amespace Win dowsFormsApplicatio n3 {public partial class Form1 : XtraForm {SerialPort sp1 = new SerialPort(); int Flag = 0;int StateCha nged = 0;int StateCha nged_Ascii = 1; int StateCha nged_16 = 0;string Temp = null;stri ng Temp_memoSe nd = n ull;private void memoSe nd_EditValueCha nged(object sen der, Even tArgs e) { - }public Form1(){In itializeComp onen t();sp1.DataReceived += sp1_DataReceived; }private void Form1_Load(object sen der, Even tArgs e) { -this.MaximizeBox = false;// 检查是否有串口stri ng[] str = SerialPort.GetPortNames();if (str == null) __________ |{MessageBox.Show(”本机没有串口!", "error");return;}// 添加串口项目foreach (stri ng port in Syste m.IO.P orts.SerialPort.GetPortNames()) { cbSerial.Properties .I tems.Add(port);}// 串口设置默认选择项cbSerial.Selectedl ndex = 0;Con trol.CheckForlllegalCrossThreadCalls = false; spl.DataReceived += new SerialDataReceivedEve ntHa ndler(sp1_DataReceived); //订阅委托e)//SerialPort sp1 = new SerialPort();if (!sp1.lsOpe n)〃串口是关闭的,设置参数,打开串口{try{// 获取串口号string serialName = cbSerial.Selectedltem.ToString(); sp1.PortName = serialName;// 设置各参数stri ng strBaudRate = cbBaudRate.Text;string strDateBits = cbDataBits.Text;string strStopBits = cbStop.Text;sp1.BaudRate = Con vert.ToI nt32(strBaudRate);〃波特率sp1.DataBits = Con vert.ToI nt32(strDateBi ts);// 数据位switch (cbStop.Text) // 停止位{case "1":sp1.StopBits = StopBits. On e;break;case "1.5":sp1.StopBits = StopBits. On e;break;case "2":sp1.StopBits = StopBits.Two;break; default:case " 奇校验":sp1.Parity = Parity.Odd; break;精品文档", "Error");case "偶校验":spl.Parity = Parity.Eve n; break; default:MessageBox.Show("Error: 参数不正确!break;labSerial.Text =" 串口号:” + sp1 .P ortName; labState.Text ="状 态:打开";}catch (System.Excepti on ex) {MessageBox.Show("Error:" + ex.Message, "Error"); return; } } }//private void CloseSerial_Click(object sen der, Even tArgs e) 〃{// if (sp1.lsOpe n) // { // sp1.Close(); // labSerial.Text =" 串口号:” + sp1.PortName; // labState.Text ="状 态:关闭";// } 〃}private void Sen d_Click(object sen der, Even tArgs e) { - stri ng StrSe nd = memoSe nd.Text; if (!sp1.lsOpe n) {MessageBox.Show (” 请先打开串口! ", "Error");return; } else {if (rbt nSen dStr.Checked)//〃bt nOpe n.En abled =false; 字符串发送{if (ckTimeSe nd.Checked&& !(stri ng.lsNullOrEmpty(textTime.Text)))//判断是否定时发送数据{string Time = textTime.Text;tmSe nd.l nterval = int. Parse(Time) * 1000;//时间单位是秒,化成毫秒单位后的空格//stri ng StrSe nd_2 = StrSe nd_1.Replace (” ", ""); //stri ng StrSe nd_3 = stri ng.J oi n (” ",Regex.Matches(StrSend_2, @"..|.").Cast<Match>().ToList());stri ng[] StrArray = StrSe nd_1.Split(' '); // 用空格符隔开字符串数组var Str_Se nd = new List<stri ng>();// i nt byteBufferLe ngth = StrArray.Le ngth; 数组StrArray 的长度for (int i = 0; i < StrArray.Le ngth; i++){if (StrArray[i].Trim()=="") {//byteBufferLe ngth--; con ti nue; }else} else //{if (ckTimeSe nd.Checked&& !(string.IsNullOrEmpty(textTime.Text))){卜六进制发送//tmSe nd.Start();//开启定时器{if (StrArray[i].Le ngth < 3){Str_Se nd.Add(StrArray[i]);}else{Str_Se nd.AddRa nge(Devide(StrArray[i]));}}}int byteBufferLe ngth = Str_Se nd.Cou nt; byte[] byteBuffer = new byte[byteBufferLe ngth];in t ii = 0;//decNum = Con vert.ToI nt32(Str_Se nd[i], 16); // 把字符串转成16进制数〃byteBuffer[ii] = Co nvert.ToByte(decNum);〃}try{decNum = Con vert.ToI nt32(Str_Se nd[i], 16); // 把字符串转成16进制数byteBuffer[ii] = Co nvert.ToByte(decNum);}catch (System.Exceptio n ex){MessageBox.Show(”输入错误!","提示");return;}ii++;}sp1.Write(byteBuffer, 0, byteBuffer.Length);// 从第0个开始写入byteBuffer ,长度bytebuffer 的长度。
串口调试助手VC源程序及详细编程过程
据数留残除清以区冲缓读预先//;)(tupnIteG.mmoClrtc_m 0为度长据数区收接前当置设// ;)0(neLtupnIteS.mmoClrtc_m 件事mmoCnO的据数收接个一发引将时符字个1于等或于多有中区冲缓收接口串当每示表1数参// ; ) 1 ( d l o h s er h T R t e S . m m oCl r t c _ m ; ) 1 ( e d o M tu p n I t e S . m m oCl r t c _ m 据数取检式方制进二以 // 位止停个1�位据数个8�验校无�0069率特波// ;)"1,8,n,0069"(sgnitteSteS.mmoClrtc_m ; )" t r o p l a i r es n e p o t o nn a c " ( x o B e g ass e M x f A esle 口串开打//;)EURT(nepOtroPteS.mmoClrtc_m ) )( n e p O t r o P te G . m m o C l r t c_m ! ( f i 1moc择选// ;)1(troPmmoCteS.mmoClrtc_m ; )E S L A F ( n e p Ot r o P t e S . m m oCl r t c _ m ) ) ( n e p O t r oP t e G . m m o C l rtc _ m ( f i e r e h n o i t az i l a i t i n i a r t x e d d A :OD O T / / �码代下如入加�口串开打)(golaiDtinInO::glDtseTmmoCSC的框话对主在们我在现。口串开打中数函 理处的钮按该在�钮按始开个一做中序程在如例�口串开打候时的要需你在以可你 数 参 口 串 置 设 和 口 串 开 打 . 6
串口调试助手源程序
串口调试助手源程序及编程详细过程1.建立项目2.在项目中插入MSComm控件3.利用ClassWizard定义CMSComm类控制变量4.在对话框中添加控件5.添加串口事件消息处理函数OnComm()6.打开和设置串口参数7.发送数据在众多网友的支持下,串口调试助手从2001年5月21日发布至今,短短一个月,在全国各地累计下载量近5000人次,在近200多个电子邮件中,20多人提供了使用测试意见,更有50多位朋友提出要串口调试助手的源代码,为了答谢谢朋友们的支持,公开推出我最初用VC控件MSComm编写串口通信程序的源代码,并写出详细的编程过程,姑且叫串口调试助手源程序V1.0或VC串口通讯源程序吧,我相信,如果你用VC编程,那么有了这个代码,就可以轻而易举地完成串口编程任务了。
(也许本文过于详细,高手就不用看)1.建立项目:打开VC++6.0,建立一个基于对话框的MFC应用程序SCommTest(与我源代码一致,等会你会方便一点);2.在项目中插入MSComm控件选择Project菜单下Add To Project子菜单中的 Components and Controls…选项,在弹出的对话框中双击Registered ActiveX Controls项(稍等一会,这个过程较慢),则所有注册过的ActiveX控件出现在列表框中。
选择Microsoft Communications Control, version 6.0,,单击Insert按钮将它插入到我们的Project中来,接受缺省的选项。
(如果你在控件列表中看不到Microsoft Communications Control, version 6.0,那可能是你在安装VC6时没有把ActiveX一项选上,重新安装VC6,选上ActiveX就可以了),这时在ClassView视窗中就可以看到CMSComm类了,(注意:此类在ClassWizard中看不到,重构clw文件也一样),并且在控件工具栏Controls中出现了电话图标(如图1所示),现在要做的是用鼠标将此图标拖到对话框中,程序运行后,这个图标是看不到的。
串口调试助手使用教程
串口调试助手使用教程首先,确保你已经正确连接了串口调试助手软件和目标设备的串口。
1. 打开串口调试助手软件。
在软件界面的顶部菜单栏中,通常会有一个“串口”的选项,点击它展开串口设置。
2. 查找并选择正确的串口。
在串口设置中,你可以看到可用的串口列表。
选择正确的串口,通常以“COM”开头并带有具体的串口号。
如果你不确定应该选择哪个串口,可以尝试一个接一个地选择每个串口,然后观察是否有数据传输。
3. 配置串口参数。
继续在串口设置中,通常会有波特率、数据位、停止位、校验位和流控制等选项。
确保这些参数与你的设备设置相匹配。
如果你不确定设备的串口参数,可以参考设备的说明书或者询问设备厂商。
4. 打开串口。
完成串口参数配置后,点击一个按钮或者选项来打开串口连接。
通常会有一个“打开串口”、“连接”或者类似的按钮。
如果一切正常,你应该能在软件界面上看到串口的连接状态。
5. 监听串口数据。
一旦串口连接成功,你可以开始接收和发送数据。
通常会有一个数据接收区和一个数据发送区。
数据接收区会实时显示通过串口接收到的数据。
你可以通过不同的设置来选择以何种方式显示数据,例如文本、十六进制等。
6. 发送数据。
如果你需要通过串口发送数据到目标设备,你可以在数据发送区输入相应的数据,然后点击发送按钮或者类似的选项。
通过串口调试助手,你可以发送文本、十六进制等各种类型的数据。
7. 保存数据。
如果你需要保存通过串口接收或发送的数据,你可以使用串口调试助手提供的保存功能。
通常会有一个保存按钮或者菜单选项,点击它可以将数据保存为文件。
8. 关闭串口。
当你不再需要使用串口时,记得关闭串口连接。
一般会有一个“关闭串口”或者类似的按钮。
这样可以释放串口资源,同时避免不必要的错误。
以上就是使用串口调试助手的基本步骤。
根据不同的软件界面和功能设置,可能会略有差异,但基本原理是相似的。
请根据具体软件的说明和使用指南进行相关操作。
经典串口调试助手源程序及串口通信设置
经典串口调试助手源程序及串口通信设置串口调试助手是一种用于串口通信调试的工具,它可以通过串口与外部设备进行数据的读写和处理,常用于单片机、嵌入式系统、电子设备等领域的开发调试中。
经典串口调试助手源程序经典串口调试助手是一款经典的串口调试工具,其源程序使用C语言编写,提供了丰富的功能和易于使用的界面,被广泛应用于各种领域的开发调试中。
该工具可以在Windows操作系统中运行,并支持多种串口通信协议,包括RS232、RS485、RS422等。
以下是经典串口调试助手部分源程序的示例:```c// 打开串口HANDLE OpenSerialPort(const char* portName){ HANDLE hCom; hCom = CreateFile(portName, // 串口名称GENERIC_READ | GENERIC_WRITE, // 读写访问0,// 无共享NULL,// 安全描述符OPEN_EXISTING,// 打开方式FILE_ATTRIBUTE_NORMAL, // 文件属性NULL); // 文件模板if (hCom ==INVALID_HANDLE_VALUE) // 判断是否打开成功{ return NULL; } return hCom;}// 发送数据int SendData(HANDLE hCom, const char* data, int len){ DWORD writeSize; if (!WriteFile(hCom, data, len, &writeSize, NULL)) // 写入数据{ return -1; } return writeSize;}// 接收数据int ReceiveData(HANDLE hCom, char* data, int len){ DWORD readSize; if (!ReadFile(hCom, data, len,&readSize, NULL)) // 读取数据{ return -1; } return readSize;}// 关闭串口int CloseSerialPort(HANDLE hCom){ if(!CloseHandle(hCom)) // 关闭句柄{ return-1; } return 0;}```上述函数实现了打开串口、发送数据、接收数据和关闭串口等基本功能,可以作为串口通信的底层驱动实现。
VB串口调试助手源代码
VB串口调试助手源代码Dim OutputAscii As BooleanDim InputString As StringDim OutputString As String'============================================================================== =======' 变量定义'============================================================================== =======Option Explicit ’强制显式声明Dim ComSwitch As Boolean ’串口开关状态判断Dim FileData As String ’要发送的文件暂存Dim SendCount As Long ’发送数据字节计数器Dim ReceiveCount As Long ’接收数据字节计数器Dim InputSignal As String ’接收缓冲暂存Dim OutputSignal As String ’发送数据暂存Dim DisplaySwitch As Boolean ’显示开关Dim ModeSend As Boolean ’发送方式判断Dim Savetime As Single ’时间数据暂存延时用Dim SaveTextPath As String ’保存文本路径' 网页超链接申明Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As LongPrivate Sub CloseCom() '关闭串口On Error GoTo ErrIf MSComm.PortOpen = True ThenMSComm.PortOpen = False’先判断串口是否打开,如果打开则先关闭txtstatus.Text = "STATUS:COM Port Cloced" ’串口状态显示mnuconnect.Caption = "断开串口"cmdswitch.Caption = "打开串口"'ImgSwitch.Picture = LoadPicture("f:\我的VB\串口调试软件\图片\guan.jpg") ' 显示串口已经关闭的图标ImgSwitchoff.Visible = TrueImgSwitchon.Visible = FalseErr:End SubPrivate Sub UpdateStatus()If MSComm.PortOpen ThenStatusBar1.Panels(1).Text = "Connected"mnuautosend.Caption = "自动发送"mnuconnect.Caption = "断开串口"ElseStatusBar1.Panels(1).Text = "断开串口"mnuautosend.Caption = "disautosend"mnuconnect.Caption = "打开串口"End IfStatusBar1.Panels(2).Text = "COM" & mPortStatusBar1.Panels(3).Text = MSComm.SettingsIf (OutputAscii) ThenStatusBar1.Panels(4) = "ASCII"ElseStatusBar1.Panels(4) = "HEX"End If'On Error GoTo ErrIf ChkAutoSend.Value = 1 Then ’如果有效则,自动发送If MSComm.PortOpen = True Then ’串口状态判断mnuautosend.Caption = "Dis&autosend"TmrAutoSend.Interval = Val(TxtAutoSendTime) ’设置自动发送时间TmrAutoSend.Enabled = True ’打开自动发送定时器Elsemnuautosend.Caption = "autosend"ChkAutoSend.Value = 0 ’串口没有打开去掉自动发送MsgBox "串口没有打开,请打开串口", 48, "串口调试助手" ' 如果串口没有被打开,提示打开串口End IfElseIf ChkAutoSend.Value = 0 Then ’如果无效,不发送mnuautosend.Caption = "autosend"TmrAutoSend.Enabled = False ’关闭自动发送定时器End IfErr:End SubPrivate Sub CmdSendFile_Click() '发送文件On Error GoTo ErrIf MSComm.PortOpen = True Then ’如果串口打开了,则可以发送数据If FileData = "" Then ’判断发送数据是否为空MsgBox "发送的文件为空", 16, "串口调试助手" ’发送数据为空则提示ElseIf ChkHexReceive.Value = 1 Then ’如果按十六进制接收时,按二进制发送,否则按文本发送MSComm.InputMode = comInputModeBinary ’二进制发送ElseMSComm.InputMode = comInputModeText ’文本发送End IfMSComm.Output = Trim(FileData) ’发送数据ModeSend = True ’设置文本发送方式End IfElseMsgBox "串口没有打开,请打开串口", 48, "串口调试助手" ' 如果串口没有被打开,提示打开串口End IfErr:End SubPrivate Sub Comm_initial(Port As Byte, BaudRate As String, ParityBit As String, DataBit As Integer, StopBit As Integer)On Error GoTo ErrorTrap ' 错误则跳往错误处理If MSComm.PortOpen = True Then MSComm.PortOpen = False’先判断串口是否打开,如果打开则先关闭mPort = Port ’设定端口MSComm.Settings = BaudRate & "," & ParityBit & "," & DataBit & "," & StopBit ' 设置波特率,无校验,8位数据位,1位停止位MSComm.InBufferSize = 1024 ’设置接收缓冲区为1024字节MSComm.OutBufferSize = 4096 ’设置发送缓冲区为4096字节MSComm.InBufferCount = 0 ’清空输入缓冲区MSComm.OutBufferCount = 0 ’清空输出缓冲区MSComm.SThreshold = 1 ’发送缓冲区空触发发送事件MSComm.RThreshold = 1 ’每X个字符到接收缓冲区引起触发接收事件MSComm.OutBufferCount = 0 ’清空发送缓冲区MSComm.InBufferCount = 0 ’滑空接收缓冲MSComm.PortOpen = True ’打开串口If MSComm.PortOpen = True Thentxtstatus.Text = "STATUS:" & cbocom.Text & " OPEND," & cbobaudrate.Text & "," &Left(cboparitybit.Text, 1) & "," & cbodatabit.Text & "," & cbostopbit.TextElsetxtstatus.Text = "STATUS:COM Port Cloced" ’串口没打开时,提示串口关闭状态End IfExit SubErrorTrap: ’错误处理Select Case Err.NumberCase comPortAlreadyOpen ’如果串口已经打开,则提示MsgBox "没有发现此串口或被占用", 49, "串口调试助手"CloseComCase ElseMsgBox "没有发现此串口或被占用", 49, "串口调试助手"CloseComEnd SelectErr.ClearEnd SubPrivate Sub Comm_reSet(Port As Byte, BaudRate As String, ParityBit As String, DataBit As Integer, StopBit As Integer)On Error GoTo ErrorHint ’错误则跳往错误处理If MSComm.PortOpen = True Then MSComm.PortOpen = False’先判断串口是否打开,如果打开则先关闭mPort = Port ’设定端口MSComm.Settings = BaudRate & "," & ParityBit & "," & DataBit & "," & StopBit ' 设置波特率,无校验,8位数据位,1位停止位MSComm.PortOpen = True ’打开串口If MSComm.PortOpen = True Thencmdswitch.Caption = "关闭串口"'ImgSwitch.Picture = LoadPicture("f:\我的VB\串口调试软件\图片\kai.jpg") ' 显示串口已经打开的图标ImgSwitchoff.Visible = Falsemnuconnect.Caption = "disconnect"ImgSwitchon.Visible = Truetxtstatus.Text = "STATUS:" & cbocom.Text & " OPEND," & cbobaudrate.Text & "," &Left(cboparitybit.Text, 1) & "," & cbodatabit.Text & "," & cbostopbit.TextElsecmdswitch.Caption = "打开串口"'ImgSwitch.Picture = LoadPicture("f:\我的VB\串口调试软件\图片\guan.jpg") ' 显示串口已经关闭的图标ImgSwitchon.Visible = FalseImgSwitchoff.Visible = Truetxtstatus.Text = "STATUS:COM Port Cloced"End IfExit SubErrorHint: ’错误处理Select Case Err.NumberCase comPortAlreadyOpen ’如果串口已经打开,则提示MsgBox "没有成功,请重试", vbExclamation, "串口调试助手"CloseCom ’调用关闭串口函数Case ElseMsgBox "没有成功,请重试", vbExclamation, "串口调试助手"CloseCom ’调用关闭串口函数End SelectErr.Clear ’清除Err 对象的属性End SubPrivate Sub Command1_Click()End SubPrivate Sub cbobaudrate_Change()Call Comm_reSet(Val(Mid(cbocom.Text, 4, 2)), cbobaudrate.Text, Left(cboparitybit.Text, 1), cbodatabit.Text, cbostopbit.Text) '串口设置End SubPrivate Sub cbocom_Change()Call Comm_reSet(Val(Mid(cbocom.Text, 4, 2)), cbobaudrate.Text, Left(cboparitybit.Text, 1), cbodatabit.Text, cbostopbit.Text) '串口设置End SubPrivate Sub cbodatabit_Change()Call Comm_reSet(Val(Mid(cbocom.Text, 4, 2)), cbobaudrate.Text, Left(cboparitybit.Text, 1), cbodatabit.Text, cbostopbit.Text) '串口设置End SubPrivate Sub cboparitybit_Change()Call Comm_reSet(Val(Mid(cbocom.Text, 4, 2)), cbobaudrate.Text, Left(cboparitybit.Text, 1), cbodatabit.Text, cbostopbit.Text) '串口设置End SubPrivate Sub cbostopbit_Change()Call Comm_reSet(Val(Mid(cbocom.Text, 4, 2)), cbobaudrate.Text, Left(cboparitybit.Text, 1), cbodatabit.Text, cbostopbit.Text) '串口设置End SubPrivate Sub chkautosend_Click()On Error GoTo ErrIf ChkAutoSend.Value = 1 Then ’如果有效则,自动发送If MSComm.PortOpen = True Then ’串口状态判断mnuautosend.Caption = "取消自动发送"TmrAutoSend.Interval = Val(TxtAutoSendTime) ’设置自动发送时间TmrAutoSend.Enabled = True ’打开自动发送定时器ElseChkAutoSend.Value = 0 ’串口没有打开去掉自动发送MsgBox "串口没有打开,请打开串口", 48, "串口调试助手" ' 如果串口没有被打开,提示打开串口End IfElseIf ChkAutoSend.Value = 0 Then ’如果无效,不发送mnuautosend.Caption = "自动发送数据"TmrAutoSend.Enabled = False ’关闭自动发送定时器End IfErr:End SubPrivate Sub cmdamend_Click()Dim spShell As Object ’定义存放引用对象的变量Dim spFolder As Object ’定义存放引用对象的变量Dim spFolderItem As Object ’定义存放引用对象的变量Dim spPath As String ’定义存放的变量On Error GoTo Err ’错误处理,防止取消打开文件夹时报错Const WINDOW_HANDLE = 0Const NO_OPTIONS = 0Set spShell = CreateObject("Shell.Application")Set spFolder = spShell.BrowseForFolder(WINDOW_HANDLE, "选择目录:", NO_OPTIONS,"C:\Scripts")Set spFolderItem = spFolder.SelfspPath = spFolderItem.PathspPath = Replace(spPath, "\", "\") ’ Replace函数的返回值是一个字符串txtsavepath.Text = spPath ’把文件夹路径显示在标签上SaveTextPath = txtsavepath.Text ’路径暂存Err:End SubPrivate Sub CmdClearCounter_Click()On Error GoTo ErrSendCount = 0 ’发送计数器清零ReceiveCount = 0 ’接收计数器清零txtRXcount.Text = "RX:" & 0 ’接收计数txtTXcount.Text = "TX:" & 0 ’发送计数Err:End SubPrivate Sub cmdclearrecieve_Click()TxtReceive.Text = ""End SubPrivate Sub cmdclearsend_Click()txtsend.Text = ""End SubPrivate Sub CmdHelp_Click()FrmHelp.ShowEnd SubPrivate Sub CmdQuit_Click()If MSComm.PortOpen = True Then MSComm.PortOpen = False’先判断串口是否打开,如果打开则先关闭Unload Me ’卸载窗体,并退出程序EndEnd SubPrivate Sub cmdsavedisp_Click()On Error GoTo Err ’错误处理SaveTextPath = txtsavepath ’路径暂存Open txtsavepath & "\1.txt" For Output As #1 ’打开文件’不存在的话会创建文件,如已存在会覆盖’ output 改为append 为追加’改为input 则只读Print #1, Year(Date) & "年" & Month(Date) & "月" & Day(Date) & _"日" & Hour(Time) & "时" & Minute(Time) & "分" & Second(Time) & _"秒" & vbCrLf & TxtReceive.Text + vbCrLf ’把接收区的文本保存文本前加上保存时间(0000年00月00日00时00分00秒)’ vbcrlf 为回车换行Close #1 ’关闭文件txtsavepath = "OK,1.txt Save" ’提示保存成功cmdsavedisp.Enabled = FalseSavetime = Timer ’记下开始的时间While Timer < Savetime + 5 ’循环等待5 - 要延时的时间DoEvents ’转让控制权,以便让操作系统处理其它的事件。
串口调试助手
串口调试工具的使用1运行串口调试助手首先运行串口调试助手运行后界面图如下所示:图1-1 串口调试工具界面图2 串口调试助手的使用2.1串口调试助手基本参数的设置串口通信最重要的参数是波特率、数据位、停止位和奇偶校验。
对于两个进行通行的端口,这些参数必须匹配:标题栏显示区调试区图2-1串口调试助手基本参数设置图(1)串口号软件启动后将自动识别所有可用的串口,您只需要在下拉框中选择即可。
如下图2-2所示,软件自动识别出COM3和COM4。
选择我们使用的串口COM4,点击“打开串口“按钮。
如果要使用另一个串口,请先单击”关闭串口“按钮,软件将显示串口已经关闭。
图2-3口号设置图(2)波特率它这是一个衡量通信速度的参数,表示每秒钟传送的bit的个数。
例如300波特表示每秒钟发送300个bit。
波特率和距离成反比,高波特率常常用于放置的很近的仪器间的通信。
我们常使用的波特率一般是9600和115200,我们这里选择波特率为9600。
图2-4波特率设置图(3)数据位这是衡量通信中实际数据位的参数。
当计算机发送一个信息包,实际的数据不一定是8位的,标准的值是5、7和8位。
如何设置取决于你想传送的信息。
比如,标准的ASCII 码是0~127(7位)。
扩展的ASCII码是0~255(8位)。
如果数据使用简单的文本(标准ASCII码),那么每个数据包使用7位数据。
每个包是指一个字节,包括开始/停止位,数据位和奇偶校验位。
由于实际数据位取决于通信协议的选取,术语“包”指任何通信的情况。
图2-5数据位设置图(4)停止位停止位用于表示单个包的最后一位。
典型的值为1,1.5和2位。
由于数据是在传输线上定时的,并且每一个设备有其自己的时钟,很可能在通信中两台设备间出现了小小的不同步。
因此停止位不仅仅是表示传输的结束,并且提供计算机校正时钟同步的机会。
适用于停止位的位数越多,不同时钟同步的容忍程度越大,但是数据传输率同时也越慢。
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),附加信息为”我以下载此文档”,进群后找群主索要源代码或进行技术交流。
经典的串口调试工具源代码(二)
经典的串口调试工具源代码(二)Private Sub cmdswitch_Click()On Error GoTo ErrIf MSComm.PortOpen = True ThenComSwitch = TrueElseComSwitch = FalseEnd IfIf ComSwitch = False ThenStatusBar1.Panels(1).Text = "Connected"mnuconnect.Caption = "Dis&connect"OpenCom ' 打开串口ComSwitch = TrueElseCloseCom ' 关闭串口ComSwitch = FalseStatusBar1.Panels(1).Text = "Disconnected"mnuconnect.Caption = "&Connect"StatusBar1.Panels(2).Text = "COM" & mPort StatusBar1.Panels(3).Text = MSComm.SettingsIf (OutputAscii) ThenStatusBar1.Panels(4) = "ASCII"ElseStatusBar1.Panels(4) = "HEX"End IfEnd IfErr:End SubPrivate Sub Form_Load()On Error GoTo ErrlblWEB.FontUnderline = True ' WEB上加下划线lblWEB.ForeColor = vbBlue ' 蓝色显示WEBtxtsend.Text = "" ' 载入发送信息If MSComm.PortOpen = True Then MSComm.PortOpen = False ' 先判断串口是否打开,如果打开则先关闭' 初始化串口Call Comm_initial(Val(Mid(cbocom.Text, 4, 1)), cbobaudrate.Text, Left(cboparitybit.Text, 1),cbodatabit.Text, cbostopbit.Text)' 数据位载入cbodatabit.AddItem "8"cbodatabit.AddItem "7"cbodatabit.AddItem "6"' 停止位载入cbostopbit.AddItem "1"cbostopbit.AddItem "1.5"cbostopbit.AddItem "2"Err:End SubPrivate Sub hexReceive()On Error GoTo ErrDim ReceiveArr() As Byte ' 接收数据数组Dim receiveData As String ' 数据暂存Dim Counter As Integer ' 接收数据个数计数器Dim i As Integer ' 循环变量If (MSComm.InBufferCount > 0) ThenCounter = MSComm.InBufferCount ' 读取接收数据个数receiveData = "" ' 清缓冲ReceiveArr = MSComm.Input ' 数据放入数组For i = 0 To (Counter - 1) Step 1 ' 数据格式处理If (ReceiveArr(i) < 16) ThenreceiveData = receiveData & "0" + Hex(ReceiveArr(i)) & Space(1) ' 小于16,前面加0ElsereceiveData = receiveData & Hex(ReceiveArr(i)) & Space(1) ' 加空格显示End IfNext iTxtReceive.Text = TxtReceive.Text + receiveData ' 显示接收的十六进制数据TxtReceive.SelStart = Len(TxtReceive.Text) ' 显示光标位置End IfReceiveCount = ReceiveCount + Counter ' 接收计数txtRXcount.Text = "RX:" & ReceiveCount ' 接收字节数显示If chkautoclear.Value = 1 Then ' 自动清空判断If ReceiveCount >= 65535 ThenTxtReceive.Text = ""End IfEnd IfErr:End SubPrivate Sub hexSend()On Error Resume NextDim outputLen As Integer ' 发送数据长度Dim outData As String ' 发送数据暂存Dim SendArr() As Byte ' 发送数组Dim TemporarySave As String ' 数据暂存Dim dataCount As Integer ' 数据个数计数Dim i As Integer ' 局部变量outData = UCase(Replace(txtsend.Text, Space(1), Space(0))) ' 先去掉空格,再转换为大写字母outData = UCase(outData) ' 转换成大写outputLen = Len(outData) ' 数据长度For i = 0 To outputLenTemporarySave = Mid(outData, i + 1, 1) ' 取一位数据If (Asc(TemporarySave) >= 48 And Asc(TemporarySave) <= 57) Or (Asc(TemporarySave) >= 65And Asc(TemporarySave) <= 70) ThendataCount = dataCount + 1ElseExit ForExit SubEnd IfNextIf dataCount Mod 2 <> 0 Then ' 判断十六进制数据是否为双数dataCount = dataCount - 1 ' 不是双数,则减1End IfoutData = Left(outData, dataCount) ' 取出有效的十六进制数据ReDim SendArr(dataCount / 2 - 1) ' 重新定义数组长度For i = 0 To dataCount / 2 - 1SendArr(i) = Val("&H" + Mid(outData, i * 2 + 1, 2)) ' 取出数据转换成十六进制并放入数组中NextSendCount = SendCount + (dataCount / 2) ' 计算总发送数txtTXcount.Text = "TX:" & SendCountMSComm.Output = SendArr ' 发送数据End SubPrivate Sub OpenCom() '打开串口On Error GoTo ErrIf MSComm.PortOpen = True Then MSComm.PortOpen = False ' 先判断串口是否打开,如果打开则先关闭Call Comm_reSet(Val(Mid(cbocom.Text, 4, 1)), cbobaudrate.Text, Left(cboparitybit.Text, 1),cbodatabit.Text, cbostopbit.Text) ' 串口设置If MSComm.PortOpen = True Thentxtstatus.Text = "STATUS:" & cbocom.Text & " OPEND," & cbobaudrate.Text & "," & Left(cboparitybit.Text, 1) & "," & cbodatabit.Text & "," & cbostopbit.Textcmdswitch.Caption = "关闭串口"mnuconnect.Caption = "disconnect"'ImgSwitch.Picture = LoadPicture("f:\我的VB\串口调试软件\图片\kai.jpg") ' 显示串口已经打开的图标ImgSwitchon.Visible = TrueImgSwitchoff.Visible = FalseElsetxtstatus.Text = "STATUS:COM Port Cloced" ' 串口状态显示cmdswitch.Caption = "打开串口"mnuconnect.Caption = "connect"'ImgSwitch.Picture = LoadPicture("f:\我的VB\串口调试软件\图片\guan.jpg") ' 显示串口已经关闭的图标ImgSwitchoff.Visible = TrueImgSwitchon.Visible = FalseEnd IfErr:End SubPrivate Sub textReceive()On Error GoTo ErrInputSignal = MSComm.InputReceiveCount = ReceiveCount + LenB(StrConv(InputSignal, vbFromUnicode)) ' 计算总接收数据If DisplaySwitch = False Then ' 显示接收文本TxtReceive.Text = TxtReceive.Text & InputSignal ' 单片机内存的值用TextReceive显示出TxtReceive.SelStart = Len(TxtReceive.Text) ' 显示光标位置End IftxtRXcount.Text = "RX:" & ReceiveCount ' 接收字节数显示If chkautoclear.Value = 1 Then ' 自动清空判断If ReceiveCount >= 65535 ThenTxtReceive.Text = ""End IfEnd IfErr:End SubPrivate Sub textSend()On Error GoTo ErrIf ModeSend = True ThenOutputSignal = FileData ' 发送文件ElseOutputSignal = txtsend.Text ' 发送文本End IfSendCount = SendCount + LenB(StrConv(OutputSignal, vbFromUnicode)) ' 计算总发送数txtTXcount.Text = "TX:" & SendCount ' 发送字节数显示Err:End SubPrivate Sub Image1_Click()End SubPrivate Sub mnuautosend_Click()On Error GoTo Err'If TmrAutoSend.Enabled = True Then ' 如果有效则,自动发送If MSComm.PortOpen = True Then ' 串口状态判断ChkAutoSend.Value = 1TmrAutoSend.Interval = Val(TxtAutoSendTime) ' 设置自动发送时间mnuautosend.Caption = "取消自动发送"TmrAutoSend.Enabled = True ' 打开自动发送定时器Elsemnuautosend.Caption = "自动发送"ChkAutoSend.Value = 0 ' 串口没有打开去掉自动发送MsgBox "串口没有打开,请打开串口", 48, "串口调试助手" ' 如果串口没有被打开,提示打开串口End If'ElseIf TmrAutoSend.Enabled = False Then ' 如果无效,不发送' mnuautosend.Caption = "autosend"' TmrAutoSend.Enabled = False ' 关闭自动发送定时器'End IfErr:End SubPrivate Sub mnucom_Click(Index As Integer)Dim i As IntegerDim OldPort As LongOn Error Resume NextWith MSCommOldPort = .CommPortIf MSComm.PortOpen Then.PortOpen = False.CommPort = Index.PortOpen = TrueIf Err.Number <> 0 Then ' This should not happen...MsgBox "Com" & Index & " is not available." & _vbCrLf & Err.DescriptionErr.Clear.CommPort = OldPortElseFor i = 1 To 4mnucom(i).Checked = FalseNext imnucom(Index).Checked = TrueEnd IfElse.CommPort = IndexFor i = 1 To 4mnucom(i).Checked = FalseNext imnucom(Index).Checked = TrueEnd IfEnd WithUpdateStatusEnd SubPrivate Sub mnuconnect_Click()On Error Resume NextIf MSComm.PortOpen = True ThenComSwitch = TrueElseComSwitch = FalseEnd IfWith MSCommIf .PortOpen = True Then.PortOpen = Falsetxtstatus.Text = "STATUS:COM Port Cloced" ' 串口状态显示cmdswitch.Caption = "打开串口"'ImgSwitch.Picture = LoadPicture("f:\我的VB\串口调试软件\图片\guan.jpg") ' 显示串口已经关闭的图标ImgSwitchoff.Visible = TrueImgSwitchon.Visible = FalseElse.PortOpen = TrueComSwitch = Truetxtstatus.Text = "STATUS:" & cbocom.Text & " OPEND," & cbobaudrate.Text & "," & Left(cboparitybit.Text, 1) & "," & cbodatabit.Text & "," & cbostopbit.Textcmdswitch.Caption = "关闭串口"'ImgSwitch.Picture = LoadPicture("f:\我的VB\串口调试软件\图片\kai.jpg") ' 显示串口已经打开的图标ImgSwitchon.Visible = TrueImgSwitchoff.Visible = FalseIf Err.Number <> 0 ThenMsgBox "Com" & .CommPort & " is not available." & vbCrLf & _Err.DescriptionErr.ClearEnd IfEnd IfEnd WithUpdateStatusEnd SubPrivate Sub mnusave_Click()On Error GoTo Err ' 错误处理SaveTextPath = txtsavepath ' 路径暂存Open txtsavepath & "\1.txt" For Output As #1 ' 打开文件' 不存在的话会创建文件,如已存在会覆盖' output 改为append 为追加' 改为input 则只读Print #1, Year(Date) & "年" & Month(Date) & "月" & Day(Date) & _"日" & Hour(Time) & "时" & Minute(Time) & "分" & Second(Time) & _"秒" & vbCrLf & TxtReceive.Text + vbCrLf ' 把接收区的文本保存文本前加上保存时间(0000年00月00日00时00分00秒)' vbcrlf 为回车换行Close #1 ' 关闭文件txtsavepath = "OK,1.txt Save" ' 提示保存成功cmdsavedisp.Enabled = FalseSavetime = Timer ' 记下开始的时间While Timer < Savetime + 5 ' 循环等待5 - 要延时的时间DoEvents ' 转让控制权,以便让操作系统处理其它的事件。
串口调试助手通信调试原理图PCB及使用手册
串口调试助手通信调试原理图PCB及使用手册【简要说明】1、尺寸:长170mmX宽72mmX高18mm二、主要芯片:单片机,MAX485,MAX232三、工作电压:6V至40V,功耗小于1W四、特点:1、具有稳压电路,输入电压广,具有电源指示灯。
2、具有485通信和232通信及TTL通信。
3、具有数码管数据显示,蜂鸣器提示音4、波特率可调分别是 2400 4800 9600 192005、采用大按键,机械寿命长。
6、单片机编程,提供源代码7、可发送20组数据8、具有系统复位按键9、端子采用螺旋压接端子10、工作温度-40度至 +70度11、工作湿度 40% ~ 80%RH12、板子静态功耗小于1W13、具有续流保护14、具有电磁抗干扰能力15、板子稳定工作可靠16、板子可安装在DIN导轨上面使用说明:【标注说明】【功能描述】【原理图】【PCB图】【元件清单】【应用举例】【应用举例2】例如:将下面一组数据通过串口发送给电脑。
波特率是9600,电脑用串口助手显示出来。
数据是:A0 B2 CC FF EF D8 90 88第一步:板子供电,串口连接电脑,查看串口号。
如下图:我的电脑--属性--硬件---设备管理器---端口设备。
如下图:第三步:从发送板,按下下面一组数据,数据是:A0 B2 CC FF EF D8 90 88数据按完之后,按发送键“S2”,如果数据输入错误,可以按”S1”按键清零,重新输入。
如果要发送多遍,重复按“S2”按键。
单遍发送如下图。
【源代码程序】/*一次最多发送20组数据,大于这个数据就不再发送*/#include <STC12C5A60S2.H>#define uchar unsigned char#define uint unsigned int/**************************************************************/unsigned char T0RH = 0; //T0重载值的高字节unsigned char T0RL = 0; //T0重载值的低字节extern void UartDriver();//串口驱动函数,监测数据帧的接收,调度功能函数,需在主循环中调用extern void ConfigUART(unsigned int baud);//串口配置函数,baud-通信波特率extern void ConfigUART1(unsigned int baud1);//串口配置函数,baud-通信波特率extern void UartRxMonitor(unsigned char ms); //串口接收监控,由空闲时间判定帧结束,需在定时中断中调用,ms-定时间隔extern void SendString(char *s) ;extern void UartWrite(unsigned char *buf, unsigned char len);//串口数据写入,即串口发送函数,buf-待发送数据的指针,len-指定的发送长度extern void fengming();uchar zh[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};uchar jieshou[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uchar jj = 0;/*****************************************************************/sbit out0 = P2^0;sbit out1 = P2^1;sbit out2 = P2^2;sbit out3 = P2^3;sbit in0 = P2^4;sbit in1 =P2^5;sbit in2 =P2^6;sbit in3 =P2^7;sbit smgk = P3^6;sbit boma1 = P1^1;sbit boma2 = P1^0;bit d1 = 1;bit d2 = 1;sbit in4 = P1^6;sbit in5 = P1^5;uchar code xianshi [] ={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e,0xbf};uchar dangqianzhuangtai[4][4] = {{1,1,1,1},{1,1,1,1},{1,1,1,1},{1,1,1,1}};void t0 () interrupt 1{uchar i;static uchar lie = 0;static uchar sao[2] = {1,1};static uchar saomiaobaocun [4][4] = {{0xff,0xff,0xff,0xff},{0xff,0xff,0xff,0xff},{0xff,0xff,0xff,0xff},{0xff,0xff,0xff,0xff}};TH0 = 0xfc;TL0 = 0x67;UartRxMonitor(1); //串口接收监控sao[0] = (sao[0]<<1) |in4;sao[1] = (sao[1]<<1) |in5;saomiaobaocun [lie][0] = (saomiaobaocun [lie][0]<<1) | in0; saomiaobaocun [lie][1] = (saomiaobaocun [lie][1]<<1) | in1; saomiaobaocun [lie][2] = (saomiaobaocun [lie][2]<<1) | in2; saomiaobaocun [lie][3] = (saomiaobaocun [lie][3]<<1) | in3;if(sao[0] == 0x00){d1 = 0;}else if(sao[0] == 0xff){d1 = 1;}if(sao[1] == 0x00){d2 = 0;}else if(sao[1] == 0xff){d2 = 1;}for (i=0;i<4;i++){if ((saomiaobaocun [lie][i] & 0x0f) == 0x00){dangqianzhuangtai[lie][i] = 0;}else if ((saomiaobaocun [lie][i] & 0x0f) == 0x0f){dangqianzhuangtai[lie][i] = 1;}}lie++;lie = lie & 0x03;switch (lie){case 0 : out1 = 1; out2 = 1; out3 = 1; out0 = 0; break;case 1 : out0 = 1; out2 = 1; out3 = 1; out1 = 0; break;case 2 : out0 = 1; out1 = 1; out3 = 1; out2 = 0; break;case 3 : out0 = 1; out1 = 1; out2 = 1; out3 = 0; break;}}void main (){uchar i,j;bit q1 = 1;bit q2 = 1;uchar qianyicizhuangtai[4][4] = {{1,1,1,1},{1,1,1,1},{1,1,1,1},{1,1,1,1}};smgk = 0;TMOD = 0x01;TH0 = 0xfc;TL0 = 0x67;TR0 = 1;EA = 1;ET0 = 1;P0 = xianshi[16];// ConfigUART(9600); //配置波特率为9600while (1){UartDriver(); //调用串口驱动if((boma1 == 0)&&(boma2 != 0)){ConfigUART(2400); //配置波特率为1200}if((boma2 == 0)&&(boma1 != 0)){ConfigUART(4800); //配置波特率为4800}if((boma1 == 0)&&(boma2 == 0)){ConfigUART(9600); //配置波特率为9600}if((boma1 != 0)&&(boma2 != 0)){ConfigUART1(19200); //配置波特率为19200 }if(d1 != q1){q1 = d1;if(d1 == 0){if((jj != 0)&&(jj <= 2)){zh[0] = jieshou[0] | jieshou[1];UartWrite(zh, 1);fengming();}if((jj > 2)&&(jj <= 4)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];UartWrite(zh, 2);fengming();}if((jj > 4)&&(jj <= 6)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];UartWrite(zh, 3);fengming();}if((jj > 6)&&(jj <= 8)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];zh[3] = jieshou[6] | jieshou[7];UartWrite(zh, 4);fengming();}if((jj > 8)&&(jj <= 10)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];zh[3] = jieshou[6] | jieshou[7];zh[4] = jieshou[8] | jieshou[9];UartWrite(zh, 5);fengming();}if((jj > 10)&&(jj <= 12)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];zh[3] = jieshou[6] | jieshou[7];zh[4] = jieshou[8] | jieshou[9];zh[5] = jieshou[10] | jieshou[11];UartWrite(zh, 6);fengming();}if((jj > 12)&&(jj <= 14)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];zh[3] = jieshou[6] | jieshou[7];zh[4] = jieshou[8] | jieshou[9];zh[5] = jieshou[10] | jieshou[11];zh[6] = jieshou[12] | jieshou[13];UartWrite(zh, 7);fengming();}if((jj > 14)&&(jj <= 16)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];zh[3] = jieshou[6] | jieshou[7];zh[4] = jieshou[8] | jieshou[9];zh[5] = jieshou[10] | jieshou[11];zh[6] = jieshou[12] | jieshou[13];zh[7] = jieshou[14] | jieshou[15];UartWrite(zh, 8);fengming();}if((jj > 16)&&(jj <= 18)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];zh[3] = jieshou[6] | jieshou[7];zh[4] = jieshou[8] | jieshou[9];zh[5] = jieshou[10] | jieshou[11];zh[6] = jieshou[12] | jieshou[13];zh[7] = jieshou[14] | jieshou[15];zh[8] = jieshou[16] | jieshou[17];UartWrite(zh, 9);fengming();}if((jj > 18)&&(jj <= 20)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];zh[3] = jieshou[6] | jieshou[7];zh[4] = jieshou[8] | jieshou[9];zh[5] = jieshou[10] | jieshou[11];zh[6] = jieshou[12] | jieshou[13];zh[7] = jieshou[14] | jieshou[15];zh[8] = jieshou[16] | jieshou[17];zh[9] = jieshou[18] | jieshou[19];UartWrite(zh, 10);fengming();}}}if(d2 != q2){q2 = d2;if(d2 == 0){jj = 0;jieshou[0] = 0x00;jieshou[1] = 0x00;jieshou[2] = 0x00;jieshou[3] = 0x00;jieshou[4] = 0x00;jieshou[5] = 0x00;jieshou[6] = 0x00;jieshou[7] = 0x00;jieshou[8] = 0x00;jieshou[9] = 0x00;P0 = xianshi[16];fengming();}}for (i=0;i<4;i++){for (j=0;j<4;j++){if(dangqianzhuangtai[i][j] != qianyicizhuangtai[i][j] ){qianyicizhuangtai[i][j] = dangqianzhuangtai[i][j];if(qianyicizhuangtai[i][j] != 0){jj++;if((i*4+j) < 9){P0 = xianshi[i*4+j+1];}if((i*4+j) == 9){P0 = xianshi[0];}if((i*4+j) > 9){P0 = xianshi[i*4+j];}fengming();/******************1组**************************/if(jj == 1){//jieshou[0] = i*4+j;//jieshou[0] = jieshou[0] << 4;if((i*4+j) < 9){jieshou[0] = i*4+j+1;if((i*4+j) == 9){jieshou[0] = 0;}if((i*4+j) > 9){jieshou[0] = i*4+j;}jieshou[0] = jieshou[0] << 4;}if(jj == 2){//jieshou[1] = i*4+j;if((i*4+j) < 9){jieshou[1] = i*4+j+1;}if((i*4+j) == 9){jieshou[1] = 0;}if((i*4+j) > 9){jieshou[1] = i*4+j;}}/******************2组**************************/ if(jj == 3){//jieshou[2] = i*4+j;if((i*4+j) < 9){jieshou[2] = i*4+j+1;}if((i*4+j) == 9){jieshou[2] = 0;}if((i*4+j) > 9){jieshou[2] = i*4+j;jieshou[2] = jieshou[2] << 4;}if(jj == 4){//jieshou[3] = i*4+j;if((i*4+j) < 9){jieshou[3] = i*4+j+1;}if((i*4+j) == 9){jieshou[3] = 0;}if((i*4+j) > 9){jieshou[3] = i*4+j;}}/******************3组**************************/ if(jj == 5){//jieshou[4] = i*4+j;if((i*4+j) < 9){jieshou[4] = i*4+j+1;}if((i*4+j) == 9){jieshou[4] = 0;}if((i*4+j) > 9){jieshou[4] = i*4+j;}jieshou[4] = jieshou[4] << 4;}if(jj == 6){//jieshou[5] = i*4+j;if((i*4+j) < 9){jieshou[5] = i*4+j+1;}if((i*4+j) == 9){jieshou[5] = 0;}if((i*4+j) > 9){jieshou[5] = i*4+j;}}/******************4组**************************/ if(jj == 7){//jieshou[6] = i*4+j;if((i*4+j) < 9){jieshou[6] = i*4+j+1;}if((i*4+j) == 9){jieshou[6] = 0;}if((i*4+j) > 9){jieshou[6] = i*4+j;}jieshou[6] = jieshou[6] << 4;}if(jj == 8){//jieshou[7] = i*4+j;if((i*4+j) < 9){jieshou[7] = i*4+j+1;}if((i*4+j) == 9){jieshou[7] = 0;}if((i*4+j) > 9){jieshou[7] = i*4+j;}}/******************5组**************************/if(jj == 9){//jieshou[8] = i*4+j;if((i*4+j) < 9){jieshou[8] = i*4+j+1;}if((i*4+j) == 9){jieshou[8] = 0;}if((i*4+j) > 9){jieshou[8] = i*4+j;}jieshou[8] = jieshou[8] << 4;}if(jj == 10){//jieshou[9] = i*4+j;if((i*4+j) < 9){jieshou[9] = i*4+j+1;}if((i*4+j) == 9){jieshou[9] = 0;}if((i*4+j) > 9){jieshou[9] = i*4+j;}}/******************6组**************************/ if(jj == 11){//jieshou[10] = i*4+j;if((i*4+j) < 9){jieshou[10] = i*4+j+1;}if((i*4+j) == 9){jieshou[10] = 0;}if((i*4+j) > 9){jieshou[10] = i*4+j;}jieshou[10] = jieshou[10] << 4;}if(jj == 12){//jieshou[11] = i*4+j;if((i*4+j) < 9){jieshou[11] = i*4+j+1;}if((i*4+j) == 9){jieshou[11] = 0;}if((i*4+j) > 9){jieshou[11] = i*4+j;}}/******************7组**************************/ if(jj == 13){//jieshou[12] = i*4+j;if((i*4+j) < 9){jieshou[12] = i*4+j+1;}if((i*4+j) == 9){jieshou[12] = 0;}if((i*4+j) > 9){jieshou[12] = i*4+j;}jieshou[12] = jieshou[12] << 4;}if(jj == 14){//jieshou[13] = i*4+j;if((i*4+j) < 9){jieshou[13] = i*4+j+1;}if((i*4+j) == 9){jieshou[13] = 0;}if((i*4+j) > 9){jieshou[13] = i*4+j;}}/******************8组**************************/ if(jj == 15){//jieshou[14] = i*4+j;if((i*4+j) < 9){jieshou[14] = i*4+j+1;}if((i*4+j) == 9){jieshou[14] = 0;}if((i*4+j) > 9){jieshou[14] = i*4+j;}jieshou[14] = jieshou[14] << 4;}if(jj == 16){//jieshou[15] = i*4+j;if((i*4+j) < 9){jieshou[15] = i*4+j+1;}if((i*4+j) == 9){jieshou[15] = 0;}if((i*4+j) > 9){jieshou[15] = i*4+j;}}/******************9组**************************/ if(jj == 17){//jieshou[16] = i*4+j;if((i*4+j) < 9){jieshou[16] = i*4+j+1;}if((i*4+j) == 9){jieshou[16] = 0;}if((i*4+j) > 9){jieshou[16] = i*4+j;}jieshou[16] = jieshou[16] << 4;}if(jj == 18){//jieshou[17] = i*4+j;if((i*4+j) < 9){jieshou[17] = i*4+j+1;}if((i*4+j) == 9){jieshou[17] = 0;}if((i*4+j) > 9){jieshou[17] = i*4+j;}}/******************10组**************************/ if(jj == 19){//jieshou[18] = i*4+j;if((i*4+j) < 9){jieshou[18] = i*4+j+1;}if((i*4+j) == 9){jieshou[18] = 0;}if((i*4+j) > 9){jieshou[18] = i*4+j;}jieshou[18] = jieshou[18] << 4;}if(jj == 20){//jieshou[19] = i*4+j;if((i*4+j) < 9){jieshou[19] = i*4+j+1;}if((i*4+j) == 9){jieshou[19] = 0;}if((i*4+j) > 9){jieshou[19] = i*4+j;}}}}}}}}void UartAction(unsigned char *buf, unsigned char len){//在接收到的数据帧后添加换车换行符后发回// buf[len++] = '\r';//buf[len++] = '\n';UartWrite(buf, (len-2));}【真值表】【图片展示】。
经典的串口调试工具源代码(二)
经典的串口调试工具源代码(二)Private Sub cmdswitch_Click()On Error GoTo ErrIf MSComm.PortOpen = True ThenComSwitch = TrueElseComSwitch = FalseEnd IfIf ComSwitch = False ThenStatusBar1.Panels(1).Text = "Connected"mnuconnect.Caption = "Dis&connect"OpenCom ' 打开串口ComSwitch = TrueElseCloseCom ' 关闭串口ComSwitch = FalseStatusBar1.Panels(1).Text = "Disconnected"mnuconnect.Caption = "&Connect"StatusBar1.Panels(2).Text = "COM" & mPort StatusBar1.Panels(3).Text = MSComm.SettingsIf (OutputAscii) ThenStatusBar1.Panels(4) = "ASCII"ElseStatusBar1.Panels(4) = "HEX"End IfEnd IfErr:End SubPrivate Sub Form_Load()On Error GoTo ErrlblWEB.FontUnderline = True ' WEB上加下划线lblWEB.ForeColor = vbBlue ' 蓝色显示WEBtxtsend.Text = "" ' 载入发送信息If MSComm.PortOpen = True Then MSComm.PortOpen = False ' 先判断串口是否打开,如果打开则先关闭' 初始化串口Call Comm_initial(Val(Mid(cbocom.Text, 4, 1)), cbobaudrate.Text, Left(cboparitybit.Text, 1),cbodatabit.Text, cbostopbit.Text)' 数据位载入cbodatabit.AddItem "8"cbodatabit.AddItem "7"cbodatabit.AddItem "6"' 停止位载入cbostopbit.AddItem "1"cbostopbit.AddItem "1.5"cbostopbit.AddItem "2"Err:End SubPrivate Sub hexReceive()On Error GoTo ErrDim ReceiveArr() As Byte ' 接收数据数组Dim receiveData As String ' 数据暂存Dim Counter As Integer ' 接收数据个数计数器Dim i As Integer ' 循环变量If (MSComm.InBufferCount > 0) ThenCounter = MSComm.InBufferCount ' 读取接收数据个数receiveData = "" ' 清缓冲ReceiveArr = MSComm.Input ' 数据放入数组For i = 0 To (Counter - 1) Step 1 ' 数据格式处理If (ReceiveArr(i) < 16) ThenreceiveData = receiveData & "0" + Hex(ReceiveArr(i)) & Space(1) ' 小于16,前面加0ElsereceiveData = receiveData & Hex(ReceiveArr(i)) & Space(1) ' 加空格显示End IfNext iTxtReceive.Text = TxtReceive.Text + receiveData ' 显示接收的十六进制数据TxtReceive.SelStart = Len(TxtReceive.Text) ' 显示光标位置End IfReceiveCount = ReceiveCount + Counter ' 接收计数txtRXcount.Text = "RX:" & ReceiveCount ' 接收字节数显示If chkautoclear.Value = 1 Then ' 自动清空判断If ReceiveCount >= 65535 ThenTxtReceive.Text = ""End IfEnd IfErr:End SubPrivate Sub hexSend()On Error Resume NextDim outputLen As Integer ' 发送数据长度Dim outData As String ' 发送数据暂存Dim SendArr() As Byte ' 发送数组Dim TemporarySave As String ' 数据暂存Dim dataCount As Integer ' 数据个数计数Dim i As Integer ' 局部变量outData = UCase(Replace(txtsend.Text, Space(1), Space(0))) ' 先去掉空格,再转换为大写字母outData = UCase(outData) ' 转换成大写outputLen = Len(outData) ' 数据长度For i = 0 To outputLenTemporarySave = Mid(outData, i + 1, 1) ' 取一位数据If (Asc(TemporarySave) >= 48 And Asc(TemporarySave) <= 57) Or (Asc(TemporarySave) >= 65And Asc(TemporarySave) <= 70) ThendataCount = dataCount + 1ElseExit ForExit SubEnd IfNextIf dataCount Mod 2 <> 0 Then ' 判断十六进制数据是否为双数dataCount = dataCount - 1 ' 不是双数,则减1End IfoutData = Left(outData, dataCount) ' 取出有效的十六进制数据ReDim SendArr(dataCount / 2 - 1) ' 重新定义数组长度For i = 0 To dataCount / 2 - 1SendArr(i) = Val("&H" + Mid(outData, i * 2 + 1, 2)) ' 取出数据转换成十六进制并放入数组中NextSendCount = SendCount + (dataCount / 2) ' 计算总发送数txtTXcount.Text = "TX:" & SendCountMSComm.Output = SendArr ' 发送数据End SubPrivate Sub OpenCom() '打开串口On Error GoTo ErrIf MSComm.PortOpen = True Then MSComm.PortOpen = False ' 先判断串口是否打开,如果打开则先关闭Call Comm_reSet(Val(Mid(cbocom.Text, 4, 1)), cbobaudrate.Text, Left(cboparitybit.Text, 1),cbodatabit.Text, cbostopbit.Text) ' 串口设置If MSComm.PortOpen = True Thentxtstatus.Text = "STATUS:" & cbocom.Text & " OPEND," & cbobaudrate.Text & "," & Left(cboparitybit.Text, 1) & "," & cbodatabit.Text & "," & cbostopbit.Textcmdswitch.Caption = "关闭串口"mnuconnect.Caption = "disconnect"'ImgSwitch.Picture = LoadPicture("f:\我的VB\串口调试软件\图片\kai.jpg") ' 显示串口已经打开的图标ImgSwitchon.Visible = TrueImgSwitchoff.Visible = FalseElsetxtstatus.Text = "STATUS:COM Port Cloced" ' 串口状态显示cmdswitch.Caption = "打开串口"mnuconnect.Caption = "connect"'ImgSwitch.Picture = LoadPicture("f:\我的VB\串口调试软件\图片\guan.jpg") ' 显示串口已经关闭的图标ImgSwitchoff.Visible = TrueImgSwitchon.Visible = FalseEnd IfErr:End SubPrivate Sub textReceive()On Error GoTo ErrInputSignal = MSComm.InputReceiveCount = ReceiveCount + LenB(StrConv(InputSignal, vbFromUnicode)) ' 计算总接收数据If DisplaySwitch = False Then ' 显示接收文本TxtReceive.Text = TxtReceive.Text & InputSignal ' 单片机内存的值用TextReceive显示出TxtReceive.SelStart = Len(TxtReceive.Text) ' 显示光标位置End IftxtRXcount.Text = "RX:" & ReceiveCount ' 接收字节数显示If chkautoclear.Value = 1 Then ' 自动清空判断If ReceiveCount >= 65535 ThenTxtReceive.Text = ""End IfEnd IfErr:End SubPrivate Sub textSend()On Error GoTo ErrIf ModeSend = True ThenOutputSignal = FileData ' 发送文件ElseOutputSignal = txtsend.Text ' 发送文本End IfSendCount = SendCount + LenB(StrConv(OutputSignal, vbFromUnicode)) ' 计算总发送数txtTXcount.Text = "TX:" & SendCount ' 发送字节数显示Err:End SubPrivate Sub Image1_Click()End SubPrivate Sub mnuautosend_Click()On Error GoTo Err'If TmrAutoSend.Enabled = True Then ' 如果有效则,自动发送If MSComm.PortOpen = True Then ' 串口状态判断ChkAutoSend.Value = 1TmrAutoSend.Interval = Val(TxtAutoSendTime) ' 设置自动发送时间mnuautosend.Caption = "取消自动发送"TmrAutoSend.Enabled = True ' 打开自动发送定时器Elsemnuautosend.Caption = "自动发送"ChkAutoSend.Value = 0 ' 串口没有打开去掉自动发送MsgBox "串口没有打开,请打开串口", 48, "串口调试助手" ' 如果串口没有被打开,提示打开串口End If'ElseIf TmrAutoSend.Enabled = False Then ' 如果无效,不发送' mnuautosend.Caption = "autosend"' TmrAutoSend.Enabled = False ' 关闭自动发送定时器'End IfErr:End SubPrivate Sub mnucom_Click(Index As Integer)Dim i As IntegerDim OldPort As LongOn Error Resume NextWith MSCommOldPort = .CommPortIf MSComm.PortOpen Then.PortOpen = False.CommPort = Index.PortOpen = TrueIf Err.Number <> 0 Then ' This should not happen...MsgBox "Com" & Index & " is not available." & _vbCrLf & Err.DescriptionErr.Clear.CommPort = OldPortElseFor i = 1 To 4mnucom(i).Checked = FalseNext imnucom(Index).Checked = TrueEnd IfElse.CommPort = IndexFor i = 1 To 4mnucom(i).Checked = FalseNext imnucom(Index).Checked = TrueEnd IfEnd WithUpdateStatusEnd SubPrivate Sub mnuconnect_Click()On Error Resume NextIf MSComm.PortOpen = True ThenComSwitch = TrueElseComSwitch = FalseEnd IfWith MSCommIf .PortOpen = True Then.PortOpen = Falsetxtstatus.Text = "STATUS:COM Port Cloced" ' 串口状态显示cmdswitch.Caption = "打开串口"'ImgSwitch.Picture = LoadPicture("f:\我的VB\串口调试软件\图片\guan.jpg") ' 显示串口已经关闭的图标ImgSwitchoff.Visible = TrueImgSwitchon.Visible = FalseElse.PortOpen = TrueComSwitch = Truetxtstatus.Text = "STATUS:" & cbocom.Text & " OPEND," & cbobaudrate.Text & "," & Left(cboparitybit.Text, 1) & "," & cbodatabit.Text & "," & cbostopbit.Textcmdswitch.Caption = "关闭串口"'ImgSwitch.Picture = LoadPicture("f:\我的VB\串口调试软件\图片\kai.jpg") ' 显示串口已经打开的图标ImgSwitchon.Visible = TrueImgSwitchoff.Visible = FalseIf Err.Number <> 0 ThenMsgBox "Com" & .CommPort & " is not available." & vbCrLf & _Err.DescriptionErr.ClearEnd IfEnd IfEnd WithUpdateStatusEnd SubPrivate Sub mnusave_Click()On Error GoTo Err ' 错误处理SaveTextPath = txtsavepath ' 路径暂存Open txtsavepath & "\1.txt" For Output As #1 ' 打开文件' 不存在的话会创建文件,如已存在会覆盖' output 改为append 为追加' 改为input 则只读Print #1, Year(Date) & "年" & Month(Date) & "月" & Day(Date) & _"日" & Hour(Time) & "时" & Minute(Time) & "分" & Second(Time) & _"秒" & vbCrLf & TxtReceive.Text + vbCrLf ' 把接收区的文本保存文本前加上保存时间(0000年00月00日00时00分00秒)' vbcrlf 为回车换行Close #1 ' 关闭文件txtsavepath = "OK,1.txt Save" ' 提示保存成功cmdsavedisp.Enabled = FalseSavetime = Timer ' 记下开始的时间While Timer < Savetime + 5 ' 循环等待5 - 要延时的时间DoEvents ' 转让控制权,以便让操作系统处理其它的事件。
串口调试助手源码
串口调试助手程序框架(一)【截图】【源码】main.cpp#include<windows.h>#include<commctrl.h>#include<iostream>#include<stdio.h>#include"resource.h"using namespace std;HINSTANCE hInst;//窗口实例HWND hRDCLEAR, hSDCLEAR;HMENU hRDCHAR;void Init(HWND hwndDlg){SetWindowText(GetDlgItem(hwndDlg, SETXONC), "0x13");SetWindowText(GetDlgItem(hwndDlg, SETXOFFC), "0x19");SetWindowText(GetDlgItem(hwndDlg, SETTO), "0");SendDlgItemMessage(hwndDlg, RDCHAR, BM_SETCHECK, 1, 0);//把RadioBox RDCHAR设置为选中SendDlgItemMessage(hwndDlg, SDCHAR, BM_SETCHECK, 1, 0);//默认发送字符SendDlgItemMessage(hwndDlg, CTASY, BM_SETCHECK, 1, 0);//默认异步通信//在一个groupbox中必须有一个radiobox的属性:组为真//串口号SetWindowText(GetDlgItem(hwndDlg, SETCOMNO), "COM4");//默认值SendDlgItemMessage(hwndDlg, SETCOMNO, CB_ADDSTRING, 0, (LPARAM)("COM1"));SendDlgItemMessage(hwndDlg, SETCOMNO, CB_ADDSTRING, 0, (LPARAM)("COM2"));SendDlgItemMessage(hwndDlg, SETCOMNO, CB_ADDSTRING, 0, (LPARAM)("COM3"));SendDlgItemMessage(hwndDlg, SETCOMNO, CB_ADDSTRING, 0, (LPARAM)("COM4"));SendDlgItemMessage(hwndDlg, SETCOMNO, CB_ADDSTRING, 0, (LPARAM)("COM5"));SendDlgItemMessage(hwndDlg, SETCOMNO, CB_ADDSTRING, 0, (LPARAM)("COM6"));SendDlgItemMessage(hwndDlg, SETCOMNO, CB_ADDSTRING, 0, (LPARAM)("COM7"));SendDlgItemMessage(hwndDlg, SETCOMNO, CB_ADDSTRING, 0, (LPARAM)("COM8"));SendDlgItemMessage(hwndDlg, SETCOMNO, CB_ADDSTRING, 0, (LPARAM)("COM9"));//波特率SetWindowText(GetDlgItem(hwndDlg, SETBR), "9600");//默认值SendDlgItemMessage(hwndDlg, SETBR, CB_ADDSTRING, 0, (LPARAM)("1200"));SendDlgItemMessage(hwndDlg, SETBR, CB_ADDSTRING, 0, (LPARAM)("2400"));SendDlgItemMessage(hwndDlg, SETBR, CB_ADDSTRING, 0, (LPARAM)("4800"));SendDlgItemMessage(hwndDlg, SETBR, CB_ADDSTRING, 0, (LPARAM)("9600"));SendDlgItemMessage(hwndDlg, SETBR, CB_ADDSTRING, 0, (LPARAM)("14400"));SendDlgItemMessage(hwndDlg, SETBR, CB_ADDSTRING, 0, (LPARAM)("28800"));SendDlgItemMessage(hwndDlg, SETBR, CB_ADDSTRING, 0, (LPARAM)("38400"));SendDlgItemMessage(hwndDlg, SETBR, CB_ADDSTRING, 0, (LPARAM)("57600"));SendDlgItemMessage(hwndDlg, SETBR, CB_ADDSTRING, 0, (LPARAM)("115200"));//数据位SetWindowText(GetDlgItem(hwndDlg, SETBS), "8");//默认值SendDlgItemMessage(hwndDlg, SETBS, CB_ADDSTRING, 0, (LPARAM)("4"));SendDlgItemMessage(hwndDlg, SETBS, CB_ADDSTRING, 0, (LPARAM)("5"));SendDlgItemMessage(hwndDlg, SETBS, CB_ADDSTRING, 0, (LPARAM)("6"));SendDlgItemMessage(hwndDlg, SETBS, CB_ADDSTRING, 0, (LPARAM)("7"));SendDlgItemMessage(hwndDlg, SETBS, CB_ADDSTRING, 0, (LPARAM)("8"));//校验位SetWindowText(GetDlgItem(hwndDlg, SETPAR), "N");//默认值SendDlgItemMessage(hwndDlg, SETPAR, CB_ADDSTRING, 0, (LPARAM)("N"));SendDlgItemMessage(hwndDlg, SETPAR, CB_ADDSTRING, 0, (LPARAM)("odd"));SendDlgItemMessage(hwndDlg, SETPAR, CB_ADDSTRING, 0, (LPARAM)("even"));//停止位SetWindowText(GetDlgItem(hwndDlg, SETSB), "1");//默认值SendDlgItemMessage(hwndDlg, SETSB, CB_ADDSTRING, 0, (LPARAM)("1"));SendDlgItemMessage(hwndDlg, SETSB, CB_ADDSTRING, 0, (LPARAM)("2"));}BOOL CALLBACK DlgMain(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {//窗口回调函数switch (uMsg)//消息处理{case WM_INITDIALOG://初始化{Init(hwndDlg);}return TRUE;case WM_CLOSE://关闭窗口{EndDialog(hwndDlg, 0);}return TRUE;case WM_COMMAND://菜单消息{switch (LOWORD(wParam)){case RDCLEAR://清空接收框数据{SetWindowText(hRDCLEAR, "");}return TRUE;case SDCLEAR://清空发送框数据{SetWindowText(GetDlgItem(hwndDlg, SDTEXT), "");}return TRUE;case SDSEND://发送数据{TCHAR szBuf[80];//缓存区string temp;GetWindowText(GetDlgItem(hwndDlg, SDTEXT), szBuf, 80);//获得接收框的文本temp = szBuf;//拼接字符串//cout<<temp;SetWindowText(GetDlgItem(hwndDlg, RDTEXT), temp.c_str());}return TRUE;case SETOP:{//打开串口}return TRUE;case SETCP:{//关闭串口}return TRUE;case SETSO:{}return TRUE;}}return TRUE;}return FALSE;}int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {hInst = hInstance;InitCommonControls();return DialogBox(hInst, MAKEINTRESOURCE(DLG_MAIN), NULL, (DLGPROC)DlgMain);}【源码】resource.h#ifndef IDC_STATIC#define IDC_STATIC (-1)#endif#define DLG_MAIN 100#define RDBOX 40000#define RDTEXT 40001#define RDCHAR 40002#define RDHEX 40003#define RDCLEAR 40004#define SDCHAR 40005#define SDHEX 40006#define SDCLEAR 40007#define SDSEND 40008#define SDAS 40009#define SDASTIME 40010#define SETCOMNO 40011#define CTSYN 40012#define CTASY 40013#define SETBR 40014#define SDTEXT 40015#define SETXONC 40016#define SETXOFFC 40017#define SETTO 40018#define SETPAR 40019#define SETSB 40020#define SETBS 40021#define SETOP 40022#define SETCP 40023#define SETSO 40024【源码】resource.rc#include<windows.h>#include<commctrl.h>#include<richedit.h>#include"resource.h"//// Dialog resources//LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRALDLG_MAIN DIALOG 0, 0, 635, 304STYLE DS_3DLOOK| DS_CENTER| DS_MODALFRAME| DS_SHELLFONT| WS_CAPTION| WS_VISIBLE| WS_POPUP| WS_SYSMENU CAPTION "SerialPortDebug"FONT 8, "Ms Shell Dlg"{GROUPBOX "Setting", 0, 257, 7, 365, 290, 0, WS_EX_LEFTLTEXT "Select Port", 0, 284, 30, 36, 8, SS_LEFT, WS_EX_LEFTGROUPBOX "Communication Type", 0, 278, 62, 295, 35, 0, WS_EX_LEFTLTEXT "ByteSize", 0, 469, 120, 28, 8, SS_LEFT, WS_EX_LEFTLTEXT "BaudRate", 0, 297, 122, 33, 8, SS_LEFT, WS_EX_LEFTGROUPBOX "Send Data", 0, 12, 135, 240, 162, 0, WS_EX_LEFTLTEXT "StopBits", 0, 471, 161, 27, 8, SS_LEFT, WS_EX_LEFTLTEXT "Parity", 0, 299, 162, 18, 8, SS_LEFT, WS_EX_LEFTAUTOCHECKBOX "fParity", 0, 401, 162, 35, 8, 0, WS_EX_LEFTAUTOCHECKBOX "CTS", 0, 296, 202, 30, 8, 0, WS_EX_LEFTAUTOCHECKBOX "DSR", 0, 365, 202, 31, 8, 0, WS_EX_LEFTAUTOCHECKBOX "DTR", 0, 436, 202, 31, 8, 0, WS_EX_LEFTAUTOCHECKBOX "XON/XOFF", 0, 507, 202, 53, 8, 0, WS_EX_LEFTLTEXT "ms", 0, 131, 228, 10, 8, SS_LEFT, WS_EX_LEFTLTEXT "ms", 0, 562, 237, 10, 8, SS_LEFT, WS_EX_LEFTLTEXT "XonChar", 0, 293, 238, 28, 8, SS_LEFT, WS_EX_LEFTLTEXT "XoffChar", 0, 383, 238, 28, 8, SS_LEFT, WS_EX_LEFTLTEXT "Timeouts", 0, 478, 238, 30, 8, SS_LEFT, WS_EX_LEFTGROUPBOX "Receive Data", RDBOX, 15, 10, 235, 120, 0, WS_EX_LEFTEDITTEXT RDTEXT, 20, 25, 225, 75, ES_AUTOHSCROLL | ES_MULTILINE | ES_READONLY, WS_EX_LEFTAUTORADIOBUTTON "Char", RDCHAR, 26, 112, 31, 8, WS_GROUP, WS_EX_LEFTAUTORADIOBUTTON "Hex", RDHEX, 80, 112, 29, 8, 0, WS_EX_LEFTPUSHBUTTON "Clear", RDCLEAR, 196, 108, 45, 14, 0, WS_EX_LEFTAUTORADIOBUTTON "Char", SDCHAR, 26, 208, 31, 8, WS_GROUP, WS_EX_LEFTAUTORADIOBUTTON "Hex", SDHEX, 82, 208, 29, 8, 0, WS_EX_LEFTPUSHBUTTON "Clear", SDCLEAR, 132, 204, 45, 14, 0, WS_EX_LEFTPUSHBUTTON "Send", SDSEND, 196, 204, 45, 14, 0, WS_EX_LEFTAUTOCHECKBOX "Auto send", SDAS, 26, 228, 48, 8, 0, WS_EX_LEFTEDITTEXT SDASTIME, 86, 225, 40, 14, ES_RIGHT | ES_AUTOHSCROLL, WS_EX_LEFTCOMBOBOX SETCOMNO, 337, 27, 95, 30, CBS_DROPDOWN | CBS_HASSTRINGS, WS_EX_LEFTAUTORADIOBUTTON "Synchronous ", CTSYN, 326, 75, 59, 8, WS_GROUP, WS_EX_LEFTAUTORADIOBUTTON "Asynchronous ", CTASY, 472, 77, 63, 8, 0, WS_EX_LEFTCOMBOBOX SETBR, 337, 120, 48, 30, CBS_DROPDOWN | CBS_HASSTRINGS, WS_EX_LEFTEDITTEXT SDTEXT, 20, 147, 227, 45, ES_AUTOHSCROLL, WS_EX_LEFTEDITTEXT SETXONC, 325, 235, 40, 14, ES_AUTOHSCROLL, WS_EX_LEFTEDITTEXT SETXOFFC, 417, 235, 40, 14, ES_AUTOHSCROLL, WS_EX_LEFTEDITTEXT SETTO, 512, 235, 40, 14, ES_AUTOHSCROLL, WS_EX_RIGHTCOMBOBOX SETPAR, 338, 160, 48, 30, CBS_DROPDOWN | CBS_HASSTRINGS, WS_EX_LEFTCOMBOBOX SETSB, 512, 159, 48, 30, CBS_DROPDOWN | CBS_HASSTRINGS, WS_EX_LEFTCOMBOBOX SETBS, 512, 117, 48, 30, CBS_DROPDOWN | CBS_HASSTRINGS, WS_EX_LEFTPUSHBUTTON "Open Port", SETOP, 297, 272, 45, 14, 0, WS_EX_LEFTPUSHBUTTON "Close Port", SETCP, 387, 272, 45, 14, 0, WS_EX_LEFTDEFPUSHBUTTON "Stop I/O", SETSO, 473, 271, 45, 14, 0, WS_EX_LEFT}//// Manifest resources//LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL1 RT_MANIFEST".\\manifest.xml"【源码】manifest.xml< ? xml version = "1.0" encoding = "UTF-8" standalone = "yes" ? ><assembly xmlns = "urn:schemas-microsoft-com:asm.v1" manifestVersion = "1.0"><dependency><dependentAssembly><assemblyIdentity type = "win32" name = "mon-Controls" version = "6.0.0.0" processorArchitecture = "*" publicKeyToken = "6595b64144ccf1df" language = "*" / >< / dependentAssembly>< / dependency><trustInfo xmlns = "urn:schemas-microsoft-com:asm.v3"><security><requestedPrivileges><requestedExecutionLevel level = "asInvoker" uiAccess = "false" / > < / requestedPrivileges> < / security>< / trustInfo>< / assembly>。
vb编写的串口调试程序
vb编写的串口调试程序(源代码)作者:Javen_yue,2005-5-17 13:23:00 发表于:《自动化软件论坛》共有8人回复,2108次点击加为好友播客博客发送留言小弟刚入行不久,写了个小程序,希望各位大侠能帮我指点一二,谢谢!Public countRX As IntegerPublic countTX As IntegerPublic num As BytePublic setport As StringPrivate Sub Combo1_Click()openportEnd SubPrivate Sub combo2_click()openportEnd SubPrivate Sub combo3_click()openportEnd SubPrivate Sub combo4_click()openportEnd SubPrivate Sub combo5_click()openportEnd SubPrivate Sub Command3_Click()Text1.Text = ""End SubPrivate Sub Command4_Click() '手动发送Dim send() As ByteDim i As IntegerDim length As IntegerDim a() As ByteDim b As Bytelength = Len(Text2.Text)If length > 0 ThenReDim a(length - 1)ReDim send(length - 1)End Ifsend = Text2.TextcountTX = countTX + lengthIf Check2.Value = 0 ThenMSComm1.Output = send'countTX = countTX + MSComm1.OutBufferCountElsei = 0b = 0Do While i <= (length - 1) * 2If ((send(i) >= 48 And send(i) <= 57) Or (send(i) >= 65 And send(i) <= 70) Or (send(i) >= 97 And s end(i) <= 102)) ThenIf (send(i) >= 97 And send(i) <= 102) Thena(b) = send(i) - 32Elsea(b) = send(i)End IfElseIf b > 0 ThenReDim Preserve a(b - 1)End IfExit DoEnd Ifi = i + 2b = b + 1DoEventsLoopMSComm1.Output = aEnd IfLabel5.Caption = "TX:" & countTX End SubPrivate Sub command5_Click()Text2.Text = " "End SubPrivate Sub Command6_Click() Label4.Caption = "RX:0 "Label5.Caption = "TX:0 "End SubPrivate Sub Form_Load()Combo1.ListIndex = 0 'initialCombo2.ListIndex = 0Combo3.ListIndex = 0Combo4.ListIndex = 0Combo5.ListIndex = 0End SubSub openport()'Dim num As Byte'Dim setport As StringOn Error GoTo msgnum = Combo1.ListIndex + 1If MSComm1.PortOpen = True Then 'MsgBox ("没有发现串口或被占用") MSComm1.PortOpen = FalseEnd IfmPort = numsetport = Combo2.Text + ","If Combo3.ListIndex = 0 Thensetport = setport + "N,"End IfIf Combo3.ListIndex = 1 Thensetport = setport + "O,"End IfIf Combo3.ListIndex = 2 Thensetport = setport + "E,"End IfIf Combo4.ListIndex = 0 Thensetport = setport + "8,"End IfIf Combo4.ListIndex = 1 Thensetport = setport + "7,"End IfIf Combo5.ListIndex = 0 Thensetport = setport + "1"End IfIf Combo5.ListIndex = 1 Thensetport = setport + "2"End IfMSComm1.Settings = setportMSComm1.PortOpen = True'If MSComm1.PortOpen = True Then'Label3.Caption = "stats:" & num & ",open" & "," & setport'Else' Label3.Caption = "stats:" & num & "close" & "," & setport 'End Ifmsg:End SubSub command1_click()On Error GoTo msgMSComm1.PortOpen = Truemsg: MsgBox ("port had opened")End SubSub command2_click()MSComm1.PortOpen = FalseEnd SubPrivate Sub Timer1_Timer()If MSComm1.PortOpen = True ThenShape1.FillColor = RGB(0, 255, 0)Command1.Visible = Falsecommand2.Visible = TrueLabel3.Caption = "stats:" & num & ",open" & "," & setport ElseShape1.FillColor = RGB(255, 0, 0)Command1.Visible = Truecommand2.Visible = FalseLabel3.Caption = "stats:" & "close" & "!"End IfEnd SubPrivate Sub Timer2_Timer() '接收信号Dim recBuf() As ByteDim recCnt As IntegerDim str As StringDim i As IntegerDim str1 As String'Dim countRX As Integer' Do Until MSComm1.InBufferCount <> 0' DoEvents' LooprecCnt = MSComm1.InBufferCountcountRX = recCnt + countRXIf recCnt > 0 ThenReDim recBuf(recCnt)recBuf = MSComm1.Inputstr = "" ' CStr(Now) & " rec:"If Check1.Value = 1 ThenFor i = 0 To recCnt - 1str = str & CStr(Hex(recBuf(i)))Next iElseFor i = 0 To recCnt - 1str = str & Chr(recBuf(i))Next iEnd IfText1.Text = Text1.Text + strLabel4.Caption = "RX:" & countRXEnd IfEnd SubPrivate Sub Timer3_Timer() '自动发送Dim length As Integerlength = Len(Text2.Text)Timer3.Interval = Text3.TextIf (Check3.Value = 1 And length <> 0) Then Dim send() As ByteDim i As IntegerDim a() As ByteDim b As ByteReDim a(length - 1)ReDim send(length - 1)countTX = countTX + lengthsend = Text2.TextIf Check2.Value = 0 ThenMSComm1.Output = sendElsei = 0b = 0Do While i <= (length - 1) * 2If ((send(i) >= 48 And send(i) <= 57) Or (send(i) >= 65 And send(i) <= 70) Or (send(i) >= 97 And s end(i) <= 102)) ThenIf (send(i) >= 97 And send(i) <= 102) Thena(b) = send(i) - 32Elsea(b) = send(i)End IfElseIf b > 0 ThenReDim Preserve a(b - 1)End IfExit DoEnd Ifi = i + 2b = b + 1DoEventsLoop。