串口调试助手源代码
经典的串口调试工具源代码(一)
经典的串口调试助手源代码(一)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 ' 转让控制权,以便让操作系统处理其它的事件。
使用MATLAB进行串口调试的两种方法
使用MATLAB进行串口调试的两种方法在MATLAB中进行串口调试有多种方法,可以使用MATLAB自带的Instrument Control Toolbox,或使用第三方函数库进行串口通信。
1. 使用MATLAB自带的Instrument Control Toolbox进行串口调试Instrument Control Toolbox是MATLAB中用于连接和控制仪器的工具箱。
它提供了一组函数,可以通过串口与仪器进行通信。
第一步是创建串口对象。
使用MATLAB的serial函数可以创建一个串口对象,并设置串口的参数。
例如,以下代码创建一个串口对象并设置波特率为9600,数据位为8位,停止位为1位,校验位为无:```matlabs = serial('COM1');set(s, 'BaudRate', 9600);set(s, 'DataBits', 8);set(s, 'StopBits', 1);set(s, 'Parity', 'none');```第二步是打开串口。
使用MATLAB的fopen函数可以打开串口并进行通信:```matlabfopen(s);```第三步是发送和接收数据。
可以使用MATLAB的fwrite函数向串口发送数据,使用fread函数从串口接收数据。
以下代码发送一个字节的数据,并接收一个字节的数据:```matlabfwrite(s, uint8('A'));receivedData = fread(s, 1);```最后一步是关闭串口。
使用MATLAB的fclose函数可以关闭已经打开的串口:```matlabfclose(s);```2.使用第三方函数库进行串口通信```matlabimport java.io.*;import ng.*;import gnu.io.*;```创建和配置串口对象的步骤与使用Instrument Control Toolbox类似:```matlabport = 'COM1';baudRate = 9600;dataBits = 8;stopBits = 1;parity = 'none';s = serial(port, baudRate, dataBits, stopBits, parity);```打开串口和发送/接收数据的步骤也与使用Instrument Control Toolbox类似:```matlabfopen(s);fwrite(s, uint8('A'));receivedData = fread(s, 1);```关闭串口的步骤也是一样的:```matlabfclose(s);```这些是使用MATLAB进行串口调试的两种常见方法。
串口精灵源代码
for(int i=0;i<len;)
{
char lstr,hstr=str[i];
if(hstr==' ')
{
i++;
continue;
}
i++;
if(i>=len)
break;
lstr=str[i];
//功能:若是在0-F之间的字符,则转换为相应的十六进制字符,否则返回-1
char CSCommTestDlg::ConvertHexChar(char ch)
{
if((ch>='0')&&(ch<='9'))
return ch-0x30;
else if((ch>='A')&&(ch<='F'))
{
// TODO: Add your control notification handler code here
VARIANT variant_inp;
COleSafeArray safearray_inp;
LONG len,k;
BYTE rxdata[2048]; //设置BYTE数组 An 8-bit integerthat is not signed.
写出详细的编程过程,姑且叫串口调试助手源程序V1.0或VC串口通讯源程序吧,
我相信,如果你用VC编程,那么有了这个代码,就可以轻而易举地完成串口编
程任务了。(也许本文过于详细,高手就不用看)
开始吧:
C#串口调试助手
//serialPort1.Parity = (Parity)Enum.Parse(typeof(Parityset), comboBox4.SelectedItem.ToString());
} public enum Parityset {
None, odd, Even, Mark, Space } private void comboBox5_SelectedIndexChanged(object sender, EventArgs e) //停止位 { serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), boBox5.Text); }
serialPort1.BaudRate = int.Parse(comboBox2.Text); serialPort1.DataBits = int.Parse(comboBox3.Text); serialPort1.Parity = (Parity)Enum.Parse(typeof(Parityset),
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) {
textBox3.Text = serialPort.ReadExisting();
label10.Text = (int.Parse(label10.Text.Trim()) + 1).ToString(); //统计接收区 数据 组数
LabWindowscvi之RS-232串口通信编程源代码
LabWindows/cvi之RS-232串口通信编程源代码/* LabWindows/CVI User Interface Resource (UIR) Include File *//* Copyright (c) National Instruments 2006. All Rights Reserved. *//* *//* W ARNING: Do not add to, delete from, or otherwise modify the contents *//* of this include file. *//**************************************************************************/#include <userint.h>#ifdef __cplusplusextern "C" {#endif/* Panels and Controls: */#define PANEL 1#define PANEL_OKBUTTON_2 2 /* callback function: receivefile */#define PANEL_OKBUTTON 3 /* callback function: receivefilename */#define PANEL_STRING_2 4#define PANEL_QUITBUTTON 5 /* callback function: QuitCallback */#define PANEL_STRING 6#define PANEL_DECORATION_2 7#define PANEL_COMMANDBUTTON 8 /* callback function: filesel */#define PANEL_DECORATION 9#define PANEL_TEXTMSG 10#define PANEL_TEXTMSG_2 11/* Menu Bars, Menus, and Menu Items: *//* (no menu bars in the resource file) *//* Callback Prototypes: */int CVICALLBACK filesel(int panel, int control, int event, void *callbackData, int eventData1, int eventData2);int CVICALLBACK QuitCallback(int panel, int control, int event, void*callbackData, int eventData1, int eventData2);int CVICALLBACK receivefile(int panel, int control, int event, void *cal lbackData, int eventData1, int eventData2);int CVICALLBACK receivefilename(int panel, int control, int event, void*callbackData, int eventData1, int eventData2);#ifdef __cplusplus}#endif#include <ansi_c.h>#include <utility.h>#include <rs232.h>#include <cvirte.h>#include <userint.h>#include "232.h"static int byteswritten;static char filename[MAX_FILENAME_LEN];static char pathname[MAX_PATHNAME_LEN];static int panelHandle;int main (int argc, char *argv[]){if (InitCVIRTE (0, argv, 0) == 0)return -1; /* out of memory */if ((panelHandle = LoadPanel (0, "232.uir", PANEL)) < 0)return -1;//打开并配置串口Com1OpenComConfig (1, "", 57600, 1, 8, 1, 32767, 32767);//设置通信超时时间SetComTime (1, 5.0);//禁止串口软件握手SetXMode (1, 0);//禁止硬件握手SetCTSMode (1, LWRS_HW HANDSHAKE_OFF); DisplayPanel (panelHandle);RunUserInterface ();DiscardPanel (panelHandle);return 0;}int CVICALLBACK sendfilename (int panel, int control, int event, void *callbackData, int eventData1, int eventData2){int comstatus;int outputqueuelen;switch (event){case EVENT_COMMIT:strcat (filename, "\r");//向Com1写入文件名字符串byteswritten = ComWrt (1, filename, strlen(filename));break;}return 0;}int CVICALLBACK QuitCallback (int panel, int control, int event, void *callbackData, int eventData1, int eventData2){switch (event){case EVENT_COMMIT://关闭串口Com1CloseCom (1);QuitUserInterface (0);break;}return 0;}int CVICALLBACK filesel (int panel, int control, int event,void *callbackData, int eventData1, int eventData2){int selstatus;switch (event){case EVENT_COMMIT:filename[0] = '\0';selstatus = FileSelectPopup ("", "*.*", "*.*", "打开文件", VAL_LOAD_BUTTON, 0, 0, 1, 1, pathname);if (selstatus >= 0){SetCtrlVal (panelHandle, PANEL_STRING, pathname);//获得文件名SplitPath (pathname, NULL, NULL, filename);}break;}return 0;}int CVICALLBACK sendfile (int panel, int control, int event,void *callbackData, int eventData1, int eventData2){int outputqueuelen;switch (event){case EVENT_COMMIT://设置串口Com1调制解调器参数XModemConfig (1, 10.0, 10, 5.0, 1024);//设置从串口Com1发送文件数据XModemSend (1, pathname);//获得串口Com1输出队列的字符串数目outputqueuelen = GetOutQLen (1);if (outputqueuelen == 0){MessagePopup ("文件传输", "文件传输完毕!");}break;}return 0;}接收程序#include "toolbox.h"#include <ansi_c.h>#include <rs232.h>#include <cvirte.h>#include <userint.h>#include "232.h"static int bytesread;static char filename[MAX_PATHNAME_LEN];static char pathname[MAX_PATHNAME_LEN];static int panelHandle;int main (int argc, char *argv[]){if (InitCVIRTE (0, argv, 0) == 0)return -1; /* out of memory */if ((panelHandle = LoadPanel (0, "232.uir", PANEL)) < 0) return -1;//打开并配置串口Com2OpenComConfig (2, "", 57600, 1, 8, 1, 32767, 32767);//设置通信超时时间SetComTime (2, 5.0);//禁止串口软件握手SetXMode (2, 0);//禁止硬件握手SetCTSMode (2, LWRS_HW HANDSHAKE_OFF);DisplayPanel (panelHandle);RunUserInterface ();DiscardPanel (panelHandle);return 0;}int CVICALLBACK receivefilename (int panel, int control, int event, void *callbackData, int eventData1, int eventData2){switch (event){case EVENT_COMMIT:filename[0] = '\0';SetCtrlVal (panelHandle, PANEL_STRING, "");//读取字符串直到回车符出现bytesread = ComRdTerm (2, filename, 260, 13);//当出现回车符后,在其后加上结束符filename[bytesread]= '\0';SetCtrlVal (panelHandle, PANEL_STRING, filename);break;}return 0;}int CVICALLBACK QuitCallback (int panel, int control, int event, void *callbackData, int eventData1, int eventData2){switch (event){case EVENT_COMMIT://关闭串口Com2CloseCom (2);QuitUserInterface (0);break;}return 0;}int CVICALLBACK filesel (int panel, int control, int event,void *callbackData, int eventData1, int eventData2){int selstatus;switch (event){case EVENT_COMMIT:selstatus = DirSelectPopup ("", "保存文件", 1, 1, pathname); if (selstatus){strcat (pathname, "\\");strcat (pathname, filename);SetCtrlVal (panelHandle, PANEL_STRING_2, pathname);}break;}return 0;}int CVICALLBACK receivefile (int panel, int control, int event, void *callbackData, int eventData1, int eventData2){int result;int filesize;int inputqueuelen;FILE *stream;switch (event){case EVENT_COMMIT:GetCtrlVal (panelHandle, PANEL_STRING_2, pathname);//判断文件是否存在result = FileExists (pathname, &filesize);if (!result){stream = fopen (pathname, "wb+");fclose (stream);}//设置串口Com2调制解调器参数XModemConfig (2, 10.0, 10, 5.0, 1024);//设置从串口Com2接收文件数据XModemReceive (2, pathname);//获得串口Com2输入队列的字符串数目inputqueuelen = GetInQLen (2);if (inputqueuelen == 0){MessagePopup ("文件保存", "文件保存完毕!"); }break;}return 0;}。
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。
串口调试助手通信调试原理图PCB及使用手册
串口调试助手通信调试原理图PCB及使用手册【简要说明】一、尺寸:长170mmX宽72mmX高18mm二、主要芯片:单片机,MAX485,MAX232三、工作电压:6V至40V,功耗小于1W四、特点:1、具有稳压电路,输入电压广,具有电源指示灯。
2、具有485通信和232通信及TTL通信。
3、具有数码管数据显示,蜂鸣器提示音4、波特率可调分别是 2400 4800 9600 192005、采用大按键,机械寿命长。
6、单片机编程,提供源代码7、可发送20组数据8、具有系统复位按键9、端子采用螺旋压接端子10、工作温度-40度至 +70度11、工作湿度 40% ~ 80%RH12、板子静态功耗小于1W13、具有续流保护14、具有电磁抗干扰能力15、板子稳定工作可靠16、板子可安装在DIN导轨上面使用说明:【标注说明】【功能描述】【原理图】【PCB图】【元件清单】【应用举例】【应用举例2】例如:将下面一组数据通过串口发送给电脑。
波特率是9600,电脑用串口助手显示出来。
数据是:A0 B2 CC FF EF D8 90 88第一步:板子供电,串口连接电脑,查看串口号。
如下图:我的电脑--属性--硬件---设备管理器---端口设备。
下图:第三步:从发送板,按下下面一组数据,数据是:A0 B2 CC FF EF D8 90 88数据按完之后,按发送键“S2”,如果数据输入错误,可以按”S1”按键清零,重新输入。
如果要发送多遍,重复按“S2”按键。
单遍发送如下图。
【源代码程序】/*一次最多发送20组数据,大于这个数据就不再发送*/#include <STC12C5A60S2.H>#define uchar unsigned char#define uint unsigned int/**************************************************************/unsigned char T0RH = 0; //T0重载值的高字节unsigned char T0RL = 0; //T0重载值的低字节extern void UartDriver(); //串口驱动函数,监测数据帧的接收,调度功能函数,需在主循环中调用extern void ConfigUART(unsigned int baud); //串口配置函数,baud-通信波特率extern void ConfigUART1(unsigned int baud1); //串口配置函数,baud-通信波特率extern void UartRxMonitor(unsigned char ms); //串口接收监控,由空闲时间判定帧结束,需在定时中断中调用,ms-定时间隔extern void SendString(char *s) ;extern void UartWrite(unsigned char *buf, unsigned char len); //串口数据写入,即串口发送函数,buf-待发送数据的指针,len-指定的发送长度extern void fengming();uchar zh[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};uchar jieshou[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uchar jj = 0;/*****************************************************************/sbit out0 = P2^0;sbit out1 = P2^1;sbit out2 = P2^2;sbit out3 = P2^3;sbit in0 = P2^4;sbit in1 = P2^5;sbit in2 = P2^6;sbit in3 = P2^7;sbit smgk = P3^6;sbit boma1 = P1^1;sbit boma2 = P1^0;bit d1 = 1;bit d2 = 1;sbit in4 = P1^6;sbit in5 = P1^5;uchar code xianshi [] ={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e,0xbf};uchar dangqianzhuangtai[4][4] = {{1,1,1,1},{1,1,1,1},{1,1,1,1},{1,1,1,1}};void t0 () interrupt 1{uchar i;static uchar lie = 0;static uchar sao[2] = {1,1};static uchar saomiaobaocun [4][4] = {{0xff,0xff,0xff,0xff},{0xff,0xff,0xff,0xff},{0xff,0xff,0xff,0xff},{0xff,0xff,0xff,0xff}};TH0 = 0xfc;TL0 = 0x67;UartRxMonitor(1); //串口接收监控sao[0] = (sao[0]<<1) |in4;sao[1] = (sao[1]<<1) |in5;saomiaobaocun [lie][0] = (saomiaobaocun [lie][0]<<1) | in0; saomiaobaocun [lie][1] = (saomiaobaocun [lie][1]<<1) | in1; saomiaobaocun [lie][2] = (saomiaobaocun [lie][2]<<1) | in2; saomiaobaocun [lie][3] = (saomiaobaocun [lie][3]<<1) | in3;if(sao[0] == 0x00){d1 = 0;}else if(sao[0] == 0xff){d1 = 1;}if(sao[1] == 0x00){d2 = 0;}else if(sao[1] == 0xff){d2 = 1;}for (i=0;i<4;i++){if ((saomiaobaocun [lie][i] & 0x0f) == 0x00){dangqianzhuangtai[lie][i] = 0;}else if ((saomiaobaocun [lie][i] & 0x0f) == 0x0f){dangqianzhuangtai[lie][i] = 1;}}lie++;lie = lie & 0x03;switch (lie){case 0 : out1 = 1; out2 = 1; out3 = 1; out0 = 0; break;case 1 : out0 = 1; out2 = 1; out3 = 1; out1 = 0; break;case 2 : out0 = 1; out1 = 1; out3 = 1; out2 = 0; break;case 3 : out0 = 1; out1 = 1; out2 = 1; out3 = 0; break;}}void main (){uchar i,j;bit q1 = 1;bit q2 = 1;uchar qianyicizhuangtai[4][4] = {{1,1,1,1},{1,1,1,1},{1,1,1,1},{1,1,1,1}};smgk = 0;TMOD = 0x01;TH0 = 0xfc;TL0 = 0x67;TR0 = 1;EA = 1;ET0 = 1;P0 = xianshi[16];// ConfigUART(9600); //配置波特率为9600while (1){UartDriver(); //调用串口驱动if((boma1 == 0)&&(boma2 != 0)){ConfigUART(2400); //配置波特率为1200}if((boma2 == 0)&&(boma1 != 0)){ConfigUART(4800); //配置波特率为4800}if((boma1 == 0)&&(boma2 == 0)){ConfigUART(9600); //配置波特率为9600}if((boma1 != 0)&&(boma2 != 0)){ConfigUART1(19200); //配置波特率为19200 }if(d1 != q1){q1 = d1;if(d1 == 0){if((jj != 0)&&(jj <= 2)){zh[0] = jieshou[0] | jieshou[1];UartWrite(zh, 1);fengming();}if((jj > 2)&&(jj <= 4)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];UartWrite(zh, 2);fengming();}if((jj > 4)&&(jj <= 6)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];UartWrite(zh, 3);fengming();}if((jj > 6)&&(jj <= 8)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];zh[3] = jieshou[6] | jieshou[7];UartWrite(zh, 4);fengming();}if((jj > 8)&&(jj <= 10)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];zh[3] = jieshou[6] | jieshou[7];zh[4] = jieshou[8] | jieshou[9];UartWrite(zh, 5);fengming();}if((jj > 10)&&(jj <= 12)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];zh[3] = jieshou[6] | jieshou[7];zh[4] = jieshou[8] | jieshou[9];zh[5] = jieshou[10] | jieshou[11];UartWrite(zh, 6);fengming();}if((jj > 12)&&(jj <= 14)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];zh[3] = jieshou[6] | jieshou[7];zh[4] = jieshou[8] | jieshou[9];zh[5] = jieshou[10] | jieshou[11];zh[6] = jieshou[12] | jieshou[13];UartWrite(zh, 7);fengming();}if((jj > 14)&&(jj <= 16)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];zh[3] = jieshou[6] | jieshou[7];zh[4] = jieshou[8] | jieshou[9];zh[5] = jieshou[10] | jieshou[11];zh[6] = jieshou[12] | jieshou[13];zh[7] = jieshou[14] | jieshou[15];UartWrite(zh, 8);fengming();}if((jj > 16)&&(jj <= 18)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];zh[3] = jieshou[6] | jieshou[7];zh[4] = jieshou[8] | jieshou[9];zh[5] = jieshou[10] | jieshou[11];zh[6] = jieshou[12] | jieshou[13];zh[7] = jieshou[14] | jieshou[15];zh[8] = jieshou[16] | jieshou[17];UartWrite(zh, 9);fengming();}if((jj > 18)&&(jj <= 20)){zh[0] = jieshou[0] | jieshou[1];zh[1] = jieshou[2] | jieshou[3];zh[2] = jieshou[4] | jieshou[5];zh[3] = jieshou[6] | jieshou[7];zh[4] = jieshou[8] | jieshou[9];zh[5] = jieshou[10] | jieshou[11];zh[6] = jieshou[12] | jieshou[13];zh[7] = jieshou[14] | jieshou[15];zh[8] = jieshou[16] | jieshou[17];zh[9] = jieshou[18] | jieshou[19];UartWrite(zh, 10);fengming();}}}if(d2 != q2){q2 = d2;if(d2 == 0){jj = 0;jieshou[0] = 0x00;jieshou[1] = 0x00;jieshou[2] = 0x00;jieshou[3] = 0x00;jieshou[4] = 0x00;jieshou[5] = 0x00;jieshou[6] = 0x00;jieshou[7] = 0x00;jieshou[8] = 0x00;jieshou[9] = 0x00;P0 = xianshi[16];fengming();}}for (i=0;i<4;i++){for (j=0;j<4;j++){if(dangqianzhuangtai[i][j] != qianyicizhuangtai[i][j] ){qianyicizhuangtai[i][j] = dangqianzhuangtai[i][j];if(qianyicizhuangtai[i][j] != 0){jj++;if((i*4+j) < 9){P0 = xianshi[i*4+j+1];}if((i*4+j) == 9){P0 = xianshi[0];}if((i*4+j) > 9){P0 = xianshi[i*4+j];}fengming();/******************1组**************************/if(jj == 1){//jieshou[0] = i*4+j;//jieshou[0] = jieshou[0] << 4;if((i*4+j) < 9){jieshou[0] = i*4+j+1;if((i*4+j) == 9){jieshou[0] = 0;}if((i*4+j) > 9){jieshou[0] = i*4+j;}jieshou[0] = jieshou[0] << 4;}if(jj == 2){//jieshou[1] = i*4+j;if((i*4+j) < 9){jieshou[1] = i*4+j+1;}if((i*4+j) == 9){jieshou[1] = 0;}if((i*4+j) > 9){jieshou[1] = i*4+j;}}/******************2组**************************/ if(jj == 3){//jieshou[2] = i*4+j;if((i*4+j) < 9){jieshou[2] = i*4+j+1;}if((i*4+j) == 9){jieshou[2] = 0;}if((i*4+j) > 9){jieshou[2] = i*4+j;jieshou[2] = jieshou[2] << 4;}if(jj == 4){//jieshou[3] = i*4+j;if((i*4+j) < 9){jieshou[3] = i*4+j+1;}if((i*4+j) == 9){jieshou[3] = 0;}if((i*4+j) > 9){jieshou[3] = i*4+j;}}/******************3组**************************/ if(jj == 5){//jieshou[4] = i*4+j;if((i*4+j) < 9){jieshou[4] = i*4+j+1;}if((i*4+j) == 9){jieshou[4] = 0;}if((i*4+j) > 9){jieshou[4] = i*4+j;}jieshou[4] = jieshou[4] << 4;}if(jj == 6){//jieshou[5] = i*4+j;if((i*4+j) < 9){jieshou[5] = i*4+j+1;}if((i*4+j) == 9){jieshou[5] = 0;}if((i*4+j) > 9){jieshou[5] = i*4+j;}}/******************4组**************************/ if(jj == 7){//jieshou[6] = i*4+j;if((i*4+j) < 9){jieshou[6] = i*4+j+1;}if((i*4+j) == 9){jieshou[6] = 0;}if((i*4+j) > 9){jieshou[6] = i*4+j;}jieshou[6] = jieshou[6] << 4;}if(jj == 8){//jieshou[7] = i*4+j;if((i*4+j) < 9){jieshou[7] = i*4+j+1;}if((i*4+j) == 9){jieshou[7] = 0;}if((i*4+j) > 9){jieshou[7] = i*4+j;}}/******************5组**************************/{//jieshou[8] = i*4+j;if((i*4+j) < 9){jieshou[8] = i*4+j+1;}if((i*4+j) == 9){jieshou[8] = 0;}if((i*4+j) > 9){jieshou[8] = i*4+j;}jieshou[8] = jieshou[8] << 4;}if(jj == 10){//jieshou[9] = i*4+j;if((i*4+j) < 9){jieshou[9] = i*4+j+1;}if((i*4+j) == 9){jieshou[9] = 0;}if((i*4+j) > 9){jieshou[9] = i*4+j;}}/******************6组**************************/ if(jj == 11){//jieshou[10] = i*4+j;if((i*4+j) < 9){jieshou[10] = i*4+j+1;}if((i*4+j) == 9){jieshou[10] = 0;if((i*4+j) > 9){jieshou[10] = i*4+j;}jieshou[10] = jieshou[10] << 4;}if(jj == 12){//jieshou[11] = i*4+j;if((i*4+j) < 9){jieshou[11] = i*4+j+1;}if((i*4+j) == 9){jieshou[11] = 0;}if((i*4+j) > 9){jieshou[11] = i*4+j;}}/******************7组**************************/ if(jj == 13){//jieshou[12] = i*4+j;if((i*4+j) < 9){jieshou[12] = i*4+j+1;}if((i*4+j) == 9){jieshou[12] = 0;}if((i*4+j) > 9){jieshou[12] = i*4+j;}jieshou[12] = jieshou[12] << 4;}if(jj == 14){//jieshou[13] = i*4+j;if((i*4+j) < 9){jieshou[13] = i*4+j+1;}if((i*4+j) == 9){jieshou[13] = 0;}if((i*4+j) > 9){jieshou[13] = i*4+j;}}/******************8组**************************/ if(jj == 15){//jieshou[14] = i*4+j;if((i*4+j) < 9){jieshou[14] = i*4+j+1;}if((i*4+j) == 9){jieshou[14] = 0;}if((i*4+j) > 9){jieshou[14] = i*4+j;}jieshou[14] = jieshou[14] << 4;}if(jj == 16){//jieshou[15] = i*4+j;if((i*4+j) < 9){jieshou[15] = i*4+j+1;}if((i*4+j) == 9){jieshou[15] = 0;}if((i*4+j) > 9){jieshou[15] = i*4+j;}}/******************9组**************************/ if(jj == 17){//jieshou[16] = i*4+j;if((i*4+j) < 9){jieshou[16] = i*4+j+1;}if((i*4+j) == 9){jieshou[16] = 0;}if((i*4+j) > 9){jieshou[16] = i*4+j;}jieshou[16] = jieshou[16] << 4;}if(jj == 18){//jieshou[17] = i*4+j;if((i*4+j) < 9){jieshou[17] = i*4+j+1;}if((i*4+j) == 9){jieshou[17] = 0;}if((i*4+j) > 9){jieshou[17] = i*4+j;}}/******************10组**************************/ if(jj == 19){//jieshou[18] = i*4+j;if((i*4+j) < 9){jieshou[18] = i*4+j+1;}if((i*4+j) == 9){jieshou[18] = 0;}if((i*4+j) > 9){jieshou[18] = i*4+j;}jieshou[18] = jieshou[18] << 4;}if(jj == 20){//jieshou[19] = i*4+j;if((i*4+j) < 9){jieshou[19] = i*4+j+1;}if((i*4+j) == 9){jieshou[19] = 0;}if((i*4+j) > 9){jieshou[19] = i*4+j;}}}}}}}}void UartAction(unsigned char *buf, unsigned char len){//在接收到的数据帧后添加换车换行符后发回// buf[len++] = '\r';//buf[len++] = '\n';UartWrite(buf, (len-2));}【真值表】【图片展示】。
c#-tcp调试助手源代码
c# tcp 调试助手源代码以下是winform tcp 调试助手源代码,调试通过,可进行简单应用using System;using System.Collections。
Generic;using ponentModel;using System.Data;using System.Drawing;using System.Linq;using System。
Text;using System。
Windows。
Forms;//添?加ó新?的?名?称?空?间?引皔用?using System.IO;using System。
Net;using System。
Net.Sockets;using System。
Threading;//using System。
Timers;namespace TCP调獭?试?助ú手?{public partial class Form1 : Form{/*****服务?端?*******/private int serve_portNum=13 ;private TcpListener serve_listener = null;//服务?器÷与?客í户§机ú之?间?的?连?接ó状痢?态?private bool bserve_Connected = false;//服务?器÷侦ì听瑈线?程ìprivate Thread tserve_AcceptMsg = null;//网?络?访?问ê的?基ù础?数簓据Y流ⅰ?private NetworkStream nStream_serve = null;//创洹?建¨读á取?器÷private TextReader tReader_serve = null;//创洹?建¨编括?写′器÷private TextWriter wReader_serve = null;/*****客í户§端?*******/private int Client_portNum = 13;//客í户§端?连?接óprivate TcpClient client_client = null;//客í户§机ú与?服务?器÷之?间?的?连?接ó状痢?态?private bool bclient_Connected = false;//客í户§机ú侦ì听瑈线?程ìprivate Thread tclient_AcceptMsg = null;//网?络?访?问ê的?基ù础?数簓据Y流ⅰ?private NetworkStream nStream_client= null;//创洹?建¨读á取?器÷private TextReader tReader_client = null;//创洹?建¨编括?写′器÷private TextWriter wReader_client = null;//接ó收?、¢发ぁ?送í数簓据Y池?长¤度èprivate const int bytelength = 1024;//服务?器÷接ó收?池?byte[] serve_rec_buff = new byte[bytelength];//服务?器÷发ぁ?送í池?byte[] serve_send_buff = new byte[bytelength];//客í户§端?接ó收?池?byte[] client_rec_buff = new byte[bytelength];//客í户§端?发ぁ?送í池?byte[] client_send_buff = new byte[bytelength];public Form1(){InitializeComponent();rb_xs_zf。
VC编写串口调试助手(含VC6工程源文件)
纯业余者用VC(MFC)编写串口调试助手1.序毕业到现在,转眼就做射频开发10年了,一直从事直放站、干放等通信边缘行业,从低噪放、锁相源、选频、功放到整机,射频就那么点东西,而且越来越集成化,软件无线电是必然趋势。
做射频从业面会越来越窄,我知道所有人都会说,当你成为专家的时候,一切就都不是问题,可有几个真正的专家,再者说,射频需要经验的积累,只有实际项目做的越多越广,经验也就积累得越多,并不是一朝一夕能达到的。
前不久突然觉得,我的射频模块控制要是也是自己来编程控制多好啊!那就得学单片机编程,学习上位机编程了,可我都不会啊,要不就先来整整上位机,windows方面的。
大学唯一学的编程语言是C语言,可根本不能理解用C做什么,还都还给老师10多年了,这怎么办?从BASIC,C/C++,JAVA,PASCAL搜索了一圈,还是选C++吧,毕竟是C 语言发展而来,用VC环境,身边有可以请教的人。
在网上转悠了很久,发现《windows程序设计》是必看,《MFC Windows程序设计》是学MFC最经典的书籍。
OMG,这些书啊,都是上千页的,白天都在上班,哪有时间看哦,只有先下载下来作为参考资料了。
扯远了啊。
这也不行那也不行,怎么办呢?干脆硬着头皮上吧,找几个实例照搬,再修修改改加深理解吧。
第一个目标,自己编写个串口调试助手,掌握串口通信编程,这样上位机的编写就有希望了。
好了,目标定下来了。
网上下载了个串口调试助手,确定基本功能:1.自动寻找串口,并自动添加到下拉框中共选择;2.有波特率、数据位、停止位、校验位的选择设置;3.串口打开控制按钮;4.发送、清除按钮;5.接收是自动实现的;6.有定时自动发送功能;7.有传送文件功能;8.有状态栏显示,指示串口状态,设置参数和发送接收显示。
下面就一步步实现,本人纯业余,只是记录下来这个学习过程,请勿拍砖。
开发平台Visual C++6.0英文版,电脑是i7-2670Q四核8G内存1G独显的笔记本,装的win764位旗舰版,因此VC6兼容不是太好,有些小毛病,不过不影响编写。
串口通信源代码
//
#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;
串口调试助手源码
串口调试助手程序框架(一)【截图】【源码】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>。
串口转网络调试助手(USR-TCP232-Test)
川 时 还 支 持 自动 换 仃 示 接 收 结 果 ,
TooI S I 工 具 箱
DNS域 名批量解析工具
商 睁
黜
BCArchiMe
软 件 属 性 :系 统 工 具 运 行 环 境 :winA1 1
软 件 大 小 :4.29MB
矬 #赫
软 件 属 性 :系统 工具 运 行 环境 :VLinAiI 软 件 大 小 :29。77MB 软 件语 言 :简体 中文 下 载 地 址 :https://w ̄w. dns.com/ DNS域 名 批 量 解 析 工 具 是 一 款 免 费 的 、实 时 在 线 的
软 件 语 言 :简 体 中丈 下 载 地 址 :https:// WWW.j et i C0.C0m/f ree— secHrity—too1 s/encrypt.一
compress-fi les—bcarchivc
BCArchive 中 文 版 是 一 款 简 单 易 用 的 文 件 加 晰 软 ft-。 加 密 T 具 (BCArchive)具 有 简 的 使 用 界 面 ,用 户 还 呵 以 通 过 鼠 标 右 键 快 速 对 文 件 进 行 加 密 ,而 不 需 要 先 启 动 软 件 。 软 件 还 町 以 生 成 自动 解 密 序
运 行环 境 :WinAl i
软 件 大 小 :866KB 软 件 语 言 :英 史 。 L
运 行 环 境 :Winall 软 件 大 小 :38OKB 软 件 语 言 :简体 中 文 下 载 地 址 :http://www “。 ·cn/Download/27.1 l
串口调试助手源代码
串口调试助手预源代码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 的长度。
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 ' 转让控制权,以便让操作系统处理其它的事件。
串口助手步骤cjq
建立SCOMM程序串口助手背景:vc++2005,不需要什么特殊空间(spcomm之类的什么都不需要)1.打开vc++2005,新建MFC AppWizard,名字SCOMM,基于对话框的。
确定完成。
2.建立界面如下:代码如下:SCOMMDlg.cpp// SCOMMDlg.cpp : 实现文件//#include"stdafx.h"#include"SCOMM.h"#include"SCOMMDlg.h"#ifdef _DEBUG#define new DEBUG_NEW#endif// 用于应用程序“关于”菜单项的CAboutDlg 对话框class CAboutDlg : public CDialog{public:CAboutDlg();// 对话框数据enum { IDD = IDD_ABOUTBOX };protected:virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持// 实现protected:DECLARE_MESSAGE_MAP()};CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD){}void CAboutDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);}BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)END_MESSAGE_MAP()// CSCOMMDlg 对话框CSCOMMDlg::CSCOMMDlg(CWnd* pParent /*=NULL*/): CDialog(CSCOMMDlg::IDD, pParent), m_ReceiveData(_T("")), m_strSendData(_T("")){m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);//自己添加初始化变量值m_bAutoSend=FALSE;m_bStopDispRXData=FALSE;m_bOpenPort=FALSE;m_nCycleTime=1000;}void CSCOMMDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);//接收区域DDX_Control(pDX, IDC_COMBO_COMSELECT, m_Com);DDX_Control(pDX, IDC_COMBO_SPEED, m_Speed);DDX_Control(pDX, IDC_COMBO_STOPBITS, m_StopBits);DDX_Control(pDX, IDC_COMBO_DATABITS, m_DataBits);DDX_Control(pDX, IDC_COMBO_PARITY, m_Parity);DDX_Control(pDX, IDC_BUTTON_STOPDISP, m_ctrlStopDisp);DDX_Control(pDX, IDC_CHECK_HEXRECIEVE, m_ctrlHexReceieve);DDX_Control(pDX, IDC_BUTTON_OPENPORT, m_ctrlOpenPort);DDX_Control(pDX, IDC_EDIT_RECIVE, m_ctrlReceiveData);DDX_Text(pDX, IDC_EDIT_RECIVE, m_ReceiveData);DDX_Control(pDX, IDC_CHECK_AUTOCLEAR, m_ctrlAutoClear);//2个计数的DDX_Control(pDX, IDC_STATIC_RXCOUNT, m_ctrlRXCOUNT);DDX_Control(pDX, IDC_STATIC_TXCOUNT, m_ctrlTXCount);DDX_Control(pDX, IDC_BUTTON_COUNTRESET, m_ctrlCounterReset);//清空计数//发送区域DDX_Control(pDX, IDC_BUTTON_MANUALSEND, m_ctrlManualSend);DDX_Control(pDX, IDC_CHECK_AUTOSEND, m_ctrlAutoSend);DDX_Control(pDX, IDC_CHECK_HEXSEND, m_ctrlHexSend);DDX_Control(pDX, IDC_EDIT_SEND, m_ctrlEditSend);DDX_Text(pDX, IDC_EDIT_SEND, m_strSendData);DDX_Control(pDX, IDC_BUTTON_CLEARRECASENDA, m_ctrlClearTXData);//关闭按钮DDX_Control(pDX, IDC_BUTTON_CLOSE, m_ctrlClose);DDX_Control(pDX, IDC_STATIC_STATUS, m_ctrlPortStatus);}BEGIN_MESSAGE_MAP(CSCOMMDlg, CDialog)ON_MESSAGE(WM_COMM_RXCHAR, OnCommunication)//自加的ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()//}}AFX_MSG_MAPON_BN_CLICKED(IDC_BUTTON_MANUALSEND,&CSCOMMDlg::OnBnClickedButtonManualsend)ON_BN_CLICKED(IDC_BUTTON_OPENPORT,&CSCOMMDlg::OnBnClickedButtonOpenport)ON_WM_DESTROY()ON_WM_TIMER()ON_BN_CLICKED(IDC_CHECK_AUTOSEND, &CSCOMMDlg::OnBnClickedCheckAutosend) ON_EN_CHANGE(IDC_EDIT_SEND, &CSCOMMDlg::OnEnChangeEditSend)ON_EN_CHANGE(IDC_EDIT_CYCLETIME, &CSCOMMDlg::OnEnChangeEditCycletime) ON_BN_CLICKED(IDC_BUTTON_CLEAR_RECI_AREA,&CSCOMMDlg::OnBnClickedButtonClearReciArea)ON_BN_CLICKED(IDC_BUTTON_STOPDISP,&CSCOMMDlg::OnBnClickedButtonStopdisp)//ON_CBN_SELCHANGE(IDC_COMBO_DATABITS,&CSCOMMDlg::OnCbnSelchangeComboDatabits)ON_CBN_SELENDOK(IDC_COMBO_COMSELECT,&CSCOMMDlg::OnCbnSelendokComboComselect)ON_CBN_SELENDOK(IDC_COMBO_SPEED, &CSCOMMDlg::OnCbnSelendokComboSpeed)ON_CBN_SELENDOK(IDC_COMBO_PARITY, &CSCOMMDlg::OnCbnSelendokComboParity)ON_CBN_SELENDOK(IDC_COMBO_DATABITS, &CSCOMMDlg::OnCbnSelendokComboDatabits) ON_CBN_SELENDOK(IDC_COMBO_STOPBITS, &CSCOMMDlg::OnCbnSelendokComboStopbits) ON_BN_CLICKED(IDC_BUTTON_CLOSE, &CSCOMMDlg::OnBnClickedButtonClose)ON_BN_CLICKED(IDC_BUTTON_CLEARRECASENDA,&CSCOMMDlg::OnBnClickedButtonClearrecasenda)ON_BN_CLICKED(IDC_BUTTON_COUNTRESET,&CSCOMMDlg::OnBnClickedButtonCountreset)ON_BN_CLICKED(IDOK, &CSCOMMDlg::OnBnClickedOk)END_MESSAGE_MAP()// CSCOMMDlg 消息处理程序BOOL CSCOMMDlg::OnInitDialog(){CDialog::OnInitDialog();// 将“关于...”菜单项添加到系统菜单中。
MTK 串口调试
MTK 串口调试(仅供内部使用)拟制: 日期: 2007.10.12 审核: 日期: yyyy-mm-dd 核准: 日期: yyyy-mm-dd 签发:日期:yyyy-mm-dd文档版本:版权所有 侵权必究文件修改记录串口调试1.对串口的设置:1)uart.c 中UART_HWInit 完成对各串口的波特率、数据位等之类初始化设置。
默认为115200。
若需调整波特率则可在此处设置。
也可调用U_SetBaudRate进行设置。
2)trace口的波特率设置如下在NVRAM_EF_PORT_SETTING_DEFAULT。
2.串口的切换:1)trace口的切换:nvram_common_config.c 中static kal_uint8 const NVRAM_EF_PORT_SETTING_DEFAULT[] ={#if defined(__ONL Y_ONE_UART__)0x63, 0x00, /* TST uses uart_port2(value is 1) */0x00, 0x00, /* APP uses uart_port1 */#else0x00, 0x00, /* TST uses uart_port2(value is 1) */表示哪个串口作输出Trace口,0x01, 0x00, /* APP uses uart_port1 */表示哪个串口用于AT。
#endif/*设置为0x00则表示串口1设置为Trace模式, 0x01表示串口2设置为Trace , 0x63表示不用Trace*/#if defined(EMPTY_MMI)0x00, 0x10, 0x0E, 0x00, /* tst default baud rate base = 921600 = 0x000E1000 */ #else0x00, 0xC2, 0x01, 0x00, /* tst default baud rate base = 115200 = 0x0001C200 */ #endif设置trace串口的波特率#if defined (__GPRS_MODE__)0x00, 0xC2, 0x01, 0x00, /* ps default baud rate base = 115200 = 0x0001C200 */ #else0x00, 0xE1, 0x00, 0x00, /* ps default baud rate base = 57600 = 0x0000E100 */ #endif设置at串口的波特率0x00, /* High SpeedSIM */0x00, /* SWDBG */0x03, 0x63, /* uart power setting, plus 1-byte padding */0x00, 0x00,0x00, 0x00 /* CTI baud rate */};0x03 -- 串口1、2 powner on0x07-- 串口1、2 、3 powner on这些设置也可在暗码“*#3646633#”中设置。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
串口调试助手预源代码using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.IO;using System.IO.Ports;using System.Threading;using DevExpress.XtraEditors;using System.Text.RegularExpressions;namespace WindowsFormsApplication3{public partial class Form1 : XtraForm {SerialPort sp1 = new SerialPort(); int Flag = 0;int StateChanged = 0;int StateChanged_Ascii = 1;int StateChanged_16 = 0;string Temp = null;string Temp_memoSend = null;private void memoSend_EditValueChanged(object sender, EventArgs e){}public Form1(){InitializeComponent();sp1.DataReceived += sp1_DataReceived;}private void Form1_Load(object sender, EventArgs e){this.MaximizeBox = false;//检查是否有串口string[] str = SerialPort.GetPortNames();if (str == null){MessageBox.Show("本机没有串口!", "error");return;}//添加串口项目foreach (string port in System.IO.Ports.SerialPort.GetPortNames()) {cbSerial.Properties.Items.Add(port);}//串口设置默认选择项cbSerial.SelectedIndex = 0;Control.CheckForIllegalCrossThreadCalls = false;sp1.DataReceived += newSerialDataReceivedEventHandler(sp1_DataReceived); //订阅委托}private void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgse){}private void OpenSerial_Click(object sender, EventArgs e){sp1.Close();//SerialPort sp1 = new SerialPort();if (!sp1.IsOpen)//串口是关闭的,设置参数,打开串口{try{//获取串口号string serialName = cbSerial.SelectedItem.ToString(); sp1.PortName = serialName;//设置各参数string strBaudRate = cbBaudRate.Text;string strDateBits = cbDataBits.Text;string strStopBits = cbStop.Text;sp1.BaudRate = Convert.ToInt32(strBaudRate);//波特率sp1.DataBits = Convert.ToInt32(strDateBits);//数据位switch (cbStop.Text) //停止位{case "1":sp1.StopBits = StopBits.One;break;case "1.5":sp1.StopBits = StopBits.One;break;case "2":sp1.StopBits = StopBits.Two;break;default:MessageBox.Show("Error:参数不正确!", "Error"); break;}switch (cbParity.Text) //校验位{case "无":sp1.Parity = Parity.None;break;case "奇校验":sp1.Parity = Parity.Odd;break;case "偶校验":sp1.Parity = Parity.Even;break;default:MessageBox.Show("Error:参数不正确!", "Error"); break;}if (sp1.IsOpen == true){sp1.Close();}sp1.Open();//btnOpen.Enabled = false;labSerial.Text = "串口号:" + sp1.PortName;labState.Text = "状态:打开";}catch (System.Exception ex){MessageBox.Show("Error:" + ex.Message, "Error");return;}}}//private void CloseSerial_Click(object sender, EventArgs e)//{// if (sp1.IsOpen)// {// sp1.Close();// labSerial.Text = "串口号:" + sp1.PortName;// labState.Text = "状态:关闭";// }//}private void Send_Click(object sender, EventArgs e){string StrSend = memoSend.Text;if (!sp1.IsOpen){MessageBox.Show("请先打开串口!", "Error");return;}else{if (rbtnSendStr.Checked) //字符串发送{if (ckTimeSend.Checked&& !(string.IsNullOrEmpty(textTime.Text)))//判断是否定时发送数据{string Time = textTime.Text;tmSend.Interval = int.Parse(Time) * 1000;//时间单位是秒,化成毫秒单位tmSend.Start(); //开启定时器}else{sp1.Write(StrSend); //写入数据}}else //十六进制发送{if (ckTimeSend.Checked&& !(string.IsNullOrEmpty(textTime.Text))){string Time = textTime.Text;tmSend.Interval = int.Parse(Time) * 1000;tmSend.Start();}else{string StrSend_1 = StrSend.Trim(); //去掉前后的空格//string StrSend_2 = StrSend_1.Replace(" ", "");//string StrSend_3 = string.Join(" ",Regex.Matches(StrSend_2, @"..|.").Cast<Match>().ToList());string[] StrArray = StrSend_1.Split(' '); //用空格符隔开字符串数组var Str_Send = new List<string>();// int byteBufferLength = StrArray.Length; //数组StrArray的长度for (int i = 0; i < StrArray.Length; i++){if (StrArray[i].Trim() == ""){//byteBufferLength--;continue;}else{if (StrArray[i].Length < 3){Str_Send.Add(StrArray[i]);}else{Str_Send.AddRange(Devide(StrArray[i]));}}}int byteBufferLength = Str_Send.Count;byte[] byteBuffer = new byte[byteBufferLength];int ii = 0;for (int i = 0; i < Str_Send.Count; i++){//Byte[] bytesOfStr =Encoding.Default.GetBytes(StrArray[i]);int decNum = 0;//if (StrArray[i] == " ")//{// continue;//}//else//{//decNum = Convert.ToInt32(Str_Send[i], 16); //把字符串转成16进制数//byteBuffer[ii] = Convert.ToByte(decNum);//}try{decNum = Convert.ToInt32(Str_Send[i], 16); //把字符串转成16进制数byteBuffer[ii] = Convert.ToByte(decNum);}catch (System.Exception ex){MessageBox.Show("输入错误!", "提示");return;}ii++;}sp1.Write(byteBuffer, 0, byteBuffer.Length);//从第0个开始写入byteBuffer,长度bytebuffer的长度。