VB串口调试助手源代码

合集下载

vb.net编写的简易串口调试程序

vb.net编写的简易串口调试程序

编写的简易串口调试程序Imports SystemImports System.IO.PortsPublic Class Form1Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load'获取计算机有效串口Dim ports As String() = SerialPort.GetPortNames() '必须用命名空间,用SerialPort,获取计算机的有效串口Dim port As StringFor Each port In portsportnamebox.Items.Add(port) '向combobox中添加项Next port'初始化界面baudratebox.Text = baudratebox.Items(2) '注释和不注释的地方可以替换portnamebox.Text = portnamebox.Items(0)'baudratebox.SelectedIndex() = 2' portnamebox.SelectedIndex() = 0Serial_Port1() '初始化串口Label3.Text = SerialPort1.IsOpenstatuslabel.Text = "串口未连接"statuslabel.ForeColor = Color.Redsendbox.Text = "123"receivebytes.Text = "0"linecheck.Enabled = Truetimebox.Enabled = TrueEnd SubPrivate Sub Serial_Port1() '设置串口参数'SerialPort1.BaudRate = Val(baudratebox.Text) '波特率'SerialPort1.PortName = portnamebox.Text '串口名称SerialPort1.PortName = portnamebox.SelectedItemSerialPort1.BaudRate = Val(baudratebox.SelectedItem)SerialPort1.DataBits = 8'数据位SerialPort1.StopBits = IO.Ports.StopBits.One '停止位SerialPort1.Parity = IO.Ports.Parity.None '校验位End Sub'关闭串口连接Private Sub closebtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closebtn.Click TrySerialPort1.Close() '关闭串口Label3.Text = SerialPort1.IsOpenIf SerialPort1.IsOpen = False Thenstatuslabel.Text = "串口未连接"statuslabel.ForeColor = Color.Redreceivebox.Text = ""receivebytes.Text = ""End IfCatch ex As ExceptionMessageBox.Show(ex.Message)End TryEnd Sub'打开串口连接Private Sub openbtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles openbtn.Click TrySerialPort1.Open() '打开串口Label3.Text = SerialPort1.IsOpenIf SerialPort1.IsOpen = True Thenstatuslabel.Text = "串口已连接"statuslabel.ForeColor = Color.GreenEnd IfCatch ex As ExceptionMessageBox.Show(ex.Message)End TryEnd Sub'手动发送数据Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Clicksend()End Sub'触发接收事件,接收数据Public Sub Sp_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceivedMe.Invoke(New EventHandler(AddressOf Sp_Receiving)) '调用接收数据函数End Sub'接收数据过程Private Sub Sp_Receiving(ByVal sender As Object, ByVal e As EventArgs)' Dim strIncoming As ByteDim strIncoming As IntegerDim str1() As StringDim str2() As StringDim bytes() As ByteDim i As IntegerTryThreading.Thread.Sleep(100) '添加的延时receivebytes.Text = Str(Val(receivebytes.Text) + SerialPort1.BytesToRead)If SerialPort1.BytesToRead > 0ThenReDim bytes(SerialPort1.BytesT oRead)'strIncoming = Convert.T oByte(SerialPort1.ReadByte())If receivecheck.Checked = True ThenstrIncoming = SerialPort1.ReadByte()bytes(0) = strIncomingFor i = 1To SerialPort1.BytesToReadstrIncoming = SerialPort1.ReadByte() '读取缓冲区中的数据bytes(i) = strIncomingNext' SerialPort1.Write(sendbox.Text)'发送数据SerialPort1.DiscardInBuffer()str1 = Split(BitConverter.ToString(bytes), "-")ReDim str2(str1.Length - 1) '去除str1中最后的字符For i = 0To str1.Length - 2str2(i) = str1(i)Nextreceivebox.Text = receivebox.Text & Join(str2, " ")'BitConverter.T oString(bytes)Elsereceivebox.Text = receivebox.Text & SerialPort1.ReadExisting()End IfEnd IfCatch ex As ExceptionMessageBox.Show(ex.Message)End TryEnd Sub'更改串口设置Private Sub portnamebox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles portnamebox.SelectedIndexChangedTrySerial_Port1()Catch ex As ExceptionMessageBox.Show(ex.Message)End TryEnd Sub'清空接收区Private Sub clearbtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles clearbtn.Clickreceivebox.Text = ""End Sub'定时发送数据Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.TickTimer1.Interval = timebox.Textsend()End Sub'选择定时发送的触发事件Private Sub timecheck_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timecheck.CheckedChangedIf timecheck.Checked = True ThenIf timebox.Text = ""ThenMsgBox("时间间隔不能为0")timecheck.Checked = FalseElsesend()timebox.Enabled = FalseEnd IfElsetimebox.Enabled = TrueEnd IfEnd SubPublic Sub send() '发送数据过程Dim databyte() As ByteDim str1() As StringDim str2 As StringDim str3 As StringDim i As IntegerTryIf sendcheck.Checked = False Then'不按照16进制发送'timecheck.Enabled = TrueIf linecheck.Checked = False Then'判断是否选中分行发送SerialPort1.Write(sendbox.Text)ElseSerialPort1.WriteLine(sendbox.Text)End IfElse'按照16进制发送If InStr(sendbox.Text, " ") Then'判断是否有空格str1 = Split(sendbox.Text)str2 = Join(str1, "")Elsestr2 = sendbox.TextEnd IfIf str2.Length Mod2 = 0Then'判断字符串字节数是否为偶数ReDim databyte(str2.Length / 2) '重新定义数组For i = 0To str2.Length / 2 - 1databyte(i) = Convert.ToByte(Mid(str2, 2 * i + 1, 2), 16) '两个字符转换为一个16进制字节'databyte(i) = Val(Mid(str2, 2 * i + 1, 2))NextSerialPort1.Write(databyte, 0, databyte.Length - 1)sendbytes.Text = Str(Val(sendbytes.Text) + databyte.Length - 1)Elsestr3 = Mid(str2, 1, (str2.Length - 1)) & "0"& Mid(str2, str2.Length)ReDim databyte(str3.Length / 2)For i = 0To str3.Length / 2 - 1databyte(i) = Convert.ToByte(Mid(str3, 2 * i + 1, 2), 16)NextSerialPort1.Write(databyte, 0, databyte.Length - 1)sendbytes.Text = Str(Val(sendbytes.Text) + databyte.Length - 1)End If'databyte = System.Text.Encoding.Default.GetBytes(sendbox.Text)把每个字符转换成字节End IfCatch ex As ExceptionMessageBox.Show(ex.Message)End TryEnd Sub'是否按照16进制发送,如果是换行将不可选。

VB串口通信程序代码

VB串口通信程序代码

vb中怎样用mscomm控件实现串口通信本问分两部分均来自第一部分jessezappy(晶晶)================================================================================== If MSComm1.PortOpen Then MSComm1.PortOpen = FalsemPort = 1 '假定是用COM1口' 设定传输速率等,可依照您的需求更改MSComm1.Settings = "9600,N,8,1"MSComm1.PortOpen = True'---------初始化Modem-------------MSComm1.Output = "ATZ"MSComm1.Output = "AT&F"MSComm1.Output = "ATE0"MSComm1.Output = "ATM1"MSComm1.Output = "ATQ0"MSComm1.Output = "ATV0"'--------------------------拨号-------------MSComm1.Output ="ATDT163" '拨163'---------------------------接通后MSComm1.Output ="SDFJDKSJLKFA" '发送字符串'---------------------Private Sub MSComm1_OnComm() '用串口事件捕捉数据..If MSComm1.InBufferCount Then' 通讯埠中假如有资料的话, 则读取进来InStringB = InStringB & MSComm1.Input' 如果资料中有Chr(13) 和Chr(10) 的话, 则显示出来If InStr(InStringB, vbCrLf) Theninstring = instring & InStringBAddText Text3, InStringB, FalseInStringB = ""End IfEnd IfEND SUB'-------------------------挂断--------MSComm1.PortOpen = False '这个挂断方法不能适用所有MODEM,我正在研究...通用办法================================================================================================第二部分:===========================================================================最后借你一篇文章看,作者不是我,里面的不一定都对..'-----------------------------------------------------------VB Mscomm控件应用江苏戚墅堰机车车辆厂设计处(213011) 李秉璋--------------------------------------------------------------------------------Visual Basic 6.0(以下简称VB) 是一种功能强大、简单易学的程序设计语言。

VB串口通信程序代码

VB串口通信程序代码

vb中怎样用mscomm控件实现串口通信本问分两部分均来自第一部分jessezappy(晶晶)================================================================================== If MSComm1.PortOpen Then MSComm1.PortOpen = FalsemPort = 1 '假定是用COM1口' 设定传输速率等,可依照您的需求更改MSComm1.Settings = "9600,N,8,1"MSComm1.PortOpen = True'---------初始化Modem-------------MSComm1.Output = "ATZ"MSComm1.Output = "AT&F"MSComm1.Output = "ATE0"MSComm1.Output = "ATM1"MSComm1.Output = "ATQ0"MSComm1.Output = "ATV0"'--------------------------拨号-------------MSComm1.Output ="ATDT163" '拨163'---------------------------接通后MSComm1.Output ="SDFJDKSJLKFA" '发送字符串'---------------------Private Sub MSComm1_OnComm() '用串口事件捕捉数据..If MSComm1.InBufferCount Then' 通讯埠中假如有资料的话, 则读取进来InStringB = InStringB & MSComm1.Input' 如果资料中有Chr(13) 和Chr(10) 的话, 则显示出来If InStr(InStringB, vbCrLf) Theninstring = instring & InStringBAddText Text3, InStringB, FalseInStringB = ""End IfEnd IfEND SUB'-------------------------挂断--------MSComm1.PortOpen = False '这个挂断方法不能适用所有MODEM,我正在研究...通用办法================================================================================================第二部分:===========================================================================最后借你一篇文章看,作者不是我,里面的不一定都对..'-----------------------------------------------------------VB Mscomm控件应用江苏戚墅堰机车车辆厂设计处(213011) 李秉璋--------------------------------------------------------------------------------Visual Basic 6.0(以下简称VB) 是一种功能强大、简单易学的程序设计语言。

Visual+Basic串口通讯调试方法

Visual+Basic串口通讯调试方法

Visual Basic串口通讯调试方法现有电子秤一台,使用串口与计算机进行通讯。

编写VB程序来访问串口,达到读取电子秤上显示的数据。

该电子秤为BE01型仪表,输出为RS-232C标准接口,波特率为300-9600、偶校验、7个数据位、2个停止位。

所有字符均发送11位ASCII码,一个起始位。

在VB 中与串口通讯需要引入控件MSComm串口通讯控件(在Microsoft Comm Control 6.0中)。

具体程序如下:控件简称:MSCDim Out(12) As Byte '接收var中的值Dim var As Variant '接收MSC.input中的数值Dim nRece As Integer '计算MSC.inputbuffer的个数Dim i As Integer, j As Integer '随即变量,计算循环****************************************************************************Private Sub Form_Load()ClearTextWith MSC.CommPort = 1 '设置Com1为通信端口.Settings = "9600,E,7,2" '设置通信端口参数9600赫兹、偶校验、7个数据位、1个停止位.(这里需要进一步说明的是:.Setting=”BBBB,P,D,S”。

含义是:B:Baud Rate(波特率);P:Parity(奇偶);D:Data Bit;S:Stop Bit).InBufferSize = 40 '设置缓冲区接收数据为40字节.InputLen = 1 '设置Input一次从接收缓冲读取字节数为1.RThreshold = 1 '设置接收一个字节就产生OnComm事件End WithEnd Sub****************************************************************************Private Sub ClearText()Text3.Text = ""Text2.Text = "5"Text1.Text = ""End SubPrivate Sub Command1_Click()ClearText' nRece = 0 '计数器清零With MSC.InputMode = comInputModeBinary '设置数据接收模式为二进制形式.InBufferCount = 0 '清除接收缓冲区If Not .PortOpen Then.PortOpen = True '打开通信端口End IfEnd WithEnd SubPrivate Sub MSC_OnComm()DelayTime ‘用来延续时间ClearTextWith MSCSelect Case .CommEvent '判断通信事件Case comEvReceive: '收到Rthreshold个字节产生的接收事件SwichVar 1If Out(1) = 2 Then '判断是否为数据的开始标志.RThreshold = 0 '关闭OnComm事件接收End IfDoDoEventsLoop Until .InBufferCount >= 3 '循环等待接收缓冲区>=3个字节' nRece = nRece + 1For i = 2 To 12SwichVar iText1.Text = Text1.Text & Chr(Out(i))NextText1.Text = LTrim(Text1.Text)Text2.Text = Text2.Text & CStr(nRece).RThreshold = 1 '打开MSComm事件接收Case Else' .PortOpen = FalseEnd SelectEnd WithEnd Sub****************************************************************************Private Sub DelayTime()Dim bDT As BooleanDim sPrevious As Single, sLast As SinglebDT = TruesPrevious = Timer (Timer可以计算从子夜到现在所经过的秒数,在Microsoft Windows中,Timer函数可以返回一秒的小数部分)Do While bDTIf Timer - sPrevious >= 0.3 Then bDT = FalseLoopbDT = TrueEnd Sub(通信传输速率为9600bps,则最快速度1.04ms发送一个字节,仪表每秒发送50帧数据,每帧数据有4个字节,即每秒发送200个字节,平均5.0ms 发送一个字节,连续读取串口数据时要在程序中添加循环等待程序)Private Sub SwichVar(ByVal nNum As Integer)DelayTimevar = Nullvar = MSC.InputOut(nNum) = var(0)End Sub(设置接收数据模式采用二进制形式,即InputMode=comInputModeBinary,但用Input 属性读取数据时,不能直接赋值给Byte 类型变量,只能通过先赋值给一个Variant 类型变量,返回一个二进制数据的数组,再转换保存到Byte类型数变量中。

VB串口通信(附图教程)

VB串口通信(附图教程)

界面如下:代码如下:Private Sub Form_Load()If MSComm1.PortOpen = True Then MSComm1.PortOpen = False ElseEnd IfCombo1.AddItem "COM1"Combo1.AddItem "COM2"Combo1.AddItem "COM3"Combo1.AddItem "COM4"Combo1.AddItem "COM5"Combo1.AddItem "COM6"Combo1.AddItem "COM7"Combo1.AddItem "COM8"Combo1.AddItem "COM9"Combo1.AddItem "COM10" Combo1.AddItem "COM11" Combo1.AddItem "COM12"Combo1.AddItem "COM13"Combo1.AddItem "COM14"Combo1.AddItem "COM15"Combo1.AddItem "COM16"Combo1.ListIndex = 2Combo2.AddItem "256000"Combo2.AddItem "128000"Combo2.AddItem "115200"Combo2.AddItem "57600"Combo2.AddItem "38400"Combo2.AddItem "28800"Combo2.AddItem "19200"Combo2.AddItem "14400"Combo2.AddItem "12800"Combo2.AddItem "11520"Combo2.AddItem "9600"Combo2.AddItem "4800"Combo2.AddItem "2400"Combo2.AddItem "1200"Combo2.AddItem "600"Combo3.AddItem "无None"Combo3.AddItem "奇Odd"Combo3.AddItem "偶Even"Combo4.AddItem "4"Combo4.AddItem "5"Combo4.AddItem "6"Combo4.AddItem "7"Combo4.AddItem "8"Combo5.AddItem "1"Combo5.AddItem "2"mPort = Combo1.ListIndex + 1 MSComm1.Settings = "9600,n,8,1"ComOpen.Caption = "打开串口"Shape1.FillColor = &HFFFFC0End SubPrivate Sub ComOpen_Click()On Error GoTo uerror '发现错误跳转到错误处理If ComOpen.Caption = "关闭串口" ThenMSComm1.PortOpen = FalseComOpen.Caption = "打开串口" '按钮文字改变Shape1.FillColor = &HFFFFC0 '灯颜色改变ElseMSComm1.PortOpen = TrueComOpen.Caption = "关闭串口"Shape1.FillColor = &HFFEnd IfExit Subuerror:msg$ = "无效端口号" '错误显示Title$ = "串口调试助手"X = MsgBox(msg$, 48, Title$) '48标示显示警告图标End SubPrivate Sub MSComm1_OnComm()Dim BytReceived() As ByteDim strBuff As StringDim i As IntegerSelect Case mEvent '事件发生Case 2ClsMSComm1.InputLen = 0 '读入缓冲区全部内容strBuff = MSComm1.Input '读入到缓冲区Label10.Caption = Label10.Caption + Len(strBuff) '接收计数If MSComm1.InputMode = comInputModeBinary ThenBytReceived() = strBuff '如果是二进制接收模式则进行数据处理,否则直接显示字符串For i = 0 To UBound(BytReceived)If Len(Hex(BytReceived(i))) = 1 ThenstrData = strData & "0" & Hex(BytReceived(i)) & " " '如果只有一个字符,则前补0,如F显示0F,最后补空格Else '方便显示观察如:00 0F FEstrData = strData & Hex(BytReceived(i)) & " "End IfNextTextReceive = TextReceive & strDatastrData = ""ElseTextReceive = TextReceive & strBuffEnd IfEnd SelectEnd SubPrivate Sub ComSend1_Click() '手动发送Dim Temp(0) As ByteDim strBuff As StringIf Option1.Value = True Then '如果显示16进制发送则进行16进制处理,这里只发送一个Temp(0) = "&H" & TextSendMSComm1.Output = Temp '发送一个16进制ElsestrBuff = TextSendEnd IfIf MSComm1.PortOpen = False ThenMsgBox "请打开串口"End IfOn Error GoTo uerrorMSComm1.Output = strBuffLabel11.Caption = Label11.Caption + Len(strBuff) '发送计数uerror:End SubPrivate Sub ComSend2_Click()If ComSend2.Caption = "自动发送" ThenComSend2.Caption = "关闭自动发送"Timer1.Interval = TextTime.TextTimer1.Enabled = TrueElseComSend2.Caption = "自动发送"Timer1.Enabled = FalseEnd IfEnd SubPrivate Sub ComClean1_Click()TextSend.Text = "" '清空发送窗口End SubPrivate Sub Option3_Click()MSComm1.InputMode = comInputModeBinary '选择接收方式End SubPrivate Sub Option4_Click()MSComm1.InputMode = comInputModeText '选择接收方式End SubPrivate Sub Timer1_Timer()Call ComSend1_Click '定时调用手动发送End SubPrivate Sub Timer2_Timer()If Combo3 = "无None" ThenMSComm1.Settings = Str(Combo2) + "N" + Str(Combo4) + Str(Combo5) ElseIf Combo3 = "奇Odd" ThenMSComm1.Settings = Str(Combo2) + "O" + Str(Combo4) + Str(Combo5) ElseIf Combo3 = "偶Even" ThenMSComm1.Settings = Str(Combo2) + "E" + Str(Combo4) + Str(Combo5) End IfEnd SubPrivate Sub Combo1_Click()If MSComm1.PortOpen = True Then '如果串口打开先关闭后再进行其他操作MSComm1.PortOpen = FalseEnd IfmPort = Combo1.ListIndex + 1 '读取com口号End SubPrivate Sub ComClean3_Click()Label10.Caption = 0Label11.Caption = 0End SubPrivate Sub ComClean2_Click()TextReceive.Text = "" '接收窗口End Sub功能上:实现了字符串的发送和接收,8位数据的十六进制发送和接收,有端口,波特率等设置。

VB串口通信源程序[1]

VB串口通信源程序[1]

Private Sub Form_Load()'设置打开端口If OpenPort(3) = False ThenMsgBox "串口打开失败!"End IfEnd SubPrivate Sub Command1_Click()Dim sBuf(2) As BytesBuf(0) = &H55sBuf(1) = &H31sBuf(2) = &HFFIf SendByte(sBuf) = False ThenEnd IfEnd Sub'收到数据产生MSComm事件Private Sub MSComm1_OnComm()Dim i As IntegerDim rBuf() As ByterBuf = MSComm1.InputFor i = 0 To UBound(rBuf)Debug.Print rBuf(i)Next iEnd Sub'串口初始化Private Function OpenPort(PortNum As Integer) As BooleanOn Error GoTo ErrExit '出错转移到ErrExit处理With Me.MSComm1.CommPort = PortNum '端口号.Settings = "9600,n,8,1" '波特率=9600bps;n(无奇偶校验)e(偶校验)o(奇校验);8位数据位;1位停止位.InputMode = 1 '采用二进制数据传输.NullDiscard = False 'NULL字符从端口传送到接受缓冲区.DTREnable = False 'DTR线无效.EOFEnable = False '不寻找EOF符.RTSEnable = False 'RTS线无效.InBufferCount = 0 '清空接受缓冲区.OutBufferCount = 0 '清空传输缓冲区.SThreshold = 0 '不产生MSComm事件.RThreshold = 1 '产生MSComm事件.InputLen = 0 '当输入占用时,告诉控件读入整个缓冲区。

串口测试软件 VB代码

串口测试软件 VB代码

串口测试软件 VB代码部分代码如下:Dim Port 'COM端口检测Dim p 'COM端口检测Dim s(255) As Integer '端口1-255Dim s1(255) '端口1-255Dim str '奇偶校验传递符Dim portstr As StringPrivate Sub Command1_Click()On Error Resume Next'---------------端口参数设置--------------- If Command1.Caption = "打开串口(&O)" Then Command1.Caption = "关闭串口(&C)"Command2.Enabled = TrueIf Combo3.Text = "无" Thenstr = "n"End IfIf Combo3.Text = "奇校验" Thenstr = "o"End IfIf Combo3.Text = "偶校验" Thenstr = "e"End IfIf Combo3.Text = "空格" Thenstr = "s"End IfIf Combo3.Text = "标记" Thenstr = "s"End If'---------------端口识别---------------For Port = 1 To 255s1(Port) = "COM" & PortIf Combo5.Text = s1(Port) ThenmPort = PortMSComm1.PortOpen = TrueIf MSComm1.PortOpen = True ThenRichTextBox2 = "COM" & Port & "已成功打开。

vb.net串口编程

vb.net串口编程

Imports System.IO.PortsImports System.TextPublic Class JCFrmDim RS232 As SerialPortPrivate Sub JCFrm_Load(ByV al sender As System.Object, ByV al e As System.EventArgs) Handles MyBase.LoadDim mBaudRate As IntegerDim mParity As IO.Ports.ParityDim mDataBit As IntegerDim mStopbit As IO.Ports.StopBitsDim mPortName As StringmPortName = "com1" '欲开启的通讯端口mBaudRate = 9600 '比特率mParity = Parity.None '校验位检查设定mDataBit = 8 '数据位设定值mStopbit = StopBits.One '停止位设定值'建立一个通讯端口对象RS232 = New IO.Ports.SerialPort(mPortName, mBaudRate, mParity, mDataBit, mStopbit)If Not RS232.IsOpen Then '尚未开启RS232.Open() '开启通讯端口ElseMsgBox("~~通讯端口已开启~~", MsgBoxStyle.Critical Or MsgBoxStyle.OkCancel)EndEnd IfPrivate Sub readBtn1_Click(ByV al sender As System.Object, ByV al e As System.EventArgs) Handles readBtn1.ClickTryIf readBtn1.Text = "读取" ThenTimer1.Interval = 100Timer1.Enabled = TruereadBtn1.Text = "确定"readBtn2.Enabled = False '检测A W1的值,不能同时检测A W2的值。

串口调试助手源码

串口调试助手源码

串口调试助手程序框架(一)【截图】【源码】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串口通信源代码

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 Combo1_Click()If MSComm1.PortOpen=True Then'如果串口打开先关闭后再进行其他操作MSComm1.PortOpen=FalseEnd IfmPort=Combo1.ListIndex+1'读取com口号End SubPrivate Sub Command1_Click()'发送到窗口现在时间time1=Timedate1=Datenow1=NowText1.Text=Hour(Time)&"时"&Minute(Time)&"分"& Second(Time)&"秒"&vbNewLine&Year(Date)&"年"& Month(Date)&"月"&Day(Date)&"日"End SubPrivate Sub Command2_Click()Text1.Text="详情参考"&vbNewLine&"淘宝店铺:/"'说明内容输出End SubPrivate Sub Command3_Click()'清空文本内容Text1.Text=""'接收窗口End SubPrivate Sub Command4_Click()'清空文本内容Text2.Text=""'发送窗口End SubPrivate Sub Command5_Click()On Error GoTo uerror'发现错误跳转到错误处理If Command5.Caption="关闭串口"ThenMSComm1.PortOpen=FalseCommand5.Caption="打开串口"'按钮文字改变Shape1.FillColor=&HFFFFC0'灯颜色改变ElseMSComm1.PortOpen=TrueCommand5.Caption="关闭串口"Shape1.FillColor=&HFFEnd IfExit Subuerror:msg$="无效端口号"'错误显示Title$="串口调试助手"x=MsgBox(msg$,48,Title$)'48标示显示警告图标End SubPrivate Sub Command6_Click()Dim Temp(0)As ByteDim strBuff As StringIf Option5.Value=True Then'如果显示16进制发送则进行16进制处理,这里只发送一个Temp(0)="&H"&Text2MSComm1.Output=Temp'发送一个16进制ElsestrBuff=Text2End IfIf MSComm1.PortOpen=False ThenMsgBox"请打开串口"End IfOn Error GoTo uerrorMSComm1.Output=strBuffLabel11.Caption=Label11.Caption+Len(strBuff)'发送计数uerror:End SubPrivate Sub Command7_Click()'自动发送If Command7.Caption="自动发送"Then Command7.Caption="关闭自动发送"Timer2.Interval=Text3.TextTimer2.Enabled=TrueElseCommand7.Caption="自动发送"Timer2.Enabled=FalseEnd IfEnd SubPrivate Sub Command8_Click()'清零计数器Label10.Caption=0Label11.Caption=0End SubPrivate Sub Form_Load()If MSComm1.PortOpen=True ThenMSComm1.PortOpen=FalseElseEnd IfCombo1.AddItem"COM1"Combo1.AddItem"COM2"Combo1.AddItem"COM3"Combo1.AddItem"COM4"Combo1.AddItem"COM5"Combo1.AddItem"COM6"Combo1.AddItem"COM7"Combo1.AddItem"COM8"Combo1.AddItem"COM9"Combo1.AddItem"COM10"Combo1.AddItem"COM11"Combo1.AddItem"COM12"Combo1.AddItem"COM13"Combo1.AddItem"COM14"Combo1.AddItem"COM15"Combo1.AddItem"COM16"Combo1.ListIndex=0mPort=Combo1.ListIndex+1MSComm1.Settings="9600,n,8,1"Command5.Caption="打开串口"Shape1.FillColor=&HFFFFC0Option2.Value=TrueOption3.Value=TrueCombo2.AddItem"256000"Combo2.AddItem"128000"Combo2.AddItem"115200"Combo2.AddItem"57600"Combo2.AddItem"38400"Combo2.AddItem"28800"Combo2.AddItem"19200"'Combo2.AddItem"14400"'Combo2.AddItem"12800"'Combo2.AddItem"11520"Combo2.AddItem"9600"Combo2.AddItem"4800"Combo2.AddItem"2400"Combo2.AddItem"1200"Combo2.AddItem"600"Combo3.AddItem"无None"Combo3.AddItem"奇Odd"Combo3.AddItem"偶Even"Combo4.AddItem"4"Combo4.AddItem"5"Combo4.AddItem"6"Combo4.AddItem"7"Combo4.AddItem"8"Combo5.AddItem"1"Combo5.AddItem"2"End SubPrivate Sub Label12_Click()ShellExecute Me.hwnd,"open","",0,0,5End SubPrivate Sub Label13_Click()ShellExecute Me.hwnd,"open","", 0,0,SW_SHOWMAXIMIZEDEnd SubPrivate Sub MSComm1_OnComm()Dim BytReceived()As ByteDim strBuff As StringDim i As IntegerSelect Case mEvent'事件发生Case2ClsMSComm1.InputLen=0'读入缓冲区全部内容strBuff=MSComm1.Input'读入到缓冲区Label10.Caption=Label10.Caption+Len(strBuff)'接收计数If MSComm1.InputMode=comInputModeBinary Then BytReceived()=strBuff'如果是二进制接收模式则进行数据处理,否则直接显示字符串For i=0To UBound(BytReceived)If Len(Hex(BytReceived(i)))=1ThenstrData=strData&"0"& Hex(BytReceived(i))&""'如果只有一个字符,则前补0,如F显示0F,最后补空格Else'方便显示观察如:000F FEstrData=strData&Hex(BytReceived(i))&" "End IfNextText1=Text1&strDatastrData=""ElseText1=Text1&strBuffEnd IfEnd SelectEnd SubPrivate Sub Option1_Click()MSComm1.InputMode=comInputModeBinary'选择接收方式End SubPrivate Sub Option2_Click()MSComm1.InputMode=comInputModeTextEnd SubPrivate Sub Text3_Change()'Timer2.Interval=Text3.TextEnd SubPrivate Sub Timer1_Timer()If Combo3="无None"ThenMSComm1.Settings=Str(Combo2)+"N"+Str(Combo4)+ Str(Combo5)ElseIf Combo3="奇Odd"ThenMSComm1.Settings=Str(Combo2)+"O"+Str(Combo4)+ Str(Combo5)ElseIf Combo3="偶Even"ThenMSComm1.Settings=Str(Combo2)+"E"+Str(Combo4)+ Str(Combo5)End IfEnd SubPrivate Sub Timer2_Timer()Call Command6_Click'定时调用手动发送End Sub。

使用VB开发串口USB通信软件

使用VB开发串口USB通信软件

使用VB开发串口USB通信软件串口和USB通信软件是一种用于在计算机和外部设备之间进行数据传输的工具。

VB语言是一种适用于Windows平台的编程语言,可以使用VB 开发串口、USB通信软件。

串口通信是一种常见的数据传输方式,它通过计算机的串口(串行通信口)与外部设备进行连接。

在VB中,可以使用SerialPort类来实现串口通信。

下面是一个使用VB编写的串口通信软件的示例代码:```vbImports System.IO.PortsPrivate WithEvents SerialPort As New SerialPortPublic Sub New'设置串口参数SerialPort.PortName = "COM1"SerialPort.BaudRate = 9600SerialPort.Parity = Parity.NoneSerialPort.DataBits = 8SerialPort.StopBits = StopBits.OneEnd SubPublic Sub Open'打开串口SerialPort.OpenEnd SubPublic Sub Close'关闭串口SerialPort.CloseEnd SubPublic Sub WriteData(ByVal data As String)'向串口写入数据SerialPort.WriteLine(data)End SubPrivate Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs) HandlesSerialPort.DataReceived'串口接收到数据时触发的事件Dim data As String = SerialPort.ReadLine'处理接收到的数据Console.WriteLine("Received data: " & data)End SubEnd Class```USB通信是另一种常用的数据传输方式,它通过计算机的USB接口与外部设备进行连接。

VB串口调试助手源代码

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 ’转让控制权,以便让操作系统处理其它的事件。

串口调试助手源代码

串口调试助手源代码

串口调试助手预源代码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 的长度。

利用API进行串口通信VB代码

利用API进行串口通信VB代码

利用API进行串口通信VB代码01. Private Sub cmdSend_Click()02. '定义文件读写属性结构03. Dim sa As SECURITY_ATTRIBUTES04. '定义串口状态结构05. Dim typCommStat As COMSTAT06. '定义串口状态错误07. Dim lngError As Long08.09. '********打开串口********10. Dim hCF As Long11. hCF = CreateFile("COM4", _12. GENERIC_READ Or GENERIC_WRITE, 0, sa, _13. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL Or FILE_FLAG_OVERLAPPED, 0)14. Debug.Print "打开串口:" & hCF15.16. '********获取出错信息********17. Dim errNum As Long18. errNum = GetLastError()19. Debug.Print "出错信息:" & errNum20.21. '定义标志值22. Dim flag As Long23.24. '定义设备控制块25. Dim typDCB As DCB26.27. '********获取设备控制块********28. flag = GetCommState(hCF, typDCB)29. Debug.Print "获取串口DCB:" & flag30.31. typDCB.BaudRate = 2500 '定义波特率32. typDCB.Parity = NOPARITY '无校验位33. typDCB.ByteSize = 8 '数据位34. typDCB.StopBits = 0 '停止位 0/1/2 = 1/1.5/235.36. '********设置串口参数********37. flag = SetCommState(hCF, typDCB)38. Debug.Print "设置串口参数:" &flag39.40. '********设置缓冲区大小********41. flag = SetupComm(hCF, 1024, 1024)42. 'Debug.Print "设置缓冲区:" & flag43.44. '********清空读写缓冲区********45. flag = PurgeComm(hCF, PURGE_RXABORT Or PURGE_RXCLEAROr PURGE_TXABORT Or PURGE_TXCLEAR)46. 'Debug.Print "强制清空缓冲区:" & flag47.48. '定义超时结构体49. Dim typCommTimeouts As COMMTIMEOUTS50. typCommTimeouts.ReadIntervalTimeout = 0 '相邻两字节读取最大时间间隔(为0表示不使用该超时间隔)51. typCommTimeouts.ReadT otalTimeoutMultiplier = 0 '一个读操作的时间常数52. typCommTimeouts.ReadT otalTimeoutConstant = 0 '读超时常数53. typCommTimeouts.WriteTotalTimeoutMultiplier = 0 '一个写操作的时间常数(为0表示不使用该超时间隔)54. typCommTimeouts.WriteTotalTimeoutConstant = 0 '写超时常数(为0表示不使用该超时间隔)55.56. '********超时设置********57. flag = SetCommTimeouts(hCF, typCommTimeouts)58. 'Debug.Print "超时设置:" & flag59.60. '********发送数据********61. '定义要发送字节数62. Dim lngNumberofBytesToWrite As Long63. '定义实际发送字节数64. Dim lngNumberofBytesToWritten As Long65. '定义重叠结构体66. Dim typOverLapped As OVERLAPPED67.68. '定义发送数据69. Dim arrbytTest(0 To 23) As Byte70. '载波收发器同步头71. arrbytTest(0) = CByte(&H53)72. arrbytTest(1) = CByte(&H4E)73. arrbytTest(2) = CByte(&H44)74. '后续数据包长度75. arrbytTest(3) = CByte(&H14)76. '载波表预同步头77. arrbytTest(4) = CByte(&HFF)78. arrbytTest(5) = CByte(&HFF)79. arrbytTest(6) = CByte(&HFF)80. arrbytTest(7) = CByte(&HFF)81. arrbytTest(8) = CByte(&HFF)arrbytTest(9) = CByte(&HFF)83. '载波表帧同步头84. arrbytTest(10) = CByte(&H9)85. arrbytTest(11) = CByte(&HAF)86. '载波表地址87. arrbytTest(12) = CByte(&H59)88. arrbytTest(13) = CByte(&H20)89. arrbytTest(14) = CByte(&H0)90. '控制码91. arrbytTest(15) = CByte(&H1)92. '数据长度93. arrbytTest(16) = CByte(&H5)94. '功能码95. arrbytTest(17) = CByte(&H10)96. arrbytTest(18) = CByte(&H90)97. '集中器地址98. arrbytTest(19) = CByte(&HBB)99. arrbytTest(20) = CByte(&HBB)100. arrbytTest(21) = CByte(&HBB)101. '校验和102. arrbytTest(22) = CByte(&H50)103. arrbytTest(23) = CByte(&H3)104.105.106. '获取要发送字节数107. lngNumberofBytesToWrite = UBound(arrbytTest) + 1 108.109. '声明等待开始时间、结束时间值110. Dim writeStarTime, writeEndTime As Long112. writeStarTime = GetTickCount()113. Debug.Print "发送开始时间:"& writeStarTime114.115. '定义发送循环步长值116. Dim i As Integer117. '定义累计发送字节数118. Dim intT otalNumberOfBytesToWritten As Integer119. '定义发送间隔时间(毫秒)120. Dim intIntervalTime As Integer121. intIntervalTime = 0122.123. '发送数据124. For i = 0 To UBound(arrbytTest)125. flag = WriteFile(hCF, arrbytTest(i), 1, lngNumberofBytesToWritten, typOverLapped)126.127. '获取出错码128. errNum = GetLastError()129. 'Debug.Print "发送操作出错码:" & errNum130.131. '若返回值不是IO异步操作未决,则关闭串口132. If (errNum <> ERROR_IO_PENDING) And (errNum<> 0) Then GoTo closeComm133.134. '异步IO事件获取(返回值为 0表示出错)135. flag = WaitForSingleObject(typOverLapped.hEvent, 0) 136. 'Debug.Print "异步IO事件获取:" & flag137.138. '判断异步IO事件获取是否成功139. If flag <> 0 Then140. '异步IO操作结果获取(等待标记值,必须为true ,否则需要事件激活返回结果)141. flag = GetOverlappedResult(hCF, typOverLapped, lngNumberofBytesToWritten, 1)142. 'Debug.Print "异步IO操作获取:" & flag143.144. '判断异步IO操作结果获取是否成功145. If flag <> 0 Then146. intTotalNumberOfBytesToWritten= intTotalNumberOfBytesToWritten+ _147. lngNumberofBytesToWritten148. End If149.150. End If151.152. '间隔时间(用于需要设定每字节间间隔时间的发送协议)153. Sleep (intIntervalTime)154. Next155.156. writeEndTime = GetTickCount()157. Debug.Print "发送结束时间:"& writeEndTime158. Debug.Print "发送总时间:" & (writeEndTime - writeStarTime)159. Debug.Print "串口发送操作:"& flag160. Debug.Print "实际发送字节数:" & intTotalNumberOfBytesToWritten161.162. '********清空缓冲区等待数据接收********163. flag = FlushFileBuffers(hCF)164. 'Debug.Print "清空缓冲区:" & flag165.166. '********设置串口事件********167. '监听数据接收事件168. ' flag = SetCommMask(hCF, EV_ERR Or EV_RXCHAR) 169. ' Debug.Print "监听事件设置:" & flag170. flag = SetCommMask(hCF, 0)171. Debug.Print "监听事件设置:"& flag172.173. '********等待串口接收事件********174. '声明等待开始时间、结束时间值175. Dim sngStarTime, sngEndTime As Long176. '事件掩码177. Dim lngEventMask As Long178.179. '定义接收字节数变量180. Dim tempReceive As Long181. tempReceive = 0182.183. Debug.Print "监听开始"184. '生成开始时间185. sngStarTime = GetTickCount()186. Debug.Print "开始监听时间:"& sngStarTime187.188. '定义等待步骤参数189. Dim n As Integer190. n = 1191.192. ' '监听串口事件193. ' flag = WaitCommEvent(hCF, lngEventMask, typOverLapped)194. ' Debug.Print "监听操作:" & flag195.196. ' '获取出错码197. ' errNum = GetLastError()198. ' Debug.Print "监听操作出错码:" & errNum199. '200. ' '若返回值不是IO异步操作未决,则关闭串口201. ' If (errNum <> ERROR_IO_PENDING) And (errNum<> 0) Then GoTo closeComm202.203. '定义读取间隔时间(毫秒)204. Dim intReadIntervalTime As Integer205. intReadIntervalTime = 1206.207. Do208.209. ' '异步IO事件获取(返回值为 0 表示出错)210. ' flag = WaitForSingleObject(typOverLapped.hEvent, 0) 211. ' Debug.Print "异步IO事件获取:" & flag212. ' '获取出错码213. ' errNum = GetLastError()214. ' Debug.Print "IO事件获取出错码:" & errNum215.216. '清除错误标志函数,获取串口设备状态217. flag = ClearCommError(hCF, lngError, typCommStat)218. Debug.Print "获取串口设备状态:" & flag219.220. '若获取状态成功221. If (flag <> 0) And (typCommStat.cbInQue > 0) Then222.223. Debug.Print "已接收字节数:"& typCommStat.cbInQue 224.225. '判断接收缓冲区内的数据是否等于需要接收的字节数226. If typCommStat.cbInQue >= 22 Then227. '跳出循环228. Debug.Print "跳出循环"229. Exit Do230. End If231.232. End If233.234. '生成结束时间235. sngEndTime = GetTickCount()236. Debug.Print "第" & n & "次监听事件时间:" & sngEndTime237.238. n = n + 1239.240. '读时间间隔241. Sleep (intReadIntervalTime)242.243. Loop Until (sngEndTime - sngStarTime) > 1000244.245. '生成结束时间246. sngEndTime = GetTickCount()247. Debug.Print "结束监听时间:"& sngEndTime248.249. Debug.Print "监听结束"250. Debug.Print "总接收时间:" & (sngEndTime - sngStarTime)251.252. '********接收数据********253. '定义接收数组254. Dim arrbytReceive(0 To 22) As Byte255. '定义实际接收字节数256. Dim lngNBR As Long257. '重叠结构置0258. typOverLapped.hEvent = 0259. typOverLapped.Internal = 0260. typOverLapped.InternalHigh = 0261. typOverLapped.offset = 0262. typOverLapped.OffsetHigh = 0263.264. '接收数据265. flag = ReadFile(hCF, arrbytReceive(0), 23, lngNBR, typOverLapped)266. Debug.Print "串口接收操作:"& flag267. Debug.Print "实际接收字节数:" & lngNBR268. Debug.Print arrbytReceive(0)269. Debug.Print arrbytReceive(21)270. Debug.Print arrbytReceive(22)271.272. closeComm:273. '********关闭所有串口事件********274. flag = SetCommMask(hCF, 0)275. 'Debug.Print "关闭串口事件:"& flag276.277. '********关闭串口********278. Dim closeFlag As Long279. closeFlag = CloseHandle(hCF) 280. Debug.Print "关闭串口:" & closeFlag 281.282. End Sub。

经典的串口调试工具源代码(二)

经典的串口调试工具源代码(二)

经典的串口调试工具源代码(二)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 ' 转让控制权,以便让操作系统处理其它的事件。

用VB调试串口通讯

用VB调试串口通讯

用VB调试串口通讯现有电子秤一台,使用串口与计算机进行通讯。

编写VB程序来访问串口,达到读取电子秤上显示的数据。

该电子秤为BE01型仪表,输出为RS-232C标准接口,波特率为300-9600、偶校验、7个数据位、2个停止位。

所有字符均发送11位ASCII码,一个起始位。

在VB中与串口通讯需要引入控件MSComm串口通讯控件(在Microsoft Comm Control 6.0中)。

具体程序如下:控件简称:MSCDim Out(12) As Byte 接收var中的值Dim var As V ariant 接收MSC.input中的数值Dim nRece As Integer 计算MSC.inputbuffer的个数Dim i As Integer, j As Integer 随即变量,计算循环****************************************************************************Private Sub Form_Load()ClearTextWith MSC.CommPort = 1 设置Com1为通信端口.Settings = 9600,E,7,2 设置通信端口参数 9600赫兹、偶校验、7个数据位、1个停止位.(这里需要进一步说明的是:.Setting=”BBBB,P,D,S”。

含义是:B:Baud Rate(波特率);P:Parity(奇偶);D:Data Bit;S:Stop Bit).InBufferSize = 40 设置缓冲区接收数据为40字节.InputLen = 1 设置Input一次从接收缓冲读取字节数为1.RThreshold = 1 设置接收一个字节就产生OnComm事件End WithEnd Sub**************************************************************************** Private Sub ClearText()Text3.Text =Text2.Text = 5Text1.Text =End SubPrivate Sub Command1_Click()ClearTextnRece = 0 计数器清零With MSC.InputMode = comInputModeBinary 设置数据接收模式为二进制形式.InBufferCount = 0 清除接收缓冲区If Not .PortOpen Then.PortOpen = True 打开通信端口End IfEnd WithEnd SubPrivate Sub MSC_OnComm()DelayTime ‘用来延续时间ClearTextWith MSCSelect Case .CommEvent 判断通信事件Case comEvReceive: 收到Rthreshold个字节产生的接收事件SwichVar 1If Out(1) = 2 Then 判断是否为数据的开始标志.RThreshold = 0 关闭OnComm事件接收End IfDoDoEventsLoop Until .InBufferCount >= 3 循环等待接收缓冲区>=3个字节 nRece = nRece + 1For i = 2 To 12SwichVar iText1.Text = Text1.Text & Chr(Out(i))NextText1.Text = LTrim(Text1.Text)Text2.Text = Text2.Text & CStr(nRece).RThreshold = 1 打开MSComm事件接收Case Else.PortOpen = FalseEnd SelectEnd WithEnd Sub****************************************************************************Private Sub DelayTime()Dim bDT As BooleanDim sPrevious As Single, sLast As SinglebDT = TruesPrevious = Timer (Timer可以计算从子夜到现在所经过的秒数,在Microsoft Windows中,Timer函数可以返回一秒的小数部分)Do While bDTIf Timer - sPrevious >= 0.3 Then bDT = FalseLoopbDT = TrueEnd Sub(通信传输速率为9600bps,则最快速度1.04ms发送一个字节,仪表每秒发送50帧数据,每帧数据有4个字节,即每秒发送200个字节,平均5.0ms 发送一个字节,连续读取串口数据时要在程序中添加循环等待程序)Private Sub SwichV ar(ByV al nNum As Integer)DelayTimevar = Nullvar = MSC.InputOut(nNum) = var(0)End Sub(设置接收数据模式采用二进制形式,即 InputMode=comInputModeBinary,但用Input属性读取数据时,不能直接赋值给 Byte 类型变量,只能通过先赋值给一个 V ariant 类型变量,返回一个二进制数据的数组,再转换保存到Byte类型数变量中。

vb编写的串口调试程序

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。

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

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 ’转让控制权,以便让操作系统处理其它的事件。

相关文档
最新文档