经典的串口调试工具源代码(一)
经典串口调试助手源程序及串口通信设置
经典串口调试助手源程序及串口通信设置标题:串口调试助手之经典源程序及通信设置导言:串口调试助手是一种用于串口通信的调试工具,广泛应用于工业控制、测试等领域。
本文将介绍一种基于Windows平台的经典串口调试助手源程序及相关的串口通信设置,旨在帮助读者更好地了解该工具的使用和配置方法。
一、经典串口调试助手源程序1.开发平台:本程序采用C++ Builder 6.0开发。
2.功能概述:(1)串口设置包括设置串口波特率、数据位、校验位、停止位、流控、超时等参数。
(2)发送数据支持以字符串或Hex方式发送数据。
(3)接收数据实时显示串口接收到的数据,并支持数据格式设置。
(4)自动发送数据支持单次或循环发送,可设置发送时间间隔和发送次数。
(5)保存数据支持将接收到的数据保存为文本或二进制文件。
3.源程序结构本程序主要由以下几个模块组成:(1)Main Form:主窗体,包含图形界面显示和基本操作控件。
(2)Serial:串口类,负责串口相关操作,例如打开、关闭、设置参数、发送、接收等。
(3)SaveToFile:文件保存类,负责数据保存到文件中。
(4)Config:配置类,负责程序设置和读取。
(5)Hex:十六进制转换类,用于将字符串转换为Hex格式。
二、串口通信设置1.串口连接串口连接有两种方式:一种是通过RS232串口连接,需要将串口线插入串口,然后将串口线连接到目标设备;另一种是通过USB转串口连接,需要将USB转串口转接器插入计算机USB接口,然后将串口线连接到USB转串口转接器。
2.串口参数设置在使用串口调试助手前,必须先设置串口参数。
打开主窗体后,点击“串口设置”按钮,在弹出的窗口中设置串口的参数,包括波特率、数据位、校验位、停止位、流控和超时等参数。
其中,波特率是指通信时的数据传输速率,常用的有9600、19200、38400、57600、115200等。
数据位是指每次传输的数据位数,常用的有8位、7位、6位等。
串口精灵源代码
for(int i=0;i<len;)
{
char lstr,hstr=str[i];
if(hstr==' ')
{
i++;
continue;
}
i++;
if(i>=len)
break;
lstr=str[i];
//功能:若是在0-F之间的字符,则转换为相应的十六进制字符,否则返回-1
char CSCommTestDlg::ConvertHexChar(char ch)
{
if((ch>='0')&&(ch<='9'))
return ch-0x30;
else if((ch>='A')&&(ch<='F'))
{
// TODO: Add your control notification handler code here
VARIANT variant_inp;
COleSafeArray safearray_inp;
LONG len,k;
BYTE rxdata[2048]; //设置BYTE数组 An 8-bit integerthat is not signed.
写出详细的编程过程,姑且叫串口调试助手源程序V1.0或VC串口通讯源程序吧,
我相信,如果你用VC编程,那么有了这个代码,就可以轻而易举地完成串口编
程任务了。(也许本文过于详细,高手就不用看)
开始吧:
c#上位机串口通信助手源代码详解
c#上位机串口通信助手源代码实例详解
一、功能
1软件打开时,自动检测有效COM端口
2软件打开时,自动复原到上次关闭时的状态
3不必关闭串口,即可直接进行更改初始化设置内容(串口号、波特率、数据位、停止位、校验位),可按更改后的信息自动将串口重新打开
4
5
6
7
8
扰
9
10
二、
三、
1
用
端口号:
数据位:
校验位:
发送(byte):tbSendCount接收(byte):tbReceivedCount
清空计数按钮:btnClearCount按16进制显示:cb16Display
接收区清空内容按钮:btnClearReceived保存数据按钮:btnSaveFile
接收数据框:tbReceivedData发送数据框:tbSendData
自动发送:cbAutomaticSend间隔时间:tbSpaceTime
按16进制发送:cb16Send发送区清空内容按钮:btnClearSend
2创建一个方法类
按Ctrl+shift+A快捷键创建一个类,名字叫Methods,代码为:
tbSendData.Text=tbSendDataStr;
}
}
//发送文本框键盘按键检测
privatevoidtbSendData_KeyPress(objectsender,KeyPressEventArgse) {
if(cb16Send.Checked)
{
//正则匹配
stringpattern="[0-9a-fA-F]|\b";//\b:退格键
if(m.Success)。
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。
易语言串口通讯modbus协议模块上位机必备例子源代码
易语言串口通讯modbus协议模块上位机必备例子源代码1.引言1.1 概述在编写易语言串口通讯modbus协议模块上位机必备例子源代码之前,我们首先需要了解一些基本概念和背景知识。
本文介绍了该例子的目的和结构,以及引言、正文和结论三个主要部分的内容。
1.1概述Modbus协议是一种常用的串行通信协议,广泛应用于工业自动化领域。
它被设计用于在不同设备之间进行数据传输和通信。
Modbus协议简洁明了,易于实现和部署,因此被许多工业设备和上位机所采用。
易语言是一种面向过程的编程语言,易于学习和使用。
它提供了丰富的库和模块,方便我们进行串口通讯编程。
易语言的特点是语法简单易懂,同时也支持调用其他语言编写的DLL函数,可以实现更加复杂的功能。
本例子的目标是演示如何使用易语言编写一个串口通讯的Modbus 协议模块,并结合上位机的必备功能来实现数据的读写和显示。
在正文部分,我们将介绍Modbus协议的简要概述,包括其通信方式、数据格式、功能码等。
同时,我们还将介绍易语言中的串口通讯模块及其基本用法。
在结论部分,我们将提供一些实例源代码示例,以便读者更好地理解和使用这个例子。
此外,我们还将列举一些上位机必备的功能,以供读者参考和扩展应用。
通过这个例子,读者可以学习到如何使用易语言进行串口通讯编程,并了解Modbus协议在实际应用中的运用。
同时,读者也可以根据自己的需求和实际情况,对例子进行二次开发和改进,以适应不同的应用场景。
在下一节中,我们将详细介绍Modbus协议的相关知识,以便读者更好地理解本例子的内容和实现。
文章结构部分主要是对整篇文章的组织和安排进行介绍,以下是1.2 文章结构的内容:1.2 文章结构本文主要分为三个部分,包括引言、正文和结论,具体如下:1. 引言部分介绍了本文的概述、文章结构和目的。
在概述中,我们对易语言串口通讯modbus协议模块上位机必备例子源代码进行了简要介绍,指出了本文的主要内容和目标。
串口调试报文解读
串口调试报文解读
串口调试报文是指通过串口通信方式传输的数据包,通常以十六进制格式表示。
下面以MODBUS RTU协议为例,解读串口调试报文:
发送数据格式:
- 起始码:3.5个字符以上时间的间隔。
- 地址码01:读取站号为1设备的数据。
- 功能码01:读的是线圈类型的数据。
- 起始地址00 06:读取数据的起始地址是6,类型是Y点。
- 读取个数00 01:读取数据的数量是1个。
- 校验码1D CB:CRC检验的值。
- 停止码:3.5个字符以上时间的间隔。
接收数据格式:
- 起始码:3.5个字符以上时间的间隔。
- 地址码01:返回站号为1设备的数据。
- 功能码01:返回的是线圈类型的数据。
- 读取个数01:返回数据的长度是1个字节。
- 返回数据01:返回的数据为H01,即Y6=bit0=1。
不同的串口通信协议可能会有不同的报文格式和含义,如果你需要解读其他类型的串口调试报文,可以提供更多信息继续向我提问。
串口通信源代码
//
#include "tdafx.h"
#include <iostream>
// #include <cv.h>
// #include <highgui.h>
/*#include <cstring>*/
#include<windows.h>
//myDCB.fBinary = TRUE;
//myDCB.fParity = FALSE;
myDCB.ByteSize = 8;
myDCB.Parity = NOPARITY;
myDCB.StopBits = ONESTOPBIT;
SetCommState(hCom, &myDCB);
TimeOuts.WriteTotalTimeoutConstant=2000;
SetCommTimeouts(hCom,&TimeOuts); //设置超时
DCB myDCB;
GetCommState(hCom, &myDCB);
myDCB.BaudRate = 9600;
ReceiveData(hCom, rdata);
cout << (BYTE)(rdata[0]) <<"%%%%%%%"<< (BYTE)(rdata[1]) << endl;
cout << "收到数据!" << endl;
if(i>=250 ) break;
串口测试软件 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 & "已成功打开。
串口调试助手源码
串口调试助手程序框架(一)【截图】【源码】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>。
VC实现串口通信项目源码
VC实现串口通信项目源码以下是一个简单的串口通信项目的VC实现源码,包括了串口初始化、发送数据、接收数据等基本功能。
```#include <Windows.h>#include <stdio.h>#define BUFFER_SIZE 1024HANDLE hSerial;//初始化串口参数BOOL InitSerialPort//打开串口hSerial = CreateFile("\\\\.\\COM1", GENERIC_READ ,GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);if (hSerial == INVALID_HANDLE_VALUE)printf("Failed to open serial port\n");return FALSE;}//配置串口参数DCB dcbSerialParams = { 0 };dcbSerialParams.DCBlength = sizeof(dcbSerialParams); printf("Failed to get serial port state\n"); CloseHandle(hSerial);return FALSE;}dcbSerialParams.BaudRate = CBR_9600; // 波特率为9600 dcbSerialParams.ByteSize = 8; // 8位数据位dcbSerialParams.Parity = NOPARITY; // 无奇偶校验dcbSerialParams.StopBits = ONESTOPBIT;// 1位停止位printf("Failed to set serial port state\n"); CloseHandle(hSerial);return FALSE;}//设置超时操作CloseHandle(hSerial);return FALSE;}return TRUE;//发送数据BOOL SendData(const char* data)DWORD bytesWritten;if (!WriteFile(hSerial, data, strlen(data), &bytesWritten, NULL))printf("Failed to send data\n");CloseHandle(hSerial);return FALSE;}return TRUE;//接收数据BOOL ReceiveData(char* buffer, DWORD size)DWORD bytesRead;if (!ReadFile(hSerial, buffer, size, &bytesRead, NULL))printf("Failed to receive data\n");CloseHandle(hSerial);return FALSE;}return TRUE;if (!InitSerialPort()return 1;}char sendBuffer[BUFFER_SIZE];char receiveBuffer[BUFFER_SIZE];//发送数据printf("Enter data to send: ");gets_s(sendBuffer, BUFFER_SIZE);if (!SendData(sendBuffer))return 1;}//接收数据printf("Receiving data...\n");if (!ReceiveData(receiveBuffer, BUFFER_SIZE)) return 1;}printf("Received data: %s\n", receiveBuffer); CloseHandle(hSerial);```这个项目使用了Windows的串口通信API函数来实现串口的初始化、发送数据和接收数据操作。
串口调试助手源代码
串口调试助手预源代码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 的长度。
经典串口调试助手源程序及串口通信设置
经典串口调试助手源程序及串口通信设置串口调试助手是一种用于串口通信调试的工具,它可以通过串口与外部设备进行数据的读写和处理,常用于单片机、嵌入式系统、电子设备等领域的开发调试中。
经典串口调试助手源程序经典串口调试助手是一款经典的串口调试工具,其源程序使用C语言编写,提供了丰富的功能和易于使用的界面,被广泛应用于各种领域的开发调试中。
该工具可以在Windows操作系统中运行,并支持多种串口通信协议,包括RS232、RS485、RS422等。
以下是经典串口调试助手部分源程序的示例:```c// 打开串口HANDLE OpenSerialPort(const char* portName){ HANDLE hCom; hCom = CreateFile(portName, // 串口名称GENERIC_READ | GENERIC_WRITE, // 读写访问0,// 无共享NULL,// 安全描述符OPEN_EXISTING,// 打开方式FILE_ATTRIBUTE_NORMAL, // 文件属性NULL); // 文件模板if (hCom ==INVALID_HANDLE_VALUE) // 判断是否打开成功{ return NULL; } return hCom;}// 发送数据int SendData(HANDLE hCom, const char* data, int len){ DWORD writeSize; if (!WriteFile(hCom, data, len, &writeSize, NULL)) // 写入数据{ return -1; } return writeSize;}// 接收数据int ReceiveData(HANDLE hCom, char* data, int len){ DWORD readSize; if (!ReadFile(hCom, data, len,&readSize, NULL)) // 读取数据{ return -1; } return readSize;}// 关闭串口int CloseSerialPort(HANDLE hCom){ if(!CloseHandle(hCom)) // 关闭句柄{ return-1; } return 0;}```上述函数实现了打开串口、发送数据、接收数据和关闭串口等基本功能,可以作为串口通信的底层驱动实现。
Comassistant串口助手详解和源代码分析
到目前为止还不能在接收编辑框中看到数据,因为我们还没有打开串口,但运行程序不应该有任何错误, 不然,你肯定哪儿没看仔细,因为我是打开 VC6 对照着做一步写一行的,运行试试。没错吧?那么做下一 步: 6.打开串口和设置串口参数 码: // TODO: Add extra initialization here if(m_ctrlComm.GetPortOpen()) m_ctrlComm.SetPortOpen(FALSE); m_ctrlComm.SetCommPort(1); //选择 com1 if( !m_ctrlComm.GetPortOpen()) m_ctrlComm.SetPortOpen(TRUE);//打开串口 else AfxMessageBox("cannot open serial port"); m_ctrlComm.SetSettings("9600,n,8,1"); //波特率 9600,无校验,8 个数据位,1 个停止位 m_ctrlComm.SetInputModel(1); //1:表示以二进制方式检取数据 m_ctrlComm.SetRThreshold(1); //参数 1 表示每当串口接收缓冲区中有多于或等于 1 个字符时将引发一个接收数据的 OnComm 事件 m_ctrlComm.SetInputLen(0); //设置当前接收区数据长度为 0 m_ctrlComm.GetInput();//先预读缓冲区以清除残留数据 现在你可以试试程序了,将串口线接好后(不会接?去看看我写的串口接线基本方法),打开串口调试助 手,并将串口设在 com2,选上自动发送,也可以等会手动发送。再执行你编写的程序,接收框里应该有数 据显示了。 7.发送数据 先为发送按钮添加一个单击消息即 BN_CLICKED 处理函数,打开 ClassWizard->Message 你可以在你需要的时候打开串口, 例如在程序中做一个开始按钮, 在该按钮
经典的串口调试工具源代码(二)
经典的串口调试工具源代码(二)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 ' 转让控制权,以便让操作系统处理其它的事件。
串口 RS232代码
while (input.available() > 0) {
input.read(readBuffer);
}
String str=new String(readBuffer);
System.out.println(str);
}
catch (IOException e) { }
}
});
import m.SerialPortEtEventListener;
import m.UnsupportedCommOperationException;
public class read {
//检测系统中可用的通讯端口类
//侦听到串口有数据,触发串口事件
serialPort.notifyOnDataAvailable(true);
}
}
}
}
}
Send.java
package serial;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
}
catch (UnsupportedCommOperationException e) {}
byte[] readBuffer = new byte[1024];
try {
input = serialPort.getInputStream();
}
catch (IOException e) {}
try {
public static void main(String[] args) throws Exception{
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
经典的串口调试助手源代码(一)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 AsString, ByVal nShowCmd As Long) As LongPrivate Sub CloseCom() '关闭串口On Error GoTo ErrIf MSComm.PortOpen = True Then MSComm.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 ' 转让控制权,以便让操作系统处理其它的事件。