VBNET开发全功能串口调试助手
用VB编写串口调试小助手

经典的串口调试助手源代码分类VB在单片机中的应Dim OutputAscii As Boolean Dim InputString As String Dim 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 quotshell32.dllquot Alias quotShellExecuteAquot 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 Long Private Sub CloseCom 关闭串口On Error GoTo Err If MSComm.PortOpen True Then MSComm.PortOpen False 先判断串口是否打开如果打开则先关闭txtstatus.Text quotSTATUSCOM Port Clocedquot 串口状态显示mnuconnect.Caption quot断开串口quot cmdswitch.Caption quot打开串口quot ImgSwitch.Picture LoadPicturequotf:我的VB串口调试软件图片guan.jpgquot 显示串口已经关闭的图标ImgSwitchoff.Visible True ImgSwitchon.Visible False Err: End Sub Private Sub UpdateStatus If MSComm.PortOpen Then StatusBar1.Panels1.Text quotConnectedquot mnuautosend.Caption quot自动发送quot mnuconnect.Caption quot断开串口quot Else StatusBar1.Panels1.Text quot断开串口quot mnuautosend.Caption quotdisautosendquot mnuconnect.Caption quot打开串口quot End If StatusBar1.Panels2.Text quotCOMquot amp mPortStatusBar1.Panels3.Text MSComm.Settings If OutputAscii Then StatusBar1.Panels4 quotASCIIquot Else StatusBar1.Panels4 quotHEXquot End If On Error GoTo Err If ChkAutoSend.Value 1 Then 如果有效则自动发送If MSComm.PortOpen True Then 串口状态判断mnuautosend.Caption quotDisampautosendquot TmrAutoSend.Interval ValTxtAutoSendTime 设置自动发送时间TmrAutoSend.Enabled True 打开自动发送定时器Else mnuautosend.Caption quotautosendquot ChkAutoSend.Value 0 串口没有打开去掉自动发送MsgBox quot串口没有打开请打开串口quot 48 quot串口调试助手quot 如果串口没有被打开提示打开串口End If ElseIf ChkAutoSend.Value 0 Then 如果无效不发送mnuautosend.Caption quotautosendquot TmrAutoSend.Enabled False 关闭自动发送定时器End If Err: End Sub Private Sub CmdSendFile_Click 发送文件On Error GoTo Err If MSComm.PortOpen True Then 如果串口打开了则可以发送数据If FileData quotquot Then 判断发送数据是否为空MsgBox quot发送的文件为空quot 16 quot串口调试助手quot 发送数据为空则提示Else If ChkHexReceive.Value 1 Then 如果按十六进制接收时按二进制发送否则按文本发送MSComm.InputMode comInputModeBinary 二进制发送ElseMSComm.InputMode comInputModeText 文本发送End If MSComm.Output TrimFileData 发送数据ModeSend True 设置文本发送方式End If Else MsgBox quot串口没有打开请打开串口quot 48 quot串口调试助手quot 如果串口没有被打开提示打开串口End If Err: End Sub Private Sub Comm_initialPort As Byte BaudRate AsString ParityBit As String DataBit As Integer StopBit As Integer On Error GoTo ErrorTrap 错误则跳往错误处理If MSComm.PortOpen True ThenMSComm.PortOpen False 先判断串口是否打开如果打开则先关闭mPort Port 设定端口MSComm.Settings BaudRate amp quotquot amp ParityBit amp quotquot amp DataBit amp quotquot amp 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 Then txtstatus.Text quotSTATUSquot amp cbocom.Text amp quot OPENDquot amp cbobaudrate.Text amp quotquot amp Leftcboparitybit.Text 1 amp quotquot amp cbodatabit.Text amp quotquot amp cbostopbit.Text Else txtstatus.Text quotSTATUSCOM Port Clocedquot 串口没打开时提示串口关闭状态End If Exit Sub ErrorTrap: 错误处理Select Case Err.Number Case comPortAlreadyOpen 如果串口已经打开则提示MsgBox quot没有发现此串口或被占用quot 49 quot串口调试助手quot CloseCom Case Else MsgBox quot没有发现此串口或被占用quot 49 quot串口调试助手quot CloseCom End Select Err.Clear End Sub Private Sub Comm_reSetPort 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 amp quotquot amp ParityBit amp quotquot amp DataBit amp quotquot amp StopBit 设置波特率无校验8位数据位1位停止位MSComm.PortOpen True 打开串口IfMSComm.PortOpen True Then cmdswitch.Caption quot关闭串口quot ImgSwitch.Picture LoadPicturequotf:我的VB串口调试软件图片kai.jpgquot 显示串口已经打开的图标ImgSwitchoff.Visible False mnuconnect.Caption quotdisconnectquot ImgSwitchon.Visible True txtstatus.Text quotSTATUSquot amp cbocom.Text amp quot OPENDquot amp cbobaudrate.Text amp quotquot amp Leftcboparitybit.Text 1 amp quotquot amp cbodatabit.Text amp quotquot amp cbostopbit.Text Else cmdswitch.Caption quot打开串口quot ImgSwitch.Picture LoadPicturequotf:我的VB串口调试软件图片guan.jpgquot 显示串口已经关闭的图标ImgSwitchon.Visible False ImgSwitchoff.Visible True txtstatus.Text quotSTATUSCOM Port Clocedquot End If Exit Sub ErrorHint: 错误处理Select Case Err.Number Case comPortAlreadyOpen 如果串口已经打开则提示MsgBox quot没有成功请重试quot vbExclamation quot串口调试助手quot CloseCom 调用关闭串口函数Case Else MsgBox quot没有成功请重试quot vbExclamation quot串口调试助手quot CloseCom 调用关闭串口函数End Select Err.Clear 清除Err 对象的属性End Sub Private Sub Command1_Click End Sub Private Sub cbobaudrate_Change Call Comm_reSetValMidcbocom.Text 4 2 cbobaudrate.Text Leftcboparitybit.Text 1cbodatabit.Text cbostopbit.Text 串口设置End Sub Private Sub cbocom_Change Call Comm_reSetValMidcbocom.Text 4 2 cbobaudrate.Text Leftcboparitybit.Text 1 cbodatabit.Text cbostopbit.Text 串口设置End Sub Private Sub cbodatabit_Change Call Comm_reSetValMidcbocom.Text 4 2 cbobaudrate.Text Leftcboparitybit.Text 1 cbodatabit.Text cbostopbit.Text 串口设置End Sub Private Sub cboparitybit_Change Call Comm_reSetValMidcbocom.Text 4 2 cbobaudrate.Text Leftcboparitybit.Text 1 cbodatabit.Text cbostopbit.Text 串口设置End Sub Private Sub cbostopbit_Change Call Comm_reSetValMidcbocom.Text 4 2 cbobaudrate.Text Leftcboparitybit.Text 1 cbodatabit.Text cbostopbit.Text 串口设置End Sub Private Sub chkautosend_Click On Error GoTo Err If ChkAutoSend.Value 1 Then 如果有效则自动发送If MSComm.PortOpen True Then 串口状态判断mnuautosend.Caption quot取消自动发送quot TmrAutoSend.Interval ValTxtAutoSendTime 设置自动发送时间TmrAutoSend.Enabled True 打开自动发送定时器Else ChkAutoSend.Value 0串口没有打开去掉自动发送MsgBox quot串口没有打开请打开串口quot 48 quot串口调试助手quot 如果串口没有被打开提示打开串口End If ElseIf ChkAutoSend.Value 0 Then 如果无效不发送mnuautosend.Caption quot自动发送数据quot TmrAutoSend.Enabled False 关闭自动发送定时器End If Err: End Sub Private 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 0 ConstNO_OPTIONS 0 Set spShell CreateObjectquotShell.Applicationquot Set spFolder spShell.BrowseForFolderWINDOW_HANDLE quot选择目录:quot NO_OPTIONS quotC:Scriptsquot Set spFolderItem spFolder.Self spPath spFolderItem.Path spPath ReplacespPath quotquot quotquot Replace函数的返回值是一个字符串txtsavepath.Text spPath 把文件夹路径显示在标签上SaveTextPath txtsavepath.Text 路径暂存Err: End Sub Private Sub CmdClearCounter_Click On Error GoTo Err SendCount 0 发送计数器清零ReceiveCount 0 接收计数器清零txtRXcount.Text quotRX:quot amp 0 接收计数txtTXcount.Text quotTX:quot amp 0 发送计数Err: End Sub Private Sub cmdclearrecieve_Click TxtReceive.Text quotquot End Sub Private Sub cmdclearsend_Click txtsend.Text quotquot End Sub Private Sub CmdHelp_Click FrmHelp.Show End Sub Private Sub CmdQuit_Click If MSComm.PortOpen True Then MSComm.PortOpen False 先判断串口是否打开如果打开则先关闭Unload Me 卸载窗体并退出程序End End Sub Private Sub cmdsavedisp_Click On Error GoTo Err 错误处理SaveTextPath txtsavepath 路径暂存Open txtsavepath amp quot1.txtquot For Output As 1 打开文件不存在的话会创建文件如已存在会覆盖output 改为append 为追加改为input 则只读Print 1 YearDate amp quot年quot amp MonthDate amp quot月quot amp DayDate amp _ quot 日quot amp HourTime amp quot时quot amp MinuteTime amp quot分quot amp SecondTime amp _ quot秒quot amp vbCrLf amp TxtReceive.Text vbCrLf 把接收区的文本保存文本前加上保存时间0000年00月00日00时00分00秒vbcrlf 为回车换行Close 1 关闭文件txtsavepath quotOK1.txt Savequot 提示保存成功cmdsavedisp.Enabled False Savetime Timer 记下开始的时间While Timer lt Savetime 5 循环等待5 - 要延时的时间DoEvents 转让控制权以便让操作系统处理其它的事件。
VC编写串口调试助手

void SetTextFont(int FontHight,LPCTSTR FontName);//设置字体
在MyButton.cpp的构造函数中初始化变量:
m_Style = 1;//m_Style = 0;//按钮形状风格
点击OK。项目创建完毕,进入项目。
删除界面上确定和取消按钮以及静态文字。
3.
保存后便可以开始创建界面了。
参考界面
仿照设计的界面,具体添加按钮或编辑框等的布局步骤就不用细说了。
4.
在资源视图中选择Icon右键InsertIcon加入打开和关闭的Icon图标或自行绘制,如下图
IDR_MAINFRAME原为MFC提供的图标,这里我直接改成自己的,生成EXE后将会显示这个图标。下面将帮助页面图标也改为自绘图标。
右键波特率对应的Combo Box,ID设置为IDC_BAUD,Type及Sort同上。
右键数据位对应的Combo Box,ID设置为IDC_BDATA,Type及Sort同上。
右键停止位对应的Combo Box,ID设置为IDC_BSTOP,Type及Sort同上。
右键校验位对应的Combo Box,ID设置为IDC_CAL,Type及Sort同上。
CRectm_ButRect;//按钮尺寸
CFont*p_Font; //字体
void DrawButton(CDC *pDC);//画正常按钮
//接口函数
public:
MyButton();
void SetText(CString str);//设置文字
void SetForeColor(COLORREF color);//设置文本颜色
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进制发送,如果是换行将不可选。
VBA调试技巧和常用工具介绍

VBA调试技巧和常用工具介绍VBA(Visual Basic for Applications)是一种广泛应用于微软Office套件中的宏语言,可以帮助用户自动执行繁琐的任务以提高工作效率。
然而,在编写VBA代码时,我们经常会遇到各种错误和问题,这就需要我们掌握一些调试技巧和常用工具来定位和解决这些问题。
本文将介绍一些VBA调试技巧和常用工具,帮助读者快速定位和解决VBA代码中的问题。
1. 使用断点调试在VBA代码中,可以设置断点来暂停程序的执行,从而可以逐行查看代码的执行过程,以便定位问题。
设置断点非常简单,只需在需要暂停的代码行前面点击鼠标左键即可,在执行代码时,程序将暂停在断点所在的行上。
在断点暂停的状态下,我们可以利用VBA编辑器中提供的各种调试工具来观察变量的值、执行代码的步骤等。
2. 运行时错误处理当程序执行时出现错误,VBA会中断程序的执行并显示一个错误消息。
但是有时候,我们可能希望通过编写一些特定的代码来捕获和处理这些错误,而不是直接中断程序的执行。
VBA提供了一些错误处理语句,如On Error Resume Next和On Error Goto语句,可以帮助我们在代码执行过程中捕获并处理错误,以保证程序的正常运行。
3. 使用调试工具窗口VBA编辑器中的调试工具窗口提供了一些强大的功能,可以帮助我们调试VBA代码。
其中最常用的是"立即窗口"(Immediate Window)和"局部窗口"(Locals Window)。
- 立即窗口允许我们在程序执行时直接输入和执行VBA语句,这对于一些短小的测试代码非常实用。
- 局部窗口可以显示当前正在执行的过程中定义的变量以及它们的值,这对于跟踪程序状态和定位错误非常有帮助。
4. 使用日志记录有时候,我们可能希望在程序执行时输出一些调试信息,以便在后期查看。
这时候,可以使用VBA的日志记录功能来记录程序的执行过程和关键变量的值。
串口调试助手使用说明

串口调试助手使用说明为简单明了,有些不言自明的功能不作介绍。
1 串口调试助手1.1 设置串口参数:串口号:1-16波特率:600-256000,>115200 时需要硬件支持。
2 接收区/键盘发送区2.1 接收数据a) 设置串口参数b) 如果要按十六进制形式显示接收数据,将十六进制显示选项选中。
c) 点击打开/关闭串口区中的打开串口按钮。
2.2 显示接收数据的长度因某些限制,显示接收数据的文本不能太长,所以当显示文本长度快达到62K 时会自动将显示文本删减到32K,此时文本可保留32K 的字符或约10K 的十六进制数据显示。
2.3 在键盘上发送英文字符a)在接收区/键盘发送区的输入框中用鼠标点一下。
b)在键盘按下按键立刻发送。
在这里不能发送回车换行,也不能发送汉字,若要发送请在单字符串发送区发送。
3 发送数据可以发送单字符串,多字符串(字符串序列)或直接在键盘上发送英文字符。
有两种发送数据格式,一种是普通的字符串,另外一种是十六进制数据即HEX 格式数据。
发送HEX 格式数据时要在字符串输入区中输入HEX 格式字符串,并且要将相应区内的十六进制发送选项选中。
例:HEX 格式数据字符串12 34 AB CD FF3.1 单字符串发送区3.1.1自动发送,自动发送周期:此项功能可以每隔一段时间反复地自动发送输入框中的数据,点击自动发送按钮后即启动自动发送功能。
自动发送周期最大为65535mS。
3.2 多字符串发送区在多字符串发送区可以发送一个字符串,或者自动地、依次发送所有的字符串。
请把鼠标移到“接收区/键盘发送区”和“多字符串发送区”之间,当鼠标形状发生变化时按下鼠标器的左键不松开,然后移动鼠标,将“多字符串发送区”的宽度调宽一些,让“间隔时间”显露出来。
3.2.1发送一个字符串a) 输入字符串。
b) 如果要发送16 进制数据, 要先在字符串后的HEX 选项框中打上对勾。
c) 点击发送按钮。
一个基于API的VB.net串口通讯类

⼀个基于API的串⼝通讯类的串⼝通讯⽀持总是让⼈觉得有所不⾜,在使⽤VB6的MsComm32.ocx时,很多⼈都会在的开发中觉得很困扰。
这⾥讲述的串⼝通讯类使⽤native代码,并且它是通API调⽤实现的,你会发现的串⼝通讯就是这么简单。
在说明如何使⽤这个类前,需要说明的是,本类只是⼀个的串⼝通讯演⽰,你可能需要根据你的情况修改后使⽤。
另外,本类的⽬的是通过例⼦教会你在⽆需ocx控件和第三⽅组件的⽀持下⽤开发串⼝通讯程序,所有并没有完善的异常错误处理。
1.初始化并打开串⼝ 创建⼀个CRs232类的实例,并在调⽤Open⽅法前设置好串⼝通讯参数。
例: Dim moRS232 as New Rs232() With moRs232 .Port = 1 '// Uses COM1 .BaudRate = 2400 '// 波特率 2400 .DataBit = 8 '// 8 data bits .StopBit = Rs232.DataStopBit.StopBit_1 '// 停⽌位 1 .Parity = Rs232.DataParity.Parity_None '// ⽆奇偶校验 .Timeout = 500 '//超时时间500 ms End With '// 初始化并打开串⼝ moRS232.Open () '// 串⼝打开后,你可以随意地控制DTR/RTS moRS232.Dtr = True moRS232.Rts = True 为了处理异常情况,建议你使⽤Try...Catch。
2.发送数据 本类为Rx和Tx准备了两个缓冲区(buffer),发送数据时,只需要设置TxData属性为你需要发送的数据,然后调⽤Tx⽅法就可以了。
例如: moRS232.TxData = txtTx.Text moRS232.Tx() 3.接收数据 先调⽤Rx⽅法(参数为您需要从串⼝读取的字节数),然后读取RxData属性。
VB NET串口通信例子--我的回忆录

这是我3年前的一个例子,最近翻出来回忆一下。
串口是计算机上一种非常通用设备通信的协议。
大多数计算机包含两个基于RS232的串口,现在配电脑好像只有一个。
串口同时也是仪器仪表设备通用的通信协议;很多GPIB兼容的设备也带有RS-232口。
同时,串口通信协议也可以用于获取远程采集设备的数据。
串口通信在工控领域用途很广。
串口通信的概念非常简单,串口按位(bit)发送和接收字节。
尽管比按字节(byte)的并行通信慢,但是串口可以在使用一根线发送数据的同时用另一根线接收数据。
它很简单并且能够实现远距离通信。
比如IEEE488定义并行通行状态时,规定设备线总常不得超过20米,并且任意两个设备间的长度不得超过2米;而对于串口而言,长度可达1200米。
典型地,串口用于ASCII码字符的传输。
通信使用3根线完成:(1)地线,(2)发送,(3)接收。
由于串口通信是异步的,端口能够在一根线上发送数据同时在另一根线上接收数据。
其他线用于握手,但是不是必须的。
串口通信最重要的参数是波特率、数据位、停止位和奇偶校验。
对于两个进行通行的端口,这些参数必须匹配:a,波特率:这是一个衡量通信速度的参数。
它表示每秒钟传送的bit的个数。
例如300波特表示每秒钟发送300个bit。
当我们提到时钟周期时,我们就是指波特率例如如果协议需要4800波特率,那么时钟是4800Hz。
这意味着串口通信在数据线上的采样率为4800Hz。
通常电话线的波特率为14400,28800和36600。
波特率可以远远大于这些值,但是波特率和距离成反比。
高波特率常常用于放置的很近的仪器间的通信,典型的例子就是GPIB设备的通信。
b,数据位:这是衡量通信中实际数据位的参数。
当计算机发送一个信息包,实际的数据不会是8位的,标准的值是5、7和8位。
如何设置取决于你想传送的信息。
比如,标准的ASCII码是0~127(7位)。
扩展的ASCII码是0~255(8位)。
如果数据使用简单的文本(标准 ASCII码),那么每个数据包使用7位数据。
VB实现串口通信,计算机网络实验

工业计算机网络实验报告实验4:计算机网络实验——VB实现串口通信一、实验目的:(1)熟悉和掌握串口通信的基本概念;(2)进一步熟悉RS-232C串口通信标准;(3)熟悉和掌握串行通信控件MSComm及其应用。
二、实验任务:(1)学会使用虚拟串行驱动程序(VSPD)虚拟串口。
(2).学会使用串口调试助手。
(3)使用VB做一个串口通信程序,要求能实现数据的收发。
三、编程实现:代码:Option ExplicitDim FS As IntegerPrivate Sub cmdExit_Click()Comm1.PortOpen = FalseEndEnd SubPrivate Sub cmdReceive_Click()txtReceive = Comm1.InputEnd SubPrivate Sub cmdSend_Click()Comm1.Output = txtSend.TextEnd SubPrivate Sub Comm1_OnComm() 'Label4.Caption = Comm1.Input End SubPrivate Sub Form_Load() Comm1.PortOpen = TrueEnd SubPrivate Sub txtReceive_Change() 'Comm1.OutputEnd Sub运行安装VPSD:用VPSD创建虚拟的端口:创建端口3,4运行两个例程,端口号分别设置为3,4:端口号3:端口号4的例程接受消息:端口号4的例程发送消息:端口为3的例程读取消息:四:实验总结通过本次试验,发现了自己在动手能力和自学能力方面的不足,我也进一步发现了自己在动手能力和自学能力方面的不足,然对本实验所涉及到的东西也算是有了不少兴趣,感觉越来越有意思然对本实验所涉及到的东西也算是有了不少兴趣,同时也对rs232串口的发送和接收信息有了进一步的了解,串口的发送和接收信息有了进一步的了解。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
开发全功能串口调试助手(含完整工程)
小记: 的串口通信用了很长时间了,也只用 Write 和Read 这样的方 法,以前都是用这种方式做上位机软件, 如此足矣。
而前几天研究GSM 模块时对 串口返回的数据总是把握不好,参考开发板附送的例程,发现采用
SerialPort
的DataReceived 事件,可以实现中断触发式的数据接收。
于是想到要自己做一 个串口调试助手,在实现基本功能的前提下增加一些方便自己调试的功能。
经过
断断续续的编写,就做成了下面这个小软件:
这个软件能够实现串口调试助手的全部功能,经过通信测试,数据接收性能 不亚于呼啸工作室的SComAssistant2.2,通过加大输入缓冲区,可以满足大量 数据接收。
的串口通信主要使用 VS 自带的SerialPort 控件,而不是早先的 MSComm 更具有兼容性,这也是很久以前就放弃 VB 改用.NET 的直接原因。
该控 件的主要方法、属性如下(该数据来自 VS 的MSD
帮助库):
想要通过串口收发数据,就需要对串口进行配置,包括设置端口、波特率、数据格式(如COM端口、9600bps、8位数据位、无校验位、1位停止位)等属性,之后通过Open方法打开串口。
打开串口可通过手动指定,也可以使用GetPortNames 方法获取计算机中存在的串口。
如果打开出错,则可能是串口不存在或者已被占用。
下面是相应代码:
Private SubSerialPortOpen()
On Error GoToErr
If SerialPort.IsOpen = True ThenSerialPort.Close() '避免重复打开端
口
SerialPort.Ope n()
LabelCOMStatus.Text ="串口已打开"
Exit Sub
Err: MsgBox(‘ 串口不存在或已被占用!" + vbNewLine + ErrorToString()) ' 出现错误,显示错误信息
En dSub
如果想要在串口中支持中文字符收发,则可在初始化时设置串口控件的编码:
SerialPort.E ncodi ng = System.Text.E ncodi ng.Default
发送数据通过Write方法来完成,由于串口调试助手需要支持文本和16进制, 需要加入转换代码:
Private SubButtonSendData_Click( ByVal sender AsSystem.Object, ByVal e AsSystem.EventArgs) Handles ButtonSendData.Click
On Error GoToErr
DimoutDataBuf AsString = TextBoxSend.Text
If outDataBuf = "" ThenExit Sub'如果输入文本框中没有数据则不发送
If SerialPort.lsOpen = True Then'判断串口是否打开
If HexSendFlag = True Then
' ----- 十六进制发送------------
outDataBuf = outDataBuf.Replace( "","")'清除空格与回车
outDataBuf = outDataBuf.Replace(vbNewLine, "")
'十六进制数据位数为偶数,例如:FF 00 15 AC 0D
If outDataBuf.Length Mod2 <> 0 Then
MsgBoxC请输入正确的十六进制数,用空格和回车隔开。
")
Exit Sub
En dIf
DimoutBytes(outDataBuf.Length / 2 - 1) As Byte
For I As Integer = 1 TooutDataBuf.Length - 1 Step 2
outBytes((I - 1) / 2) = Val( "&H" + Mid(outDataBuf, I, 2))
'VB 的十六进制表示方法,例如0x1D表示为& H1D
Next
SerialPort.Write(outBytes, 0, outDataBuf.Length / 2)
BarCou ntTx.Text = Val(BarCou ntTx.Text) + outDataBuf.Le ngth / 2
Else
' ------- 文本发送 --------------
SerialPort.Write(outDataBuf)
BarCountTx.Text = Val(BarCountTx.Text) + outDataBuf.Length '发送字节计数
En dIf
Else
MsgBox"串口未打开,请先打开串口。
")
En dIf
Exit Sub
Err: MsgBox(‘ 数据输入或发送错误!" + vbNewL ine + ErrorToStri ng())
En dSub
接收数据采用DataReceived事件,该事件在串口输入缓冲区中的字节数满足
设置条件时触发,并执行事件中的代码。
事件触发的字节数在ReceivedBytesThreshold 属性中设置,默认为1字节。
由于DataReceived事件采用了独立的线程,无法对软件界面中的控件进行直接操作,因而在现实时需要采用委托实例的方法。
首先建立委托:
Delegate SubRecieveRefreshMethodDelegate( ByVal [text] As String )'声
明委托
Dim RecieveRefresh AsNewRecieveRefreshMethodDelegate( AddressOf Recie veRefreshMethod)'定义数据显示委托实例
Sub RecieveRefreshMethod( ByVal str As String )'定义一个数据显示委托实例的方法
ShowRecieveData(str)
EndSub
其中ShowRecieveData函数将str字符串显示到TextBox控件中。
下面是DataReceived事件中对十六进制数据的处理。
同发送数据一样,读取数据时也要根据不同的显示方式使用不同的方法。
通过Read方法,根据缓冲区中存在的字节数读取十六进制数据,而文本显示则简单的多,只需ReadExisting即可。
最后通过Invoke方法调用委托,显示数据。
Private Sub SerialPort_DataReceived( ByVal sender As Object, ByVal e As
Syste m.10 .Ports.SerialDataReceivedEve ntArgs) Han dles SerialPort.DataRec eived
If HexRecieveFlag Then
' ------ 十六进制显示--------
Dim inDataLen As Integer = SerialPort.BytesToRead()'获取可读取的字节数
If inDataLen > 0 Then
Dim inBytes(inDataLen - 1) As Byte, bytes As Byte
Dim strHex As String =""
SerialPort.Read(i nBytes, 0, i nDataLe n) '读取数据
For Each bytes In in Bytes
strHex = strHex + [String].Format( "{0:X2} ", bytes)'格式化成十六
进制(不含&H)
Next
TextBoxRecieve.I nvoke(RecieveRefresh, strHex) '调用委托,显示接收的数据
BarCou ntRx.Text = (Val(BarCou ntRx.Text) + in DataLe n).ToStri ng ' 接收字节计数
End If
Else
'------------ 文本显示----------
Dim str As String
str = SerialPort.ReadExisti ng '读取全部可用字符串
TextBoxRecieve .Inv oke(RecieveRefresh, str)
BarCou ntRx.Text = (Val(BarCou ntRx.Text) + str.Le ngth).ToStri ng '接收字节计数
End If
End Sub
至此就实现了串口收发的基本功能,另外的定时收发(使用Timer控件)、
文件发送(使用FileSystem )参见附带的源文件代码。
(附件功能完全不给力呀,终于传上来了... ) AHSerialPortEIf.rar
在完成串口调试助手的功能后,还可以根据个人的使用习惯或需求,添加相应的功能。