串口通讯测试程序的源代码
经典的串口调试工具源代码(一)
经典的串口调试助手源代码(一)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 ' 转让控制权,以便让操作系统处理其它的事件。
C语言串口通信-源代码
C语言串口通信-源代码#include<tdio.h>#include<do.h>#include<conio.h>#include<tring.h>#defineCOM2320某2f8#defineCOMINT0某0b#defineMa某BufLen500#definePort82590某20#defineEofInt0某20taticcharintvectnum;taticunignedcharmakb;taticunignedcharBuffer[Ma某BufLen];taticintCharInBuf,CircIn,CircOut;taticvoid(interruptfar某OldAyncInt)();taticvoidinterruptfarAyncInt(void);unignedcharData,unignedcharStop,unignedcharParity){ unignedcharHigh,Low;intf;intvectnum=IntVectNum;CharInBuf=0;CircIn=0;CircOut=0;diable();OldAyncInt=getvect(IntVectNum);etvect(IntVectNum,Ay ncInt);enable();makb=inp(Port8259+1);if(IntVectNum==0某0c)outp(Port8259+1,makb&0某ef);eleoutp(Port8259+1,makb&0某f7);}taticvoidinterruptfarAyncInt(void){diable();if(CharInBuf<Ma某BufLen)if(CircIn<Ma某BufLen-1)CircIn++;eleCircIn=0;if(CircIn==CircOut)CircOut++;eleCharInBuf++;enable();outp(Port8259,EofInt);}voidRetore(void)etvect(intvectnum,OldAyncInt);outp(Port8259+1,makb);}intGetCharInBuf(unignedchar某Char) {intFlag;Flag=-1;if(CharInBuf>0){(某Char)=Buffer[CircOut];if(CircOut<Ma某BufLen-1)CircOut++; eleCircOut=0;CharInBuf--;Flag=0;}returnFlag;}intSendChar(unignedcharChar)return0;}main(){inti,c;unignedcharInChar;Init_COM(COM232,COMINT,1200,8,1,0); while(1){if(kbhit()){if((InChar=getch())==27)break; elewhile(SendChar(InChar));}if(GetCharInBuf(&InChar)==0)printf("%c",InChar);}Retore();}接收程序:#include<do.h>#include<ftream.h>#include<conio.h>#include<tdio.h>#include<tdlib.h>#include<math.h>#defineR某D0//接收voidInt(){unignedcharkey,key2;if(peek(0某40,port某2)==0){e某it(1);}ele{};Getportaddr(port);//得到串口地址SerInit(SER_BAUD_9600,SER_PARITY_EVEN|SER_BITS_8|SER_STOP_1) ;//初始化串口,设置波特率等SerOpen();do{if(kbhit()){key2=getch();if(key2==27){break;}};key=getb();if(key!=0某ff){printf("%某\t",key);FILE某fp;fp=fopen("C:\\Receivedata.dat","ab");//可选择接收数据的存放文件路径和文件名if(fp==NULL)printf("Fileopenerror!");//fputc(key,fp);fwrite(&key,izeof(unignedchar),1,fp);fcloe(fp);}}while(key2!=27);SerCloe();//printf("%dcharhabeenreceived\n",incount); //printf("%dcharhabeenended\n",outcount);//printf("\num=%d\n",um);}{printf("PleaeinputthereceiveCOMnum:(1~4)\n"); Cloe_Serial(intport_bae){outp(port_bae+SER_MCR,0);outp(port_bae+SER_IER,0);outp(PIC_IMR,old_int_mak);if(port_bae==COM_1){_do_etvect(INT_SER_PORT_0,Old_Ir);}ele{_do_etvect(INT_SER_PORT_1,Old_Ir);}}/某-------------发送应用----------------某/ voidmain(intargc,char某argv[]){charch,pre;intdone=0;FILE某fp;argc=2;if(argc<2){printf("\nUage:diplayfilename.wav!!!");//e某it(1);}if((fp=fopen(argv[1],"r+b"))==NULL){printf("cannotopenthefile\n");//e某it(0);}feek(fp,0,SEEK_SET);Open_Serial(COM_1,SER_BAUD_9600,SER_PARITY_EVEN|SER_STOP_1);printf("preanykeytobeginending");getch();//Serial_Write('');//该语句可用于发送单个字符while(!done&&ch!=EOF)//发送文件开始{ch=fgetc(fp);SER_BITS_8|//if(ch==EOF)Serial_Write(27);Serial_Write(ch);delay(30);if( kbhit()){pre=getch();if(pre==27){Serial_Write(27);done=1;}}}Cloe _Serial(COM_1);fcloe(fp);}下面介绍最重要的MFC:CWnd:窗口,它是大多数“看得见的东西”的父类(Window里几乎所有看得见的东西都是一个窗口,大窗口里有许多小窗口),比如视图CView、框架窗口CFrameWnd、工具条CToolBar、对话框CDialog、按钮CButton,etc;一个例外是菜单(CMenu)不是从窗口派生的。
C语言实现串口通信
C语言实现串口通信在使用系统调用函数进行串口通信之前,需要打开串口设备并设置相关参数。
打开串口设备可以使用open(函数,设置串口参数可以使用termios结构体和tcsetattr(函数。
以下是一个简单的串口通信接收数据的示例代码:```c#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include <unistd.h>#include <termios.h>int mainint fd; // 串口设备文件描述符char buff[255]; // 存储接收到的数据int len; // 接收到的数据长度//打开串口设备fd = open("/dev/ttyS0", O_RDONLY);if (fd < 0)perror("Failed to open serial port");return -1;}//设置串口参数struct termios options;tcgetattr(fd, &options);cfsetspeed(&options, B1200); // 设置波特率为1200 tcsetattr(fd, TCSANOW, &options);//接收数据while (1)len = read(fd, buff, sizeof(buff)); // 从串口读取数据if (len > 0)buff[len] = '\0'; // 将接收到的数据转为字符串printf("Received data: %s\n", buff);}}//关闭串口设备close(fd);return 0;```这段代码首先通过open(函数打开串口设备文件"/dev/ttyS0",然后使用tcgetattr(函数获取当前设置的串口参数,接着使用cfsetspeed(函数设置波特率为1200,最后使用tcsetattr(函数将设置好的串口参数写回。
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;}。
Linux串口测试程序
return g_PCUART_fd; }
uart_init int
( int COM, int BAUD, int databits, int stopbit, int paritybit )
{ int fd_uart;
struct termios options;
if( COM1 == COM ) {
/* ===============================================================================
********************
<lihf> linux串口测试代码
*******************
* Linux版本号2.6.23.17
printf("[ERROR]Uart databits is wrong! \n"); goto ↓uart_init_fail; }
switch( stopbit )
{
case 1 : options.c_cflag &= ~CSTOPB; break; //1位停止位 case 2 : options.c_cflag |= CSTOPB; break; //2位停止位
BAUD = B9600; }
if( cfsetospeed(&options, BAUD) < 0 )
{ printf("[fail] Set uart output baudrate fail!\n"); goto ↓uart_init_fail;
}
if( cfsetispeed(&options, BAUD) < 0 )
串口通信源代码
//
#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;
C语言串口通信-源代码
#include <stdio.h>#include <dos.h>#include <conio.h>#include <string.h>#define COM232 0x2f8#define COMINT 0x0b#define MaxBufLen 500#define Port8259 0x20#define EofInt 0x20static int comportaddr;static char intvectnum;static unsigned char maskb;static unsigned char Buffer[MaxBufLen];static int CharsInBuf,CircIn,CircOut;static void (interrupt far *OldAsyncInt)();static void interrupt far AsyncInt(void);void Init_COM(int ComPortAddr, unsigned char IntVectNum, int Baud, unsigned char Data, unsigned char Stop, unsigned char Parity) {unsigned char High,Low;int f;comportaddr=ComPortAddr;intvectnum=IntVectNum;CharsInBuf=0;CircIn=0;CircOut=0;f=(Baud/100);f=1152/f; High=f/256;Low=f-High*256;outp(ComPortAddr+3,0x80);outp(ComPortAddr,Low);outp(ComPortAddr+1,High);Data=(Data-5)|((Stop-1)*4);if(Parity==2) Data=Data|0x18;else if(Parity==1) Data=Data|0x8;outp(ComPortAddr+3,Data);outp(ComPortAddr+4,0x0a);outp(ComPortAddr+1,0x01);disable();OldAsyncInt=getvect( IntVectNum );setvect( IntVectNum, AsyncInt );enable();maskb=inp(Port8259+1);if(IntVectNum==0x0c)outp(Port8259+1,maskb&0xef); else outp(Port8259+1,maskb&0xf7);}static void interrupt far AsyncInt(void){disable();if(CharsInBuf<MaxBufLen)Buffer[CircIn]=inp(comportaddr);if(CircIn<MaxBufLen-1) CircIn++;else CircIn=0;if(CircIn==CircOut) CircOut++;else CharsInBuf++;enable();outp(Port8259,EofInt);}void Restore(void){setvect(intvectnum,OldAsyncInt);outp(Port8259+1,maskb);}int GetCharInBuf(unsigned char *Char){int Flag;Flag=-1;if(CharsInBuf>0){(*Char)=Buffer[CircOut];if(CircOut<MaxBufLen-1)CircOut++;else CircOut=0;CharsInBuf--;Flag=0;}return Flag;}int SendChar(unsigned char Char){if((inp(comportaddr+5)&0x20)==0) return -1; outp(comportaddr,Char);return 0;}main(){int i,c;unsigned char InChar;Init_COM(COM232,COMINT,1200,8,1,0);while(1){if(kbhit()){if((InChar=getch())==27)break;else while(SendChar(InChar));}if(GetCharInBuf(&InChar)==0)printf("%c",InChar);}Restore();}接收程序:#include <dos.h>#include <fstream.h>#include <conio.h>#include <stdio.h>#include <stdlib.h>#include <math.h>#define RXD 0 //接收#define TXD 0 //发送#define LSB 0 //波特率调节低8位#define MSB 1 //波特率调节高8位#define IER 1 // 中断起用寄存器#define IIR 2 //中断标识寄存器#define LCR 3 //线路控制寄存器#define MCR 4 //调制解调器控制寄存器#define LSR 5 //线路状态寄存器#define MSR 6 //调制解调器状态寄存器#define IERV 1#define OUT2 0x08#define ERTS 2#define EDTR 1#define EMPTY 0X20#define READY 0X30#define ICREG 0X20#define IMASKREG 0X21#define EOI 0X20#define WAITCOUNT 5000#define BUFFLEN 2048 //用于存储字符的数组的界#define ALTE 0X12#define ALTQ 0X10#define SER_BAUD_1200 96#define SER_BAUD_2400 48#define SER_BAUD_9600 0x0C#define SER_BAUD_19200 6#define SER_STOP_1 0 /*/ 1 stop bit per character*/#define SER_STOP_2 4 /*/ 2 stop bits per character*/#define SER_BITS_5 0 /*/ send 5 bit characters*/#define SER_BITS_6 1 /*/ send 6 bit characters*/#define SER_BITS_7 2 /*/ send 7 bit characters*/#define SER_BITS_8 3 /*/ send 8 bit characters*/#define SER_PARITY_NONE 0 /*/ no parity*/#define SER_PARITY_ODD 8 /*/ odd parity*/#define SER_PARITY_EVEN 24 /*/ even parity*/int port;int ComNum;unsigned portaddr;unsigned portf;unsigned int baudtable[]={0x180,0xc0,0x60,0x30,0x18,0x0c,0x06};unsigned char paritytable[]={0x08,0x18,0x00,0x28,0x38};unsigned char buffer[BUFFLEN];//recv bufint buffin=0;int buffout=0;int incount=0;int outcount=0;void interrupt(*vect_com)(...);void putb(unsigned char ch)//write a char to the recvbuf 将中断得到的数据写到缓冲区{int temp;temp=buffin;if(++buffin==BUFFLEN)buffin=0;if(buffin!=buffout){buffer[buffin]=ch;// printf("bufferin[%d]=%c",buffer[buffin]);// getch();}elsebuffin=temp;};unsigned char getb()//read a char from the recvbuf{if(buffout!=buffin){if(++buffout==BUFFLEN)buffout=0;//printf("bufferout[%d]=%c",buffout,buffer[buffout]);return(buffer[buffout]);}elsereturn(0xff);};/*unsigned char sender( unsigned char ch){outportb(portaddr2+TXD,ch);printf("\nsender outportdata=%c\n",ch);outcount++;return(1);};*/void interrupt receiver(...){unsigned char ch;ch=inportb(portaddr+RXD);putb(ch);incount++; //记录接收了多少个数据。
串口测试软件 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 & "已成功打开。
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函数来实现串口的初始化、发送数据和接收数据操作。
(完整版)MATLAB串口通信设计源码
(完整版)MATLAB串口通信设计源码function varargout = PJSerialCOM(varargin)% PJSERIALCOM M-file for PJSerialCOM.fig% PJSERIALCOM, by itself, creates a new PJSERIALCOM or raises the existing% singleton*.%% H = PJSERIALCOM returns the handle to a new PJSERIALCOM or the handle to% the existing singleton*.%% PJSERIALCOM('CALLBACK',hObject,eventData,handles,...) calls thelocal% function named CALLBACK in PJSERIALCOM.M with the given input arguments.%% PJSERIALCOM('Property','Value',...) creates a new PJSERIALCOM or raises the% existing singleton*. Starting from the left, property value pairs are% applied to the GUI before PJSerialCOM_OpeningFcn gets called. An% unrecognized property name or invalid value makes property application% stop. All inputs are passed to PJSerialCOM_OpeningFcn via varargin.%% *See GUI Options on GUIDE's Tools menu. Choose "GUIallows only one% instance to run (singleton)".%% See also: GUIDE, GUIDATA, GUIHANDLES% Edit the above text to modify the response to help PJSerialCOM% Last Modified by GUIDE v2.5 26-May-2012 18:45:14 % Begin initialization code - DO NOT EDITgui_Singleton = 1;gui_State = struct( 'gui_Name' 'gui_Singleton' 'gui_OpeningFcn''gui_OutputFcn''gui_LayoutFcn''gui_Callback' if nargin && ischar(varargin{1})gui_State.gui_Callback =str2func(varargin{1}); endif nargout[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); elsegui_mainfcn(gui_State, varargin{:});end% End initialization code - DO NOT EDIT% --- Executes just before PJSerialCOM is made visible.function PJSerialCOM_OpeningFcn(hObject, eventdata, handles, varargin)% This function has no output args, see OutputFcn.% hObject handle to figure% eventdata reserved - to be defined in a future version of MATLABmfilename, ... gui_Singleton, ..., @PJSerialCOM_OpeningFcn,@PJSerialCOM_OutputFcn, [] , ... []);% handles structure with handles and user data (see GUIDATA)% varargin command line arguments to PJSerialCOM (see VARARGIN)% Choose default command line output for PJSerialCOM handles.output = hObject;% Update handles structure guidata(hObject, handles);% UIWAIT makes PJSerialCOM wait for user response (see UIRESUME) % uiwait(handles.figPJSerialCOM); set(handles.btnClosePort, 'Enable' , 'off' ); set(handles.btnSendData, 'Enable' , 'Off' );setappdata(handles.figPJSerialCOM, 'u' , '' );% --- Outputs from this function are returned to the command line.function varargout = PJSerialCOM_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT);% hObject handle to figure% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% Get default command line output from handles structure varargout{1} = handles.output;% --- Executes on selection change in pumComPort. function pumComPort_Callback(hObject, eventdata, handles)% hObject handle to pumComPort (see GCBO)% eventdata reserved - to be defined in a future version ofMATLAB% handles structure with handles and user data (see GUIDATA)% Hints: contents = get(hObject,'String') returns pumComPort contents as cell array% contents{get(hObject,'Value')} returns selected item from pumComPort % --- Executes during object creation, after setting all properties. functionpumComPort_CreateFcn(hObject, eventdata, handles) % hObject handle to pumComPort (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. get(0, 'defaultUicontrolBackgroundColor' set(hObject, 'BackgroundColor' , 'white' );end% --- Executes on selection change in pumBaudRate. functionpumBaudRate_Callback(hObject, eventdata, handles)if ispc && isequal(get(hObject, 'BackgroundColor' ),))% hObject handle to pumBaudRate (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% Hints: contents = get(hObject,'String') returns pumBaudRate contents as cellarray% contents{get(hObject,'Value')} returns selected item from pumBaudRate % --- Executes during object creation, after setting all properties.function pumBaudRate_CreateFcn(hObject, eventdata, handles)% hObject handle to pumBaudRate (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called% Hint: popupmenu controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject, 'BackgroundColor' ), get(0, 'defaultUicontrolBackgroundColor' )) set(hObject, 'BackgroundColor' , 'white' );end% --- Executes on selection change in pumDataBits. function pumDataBits_Callback(hObject, eventdata, handles)% hObject handle to pumDataBits (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% Hints: contents = get(hObject,'String') returns pumDataBits contents as cellarray% contents{get(hObject,'Value')} returns selected item from pumDataBits % --- Executes during object creation, aftersetting all properties.function pumDataBits_CreateFcn(hObject, eventdata, handles)% hObject handle to pumDataBits (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called % Hint:popupmenu controls usually have a white background on Windows. % See ISPCand COMPUTER.if ispc && isequal(get(hObject, get(0, 'defaultUicontrolBackgroundColor' set(hObject, 'BackgroundColor'end% --- Executes on selection change in pumStopBits.function pumStopBits_Callback(hObject, eventdata, handles) % hObject handle to pumStopBits (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB 'BackgroundColor' )) , 'white' ); ),% handles structure with handles and user data (see GUIDATA) % Hints:contents = get(hObject,'String') returns pumStopBits contents as cell array% contents{get(hObject,'Value')} returns selected item from pumStopBits% --- Executes during object creation, after setting all properties. functionpumStopBits_CreateFcn(hObject, eventdata, handles)% hObject handle to pumStopBits (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called% Hint: popupmenu controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject, 'BackgroundColor' ),get(0, 'defaultUicontrolBackgroundColor' )) set(hObject, 'BackgroundColor' ,'white' );end% --- Executes on selection change in pumParity.function pumParity_Callback(hObject, eventdata, handles)% hObject handle to pumParity (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% Hints: contents = get(hObject,'String') array% contents{get(hObject,'Value')} % --- Executes duringobject creation, after setting all properties. function pumParity_CreateFcn(hObject, eventdata, handles)% hObject handle to pumParity (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called % Hint:popupmenu controls usually have a white background on Windows. % See ISPCand COMPUTER.if ispc && isequal(get(hObject, 'BackgroundColor' ),get(0, 'defaultUicontrolBackgroundColor' )) set(hObject, 'BackgroundColor' ,'white' );end % --- Executes on selection change in pumFlowControl. functionpumFlowControl_Callback(hObject, eventdata, handles)% hObject handle to pumFlowControl (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% Hints: contents = get(hObject,'String') returns pumFlowControl contentsreturns pumParity contents returns selected item from as cell pumParityas cell array% contents{get(hObject,'Value')} returns selected item from pumFlowControl % --- Executes during object creation, after setting all properties. function pumFlowControl_CreateFcn(hObject, eventdata, handles) % hObject handle to pumFlowControl (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called% Hint: popupmenu controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject, 'BackgroundColor' ), get(0, 'defaultUicontrolBackgroundColor' )) set(hObject, 'BackgroundColor' , 'white' );endfunction edtRecvData_Callback(hObject, eventdata, handles) % hObject handle to edtRecvData (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% Hints: get(hObject,'String') returns contents of edtRecvData as text% str2double(get(hObject,'String')) returns contents of edtRecvDataas a double% --- Executes during object creation, after setting all properties. functionedtRecvData_CreateFcn(hObject, eventdata, handles)% hObject handle to edtRecvData (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called% Hint: edit controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject, 'BackgroundColor' ),get(0, 'defaultUicontrolBackgroundColor' )) set(hObject, 'BackgroundColor' , 'white' );end function edtSendData_Callback(hObject, eventdata,handles)% hObject handle to edtSendData (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% Hints: get(hObject,'String') returns contents of edtSendData as text% str2double(get(hObject,'String')) returns contents of edtSendDataas a double% --- Executes during object creation, after setting all properties. functionedtSendData_CreateFcn(hObject, eventdata, handles) % hObject handle to edtSendData (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject, 'BackgroundColor' ), get(0, 'defaultUicontrolBackgroundColor' ))set(hObject, 'BackgroundColor' , 'white' );end % --- Executes on button press in btnOpenPort.function btnOpenPort_Callback(hObject, eventdata, handles) % hObject handle to btnOpenPort (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (seeGUIDATA)comPort=get(handles.pumComPort, 'String' );handles.u_sCom=serial(comPort{get(handles.pumComPort, 'Value'baudRate=get(handles.pumBaudRate, set(handles.u_sCom, 'BaudRate' te,'Value' )}));dataBits=get(handles.pumDataBits,set(handles.u_sCom, 'DataBits' ts,'Value' )}));stopBits=get(handles.pumStopBits,set(handles.u_sCom, 'StopBits' ts,'Value' )})); parity=get(handles.pumParity, if strcmp(parity, '?T' )==1set(handles.u_sCom, 'Parity' else'String' );,str2double(baudRate{get(handles.pumBaudRa 'String' );,str2double(dataBits{get(handles.pumDataBi 'String' );,str2double(stopBits{get(handles.pumStopBi'String' );, 'none' );if strcmp(parity,set(handles.u_sCom, elseif strcmp(parity, set(handles.u_sCom, elseset(handles.u_sCom, end '??D £?e'==i'Parity' , 'odd' );'??D £?e'==i'Parity' , 'even' )'Parity' , 'none' )end endflowControl=get(handles.pumFlowControl,if strcmp(flowControl, '?T' )==1 set(handles.u_sCom, 'FlowControl' else'String' ); , 'none' );if strcmp(flowControl, set(handles.u_sCom, elseo 2?t' )==1'FlowControl' , 'hardware' );if strcmp(flowControl, set(handles.u_sCom, elseset(handles.u_sCom,「?t')==1'FlowControl' , 'software' );'FlowControl' , 'none' );)});fopen(handles.u_sCom); set(handles.txtStatus, set(hObject, 'Enable'set(handles.btnClosePort, %handles.u_timer=timer('TimerFcn',{@ReadCom,handles},'Per iod',1,'ExecutionMode','fixedrate');guidata(hObject,handles);set(handles.btnSendData, 'Enable' , 'On' );% function ReadCom(obj,eventdata,handles)% set(handles.txtStatus,'String','?y? u ? ae ? e y?Y');% readString=fread(handles.u_sCom,10);% set(handles.edtRecvData,'String',readString);% set(handles.txtStatus,'String','? oe ? e y?Y3 e 1|');% --- Executes on button press in btnClosePort.function btnClosePort_Callback(hObject, eventdata, handles) % hObject handle to btnClosePort (see GCBO)% eventdata reserved - to be defined in a future version ofMATLAB %handles structure with handles and user data (see GUIDATA) fclose(handles.u_sCom); % stop(handles.u_timer);% delete(handles.u_timer); handles.u_sCom=0; guidata(hObject,handles);set(handles.txtStatus, set(handles.btnOpenPort, set(handles.btnSendData,set(hObject, 'Enable' % --- Executes on button press in btnSendData.function btnSendData_Callback(hObject, eventdata, handles) % hObject handle to btnSendData (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)sendString=get(handles.edtSendData, 'String' );fwrite(handles.u_sCom,sendString);set(handles.txtStatus, 'String' set(handles.edtSendData, 'String'% start(handles.u_timer);,'7 ? ^e y?Y3 e 1):, '' ); function BytesAvailableFcnCallback(t,eventdata,handles)readString=fread(handles.u_sCom,1);u=getappdata(handles.figPJSerialCOM, 'u' ); endend endset(handles.u_sCom,set(handles.u_sCom,set(handles.u_sCom,set(handles.u_sCom, set(handles.u_sCom,les});'Timeout' ,1); 'InputBufferSize' ,1024);'BytesAvailableFcnMode' 'BytesAvailableFcnCount' 'BytesAvailableFcn' , 'byte' ); ,1); ,{@BytesAvailableFcnCallback,hand'Stri ng' ,'‘ 6 ?a u 3e 1|'); , 'off' ); 'Enable' , 'On' );'String' , '1? ±u 3e 1|' ); 'Enable', 'On' );'Enable' , 'Off' );, 'Off' );。
c语言怎么写串口通信编程
c语言怎么写串口通信编程串口通信是一种广泛应用于嵌入式系统和电子设备之间的通信方式。
无论是嵌入式开发还是电子设备控制,串口通信都是常见的需求。
在C语言中,实现串口通信需要通过操作串口的硬件寄存器和使用相应的通信协议来实现数据的发送和接收。
本文将一步一步介绍如何使用C语言编写串口通信程序。
第一步:打开串口要开始串口通信,首先需要打开串口。
在C语言中,可以使用文件操作函数来打开串口设备。
通常,串口设备被命名为/dev/ttyS0,/dev/ttyS1等,具体名称取决于系统。
下面是一个打开串口设备的示例代码:cinclude <stdio.h>include <fcntl.h>include <termios.h>int open_serial_port(const char *port) {int fd = open(port, O_RDWR O_NOCTTYO_NDELAY);if (fd == -1) {perror("open_serial_port");return -1;}设置串口属性struct termios options;tcgetattr(fd, &options);cfmakeraw(&options);cfsetspeed(&options, B9600);tcsetattr(fd, TCSANOW, &options);return fd;}int main() {const char *port = "/dev/ttyS0";int fd = open_serial_port(port);if (fd == -1) {打开串口失败,处理错误return -1;}串口已打开,可以进行数据的读写操作return 0;}在上面的代码中,open_serial_port函数用于打开指定的串口设备并进行一些必要的设置。
C语言串口通信源代码
C语言串口通信源代码#include#include#include#include#define COM232 0x2f8#define COMINT 0x0b#define MaxBufLen 500#define Port8259 0x20#define EofInt 0x20static int comportaddr;static char intvectnum;static unsigned char maskb;static unsigned char Buffer[MaxBufLen];static int CharsInBuf,CircIn,CircOut;static void (interrupt far *OldAsyncInt)();static void interrupt far AsyncInt(void);void Init_COM(int ComPortAddr, unsigned char IntVectNum, int Baud, unsigned char Data, unsigned char Stop, unsigned char Parity){unsigned char High,Low;int f;comportaddr=ComPortAddr;intvectnum=IntVectNum;CharsInBuf=0;CircIn=0;CircOut=0;f=(Baud/100);f=1152/f; High=f/256;Low=f-High*256;outp(ComPortAddr+3,0x80);outp(ComPortAddr,Low);outp(ComPortAddr+1,High);Data=(Data-5)|((Stop-1)*4);if(Parity==2) Data=Data|0x18;else if(Parity==1) Data=Data|0x8;outp(ComPortAddr+3,Data);outp(ComPortAddr+4,0x0a);outp(ComPortAddr+1,0x01);disable();OldAsyncInt=getvect( IntVectNum );setvect( IntVectNum, AsyncInt );enable();maskb=inp(Port8259+1);if(IntVectNum==0x0c)outp(Port8259+1,maskb&0xef); else outp(Port8259+1,maskb&0xf7);}static void interrupt far AsyncInt(void){disable();if(CharsInBuf<maxbuflen)< bdsfid="112" p=""></maxbuflen)<>Buffer[CircIn]=inp(comportaddr);if(CircIn<="" p="">else CircIn=0;if(CircIn==CircOut) CircOut++;else CharsInBuf++;enable();outp(Port8259,EofInt);}void Restore(void){setvect(intvectnum,OldAsyncInt);outp(Port8259+1,maskb);}int GetCharInBuf(unsigned char *Char){int Flag;Flag=-1;if(CharsInBuf>0){(*Char)=Buffer[CircOut];if(CircOut<maxbuflen-1)circout++;< bdsfid="135" p=""></maxbuflen-1)circout++;<>else CircOut=0;CharsInBuf--;Flag=0;}return Flag;}int SendChar(unsigned char Char){if((inp(comportaddr+5)&0x20)==0) return -1;outp(comportaddr,Char);return 0;}main(){int i,c;unsigned char InChar;Init_COM(COM232,COMINT,1200,8,1,0);while(1){if(kbhit()){if((InChar=getch())==27)break;else while(SendChar(InChar));}if(GetCharInBuf(&InChar)==0)printf("%c",InChar);}Restore();}接收程序:#include#include#include#include#include#include #define RXD 0 //接收#define TXD 0 //发送#define LSB 0 //波特率调节低8位#define MSB 1 //波特率调节高8位#define IER 1 // 中断起用寄存器#define IIR 2 //中断标识寄存器#define LCR 3 //线路控制寄存器#define MCR 4 //调制解调器控制寄存器#define LSR 5 //线路状态寄存器#define MSR 6 //调制解调器状态寄存器#define IERV 1#define OUT2 0x08#define ERTS 2#define EDTR 1#define EMPTY 0X20#define READY 0X30#define ICREG 0X20#define IMASKREG 0X21#define EOI 0X20#define WAITCOUNT 5000 #define BUFFLEN 2048 //用于存储字符的数组的界#define ALTE 0X12#define ALTQ 0X10#define SER_BAUD_1200 96#define SER_BAUD_2400 48#define SER_BAUD_9600 0x0C#define SER_BAUD_19200 6 #define SER_STOP_1 0 /*/ 1 stop bit per character*/ #define SER_STOP_2 4 /*/ 2 stop bits per character*/ #define SER_BITS_5 0 /*/ send 5 bit characters*/ #define SER_BITS_6 1 /*/ send 6 bit characters*/ #define SER_BITS_7 2 /*/ send 7 bit characters*/ #define SER_BITS_8 3 /*/ send 8 bit characters*/ #define SER_PARITY_NONE 0 /*/ no parity*/ #define SER_PARITY_ODD 8 /*/ odd parity*/ #define SER_PARITY_EVEN 24 /*/ even parity*/int port;int ComNum;unsigned portaddr;unsigned portf;unsigned int baudtable[]={0x180,0xc0,0x60,0x30,0x18,0x0c,0x06};unsigned char paritytable[]={0x08,0x18,0x00,0x28,0x38};unsigned char buffer[BUFFLEN];//recv bufint buffin=0;int buffout=0;int incount=0;int outcount=0;void interrupt(*vect_com)(...); void putb(unsigned char ch)//write a char to the recvbuf 将中断得到的数据写到缓冲区{int temp;temp=buffin;if(++buffin==BUFFLEN)buffin=0;if(buffin!=buffout){buffer[buffin]=ch;// printf("bufferin[%d]=%c",buffer[buffin]);// getch();}elsebuffin=temp;};unsigned char getb()//read a char from the recvbuf{if(buffout!=buffin){if(++buffout==BUFFLEN)buffout=0;//printf("bufferout[%d]=%c",buffout,buffer[buffout]);return(buffer[buffout]);}elsereturn(0xff);};/*unsigned char sender( unsigned char ch){outportb(portaddr2+TXD,ch);printf("\nsender outportdata=%c\n",ch); outcount++;return(1);};*/void interrupt receiver(...){unsigned char ch;ch=inportb(portaddr+RXD);putb(ch);incount++; //记录接收了多少个数据。
C51串口源代码实例
C51串口源代码实例串口实现函数:void init_uart(void){PCON=0x80; //倍频,减少误差率TMOD=0x25; //设置定时器1 为方式2(用于设置波特率);设置T0 为计数器模式1,用作HV 的检查TH1=0xF1; //装入初值波特率为9600 晶振27MHzTH1=0XF1TL1=0xF1;TR1=1; //启动定时器1SM0=0;SM1=1; //串口方式1,8 bit uartREN=1; //接收使能EA=1;ES=1;return;}void serial() interrupt 4{//uartflag = 1;RI=0;}//向串口发送一个字符void send_char(U8 ch) { ES=0;TI=0;SBUF=ch; while(!TI); TI=0;ES=1; } //向串口发送多个字符void send_chars(U8 *ch){U8i=0;ES=0;TI=0;for(i=0;ch[i]!=;i++){SBUF=ch[i];while(!TI);TI=0;}ES=1;}//向串口发送一个字符无需十六进制显示void send_u8(U8 ch){U8 tt;send_char(x30);//x30 其中30 是十六进制代表0send_char(x58); //x58 其中30 是十六进制代表xtt = ch >>4 ;if(ttsend_char(tt+0);}else{send_char(tt+A-10);}tt = ch &0x0F;if(ttsend_char(tt+0);}else{send_char(tt+A-10);}send_chars(““);}//向串口发送一个字符无需十六进制显示void send_u16(U16 ch){U8 tt;send_char(x30); //x30 其中30 是十六进制代表0send_char(x58); //x58 其中30 是十六进制代表xtt = ch >>12 ;if(ttsend_char(tt+0);}else{send_char(tt+A-10);}tt = (ch>>8) &0x0F;if(ttsend_char(tt+0);}else{send_char(tt+A-10);}tt = (ch>>4) &0x0F;if(ttsend_char(tt+0);}else{send_char(tt+A-10);}tt = ch &0x0F;if(ttsend_char(tt+0);}else{send_char(tt+A-10);}send_chars(““);}voiduart_welcome(){send_chars(“---------------------------------------------------------------”);send_chars(“Welcome to Tvia 5735 Uart Test V1.0”);send_chars(“Built time: 2013-09-24”);send_chars(“MCU FOSC:27Mhz Baud rate:9600”);send_chars(“Note:”);send_chars(“Serial debugging assistants do not need。
C51单片机串口通讯通用模块代码(可用于操作系统串口通讯)
C51单片机串口通讯通用模块代码(可用于操作系统串口通讯)#include#include "UART1.h"#include "commdriver.h"//当前适用于C51//可以根据具体CPU型号,修改宏定义和串口初始化代码就可以#define CPU_XTAL 22118400 //CPU频率#define FUNCTION_NULL 0 //没有定义函数#define COM_TI TI //发送中断寄存器#define COM_TI0() {TI = 0;} //发送中断寄存器清零#define COM_TI1() {TI = 1;} //发送中断寄存器置一( 强行置一触发发送中断)#define COM_TI_SBUF(dat) {SBUF = dat;} //发送数据到硬件缓冲区#define COM_TI_End() {return;} //发送结束处理函数#define COM_RI RI //接收中断寄存器#define COM_RI0() {RI = 0;} //接收中断寄存器清零#define COM_RI1() {RI = 1;} //接收中断寄存器置一#define COM_RI_SBUF(dat) {dat = SBUF;} //提取接收硬件缓冲区数据#define COM_TI_FLAG COM_TI //发送中断标志寄存器(非中断发送方式使用)#define COM_TI_FLAG0() COM_TI0() //发送中断标志寄存器清零(非中断发送方式使用)void (*COM1RevEvent)(unsigned char dat); //数据接收事件#define LenTxBuf 30 //发送缓冲区长度#define LenRxBuf 1 //接收缓冲区长度volatile unsigned char TxBuf1[LenTxBuf],RxBuf1[LenRxBuf]; //收发缓冲区实体volatile unsigned char *inTxBuf1,*outTxBuf1,*inRxBuf1,*outRxBuf1; //收发缓冲区读写指针volatile unsigned char TIflag1=1;//Note:It must be 1. //发送缓冲区为空标志//*********************#define _TxBuf TxBuf1#define _RxBuf RxBuf1#define _inTxBuf inTxBuf1#define _outTxBuf outTxBuf1#define _inRxBuf inRxBuf1#define _outRxBuf outRxBuf1#define _TIflag TIflag1/*************函数声明****************/#define _COMRevEvent COM1RevEvent //串口接收事件#define _USART_IRQ void USART1_IRQHandler(void) interrupt 4 //串口中断服务程序#define _COM_Buffer_Init void COM1_Buffer_Init(void) //串口缓冲区初始化#define _COM_Open void COM1_Open(unsigned int baudrate,void (*revevent)(unsigned char dat)) // 串口初始化#define _COM_Close void COM1_Close(void) //关闭串口#define _COM_GetOneByte unsigned charCOM1_GetOneByte(unsigned char *ch) //获取一个字节#define _COM_GetPChar unsigned char COM1_GetPChar(unsigned char *ch,unsigned char len) //获取指定长度字节数组#define _COM_RxByte unsigned char COM1_RxByte(void) //获取接收字节个数//********缓冲区中断方式发送(安全性高)#define _COM_SendOneByte unsigned char COM1_SendOneByte(unsigned char one_byte) // 发送一个字节#define _COM_SendPChar void COM1_SendPChar(unsigned char *P,unsigned char Len) //发送定长字节数组#define _COM_SendString void COM1_SendString(unsigned char *P) //发送字符串//********非缓冲区中断方式发送#define _COM_PrintOneByte void COM1_PrintOneByte(unsigned char c) // 发送一个字节#define _COM_PrintPChar void COM1_PrintPChar(unsigned char *buf,unsigned int len) //发送定长字节数组#define _COM_PrintString void COM1_PrintString(unsigned char *P) //发送字符串//*************内部引用模型函数(外部不关心,移植时修改后面函数名,要与上面对应的外部声明的函数名一致)*******************#define COM_GetOneByte_(ptr) COM1_GetOneByte(ptr) //与上面获取一个字节的函数对应#define COM_SendOneByte_(dat) COM1_SendOneByte(dat) //与上面发送一个字节的函数对应#define COM_PrintOneByte_(dat) COM1_PrintOneByte(dat) //与上面发送一个字节的函数对应//*********************函数模型定义区(不需要修改)*****************/****************************函数模型:void USART_IRQHandler(void)函数功能:串口中断服务程序入口参数:无返回值:无修改者:修改时间:修改内容简要:***************************/_USART_IRQ //串口1中断{volatile unsigned char *t;if(COM_RI){COM_RI0(); //清接收标记if(_COMRevEvent != FUNCTION_NULL) //自定义接收事件{COM_RI_SBUF(*_inRxBuf);_COMRevEvent(*_inRxBuf);}else{t = _inRxBuf;t++;if(t == (_RxBuf + LenRxBuf)) t = _RxBuf;if(t != _outRxBuf) //RxBuf No Full{COM_RI_SBUF(*_inRxBuf);_inRxBuf = t;}}}if(COM_TI){COM_TI0();if(_inTxBuf == _outTxBuf) {_TIflag = 1;COM_TI_End();};//TxBuf1 EmptyCOM_TI_SBUF(*_outTxBuf); _outTxBuf++;if(_outTxBuf == (_TxBuf+LenTxBuf)) _outTxBuf = _TxBuf;}}/****************************函数模型:void COM1_Buffer_Init(void)函数功能:串口1缓冲区初始化入口参数:无返回值:无修改者:修改时间:修改内容简要:***************************/_COM_Buffer_Init{_inTxBuf = _TxBuf;_outTxBuf = _TxBuf;_inRxBuf = _RxBuf;_outRxBuf = _RxBuf;}/****************************函数模型:void COM_Open(unsigned int baudrate,void (*revevent)(unsigned char dat))函数功能:系统串口初始化入口参数: unsigned int baudrate:串口波特率返回值:无修改者:修改时间:修改内容简要:***************************/_COM_Open{//定时器1做波特率发生器TI = 0; /* clear transmit interrupt */TR1 = 0; /* stop timer 1 */ET1 = 0; /* disable timer 1 interrupt */PCON |= 0x80; /* 0x80=SMOD: set serial baudrate doubler */ TMOD &= ~0xF0; /* clear timer 1 mode bits */TMOD |= 0x20; /* put timer 1 into MODE 2 */TH1 = (unsigned char) (256 - (CPU_XTAL / (16L * 12L * baudrate)));TR1 = 1; /* start timer 1 *///设置串口1模式SM0 = 0; SM1 = 1; /* serial port MODE 1 */SM2 = 0;REN = 1; /* enable serial receiver */RI = 0; /* clear receiver interrupt */TI = 0; /* clear transmit interrupt */ES = 1; /* enable serial interrupts */PS = 1; /* set serial interrupts to low priority */_COMRevEvent = revevent;}/****************************函数模型:void COM1_Close(void)函数功能:关闭系统串口入口参数:无返回值:无修改者:修改时间:修改内容简要:***************************/_COM_Close{}/****************************函数模型:unsigned char COM1_GetOneByte(unsigned char *ch)函数功能:获取一个字节入口参数:unsigned char *ch:接收字节指针返回值: unsigned char *ch:接收字节指针unsigned char :获取状态;0:成功,1:失败(缓冲区为空)修改者:修改时间:修改内容简要:***************************/_COM_GetOneByte{if(_inRxBuf == _outRxBuf) {return 0;}; //RxBuf Empty*ch = *_outRxBuf; _outRxBuf++;if(_outRxBuf==_RxBuf+LenRxBuf) _outRxBuf = _RxBuf;return 1;}/****************************函数模型:unsigned char COM_GetPChar(unsigned char *ch,unsigned char len)函数功能:获取指定长度字节数组入口参数: unsigned char *ch:接收字节数组指针unsigned char len:接收字节个数返回值: unsigned char *ch:接收字节数组指针unsigned char:实际接收字节个数修改者:修改时间:修改内容简要:***************************/_COM_GetPChar{unsigned char i = 0;do{len--;if(!COM_GetOneByte_(ch)) break;i++;ch++;}while(len);return i;}/****************************函数模型:unsigned char COM_RxByte(void)函数功能:获取接收缓冲区有效字节个数入口参数:无返回值: unsigned char:接收缓冲区有效字节个数修改者:修改时间:修改内容简要:***************************/_COM_RxByte{if(_inRxBuf>=_outRxBuf) return (_inRxBuf-_outRxBuf);else return LenRxBuf-(_outRxBuf-_inRxBuf);}/****************************函数模型:unsigned char COM_SendOneByte(unsigned char one_byte)函数功能:发送一个字节入口参数: unsigned char one_byte:发送的字节返回值:unsigned char:发送状态,0:成功,1:失败(缓冲区满)修改者:修改时间:修改内容简要:***************************/_COM_SendOneByte{volatile unsigned char *t;if(_TIflag){_TIflag = 0;COM_TI1();}t = _inTxBuf;t++;if(t == _TxBuf + LenTxBuf) t = _TxBuf;if(t == _outTxBuf) {return 1;};//TxBuf Full*_inTxBuf = one_byte;_inTxBuf = t;return 0;}/****************************函数模型:void COM_SendPChar(unsigned char *P,unsigned char Len)函数功能:发送定长字节数组入口参数: unsigned char *P:字节数组指针unsigned char Len:发送长度返回值:无修改者:修改时间:修改内容简要:***************************/_COM_SendPChar{while(Len){//while(COM1_SendOneByte(*P)); //发送失败,继续发送,知道发送成功COM_SendOneByte_(*P);P++;Len--;}}/****************************函数模型:void COM_SendString(unsigned char *P)函数功能:发送字符串入口参数: unsigned char *P:字符串指针返回值:无修改者:修改时间:修改内容简要:***************************/_COM_SendString{while(*P){COM_SendOneByte_(*P);P++;}}//**************** 非缓冲区中断方式发送/****************************函数模型:void COM_PrintOneByte(unsigned char c)函数功能:发送一个字节入口参数: unsigned char one_byte:发送的字节返回值:无修改者:修改时间:修改内容简要:***************************/_COM_PrintOneByte{COM_TI_FLAG0();COM_TI_SBUF(c); //发送数据while(!COM_TI_FLAG) ; //等待发送结束}/****************************函数模型:void COM_PrintPChar(unsigned char *buf,unsigned int len)函数功能:发送定长字节数组入口参数: unsigned char *P:字节数组指针unsigned char Len:发送长度返回值:无修改者:修改时间:修改内容简要:***************************/_COM_PrintPChar{while(len){COM_PrintOneByte_(*buf);buf ++;len--;}}/****************************函数模型:void COM_PrintString(unsigned char *P) 函数功能:发送字符串入口参数: unsigned char *P:字符串指针返回值:无修改者:修改时间:修改内容简要:***************************/_COM_PrintString{while(*P){COM_PrintOneByte_(*P);P++;}}。
stc15串口范例程序
stc15串口范例程序STC15是一种常见的单片机型号,它具有丰富的外设和功能,其中包括串口通信功能。
下面是一个简单的STC15串口通信的范例程序,供你参考:c.#include <STC15F2K60S2.H>。
#define FOSC 11059200L.#define BAUD 9600。
void InitUART() {。
SCON = 0x50; // 8位数据,可变波特率。
TMOD = 0x20; // 设置定时器1为模式2。
TH1 = 256 FOSC/12/32/BAUD; // 波特率9600。
TL1 = TH1; // 初始化TL1。
TR1 = 1; // 启动定时器1。
ES = 1; // 使能串口中断。
EA = 1; // 打开总中断。
}。
void UARTInterrupt() interrupt 4 {。
if (RI) {。
P0 = SBUF; // 串口接收到的数据通过P0口输出。
RI = 0; // 清零接收中断标志位。
}。
if (TI) {。
TI = 0; // 清零发送中断标志位。
}。
}。
void main() {。
InitUART(); // 初始化串口。
while (1) {。
// 主循环。
}。
}。
以上是一个简单的STC15串口通信的范例程序。
在这个程序中,我们首先定义了晶振频率和波特率,然后编写了初始化串口的函数InitUART。
在主函数main中,我们调用InitUART进行串口的初始化,然后进入一个无限循环。
当有数据通过串口接收到时,会触发串口中断UARTInterrupt,并将接收到的数据通过P0口输出。
这个程序可以作为一个基础的串口通信范例,你可以根据自己的实际需求进行修改和扩展。
希望这个范例对你有所帮助。
stm32f103串口程序代码
stm32f103串口程序代码STM32F103系列是意法半导体推出的一款32位单片机系列产品,该系列产品在嵌入式系统领域广泛应用。
其中,串口通信是单片机应用中常用的通信方式之一。
本文将介绍STM32F103的串口通信程序代码。
我们需要了解串口通信的基本原理。
串口通信是一种通过串行传输数据的通信方式,它将数据分为一系列的位依次传输。
串口通信一般包括发送和接收两个部分,发送数据时,将数据从高位到低位逐个发送;接收数据时,将数据从低位到高位逐个接收。
为了使数据传输更加稳定可靠,常常需要使用校验位进行数据的校验。
在STM32F103系列中,串口通信的实现需要使用USART模块。
USART 是一种通用的同步/异步收发器,它可以实现全双工通信。
串口通信的代码一般包括以下几个方面的内容:1. 引入头文件和定义宏:在开始编写串口通信的代码之前,我们需要引入相应的头文件,并定义一些宏。
头文件中包含了USART所需要的寄存器地址和一些相关的宏定义。
宏定义可以方便我们在代码中使用一些常用的参数。
2. 初始化USART模块:在使用USART进行串口通信之前,需要对USART模块进行初始化。
初始化的过程包括设置波特率、数据位、停止位、校验位等参数。
在STM32F103系列中,可以通过修改USART_CR1和USART_CR2寄存器来完成初始化。
3. 发送数据:发送数据时,需要将待发送的数据写入USART_DR寄存器中。
在发送数据之前,需要判断USART_SR寄存器中的状态位,确保USART_DR 寄存器为空,以免数据丢失。
发送数据完成后,可以通过判断USART_SR寄存器中的状态位,判断数据是否发送成功。
4. 接收数据:接收数据时,需要从USART_DR寄存器中读取接收到的数据。
在接收数据之前,需要判断USART_SR寄存器中的状态位,确保USART_DR 寄存器中有数据可读。
接收数据完成后,可以通过判断USART_SR寄存器中的状态位,判断数据是否接收成功。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
using System;using System.Drawing;using System.Collections;using ponentModel;using System.Windows.Forms;using System.Data;using System.Threading;namespace BusApp{/// <summary>/// Form1 的摘要说明。
/// </summary>public class Form1 : System.Windows.Forms.Form{private bel label1;private bel label2;private System.Windows.Forms.Button button1;private System.Windows.Forms.GroupBox groupBox1;private bel label3;private bel label4;private bel label5;private bel label6;private System.Windows.Forms.Button button2;private System.Windows.Forms.Button button3;private System.Windows.Forms.Button button4;private System.Windows.Forms.TextBox textBox8;private bel label7;public int iPort=1; //1,2,3,4public int iRate=9600; //1200,2400,4800,9600public byte bSize=8; //8 bitspublic byte bParity=0; // 0-4=no,odd,even,mark,spacepublic byte bStopBits=1; // 0,1,2 = 1, 1.5, 2public int iTimeout=1000;public mycom mycom1=new mycom();public byte[] recb;private System.Windows.Forms.TextBox msg;private System.Windows.Forms.TextBox t_port;private System.Windows.Forms.TextBox t_rate;private System.Windows.Forms.TextBox t_bytesize;private System.Windows.Forms.TextBox t_stopbyte;private System.Windows.Forms.TextBox t_parity;private System.Windows.Forms.TextBox t_send;private System.Windows.Forms.Button button5; //readTimeOut /// <summary>/// 必需的设计器变量。
/// </summary>private ponentModel.Container components = null; public Form1(){InitializeComponent();}/// <summary>/// 清理所有正在使用的资源。
/// </summary>protected override void Dispose( bool disposing ){if( disposing ){if (components != null){components.Dispose();}}base.Dispose( disposing );}#region Windows 窗体设计器生成的代码/// <summary>/// 设计器支持所需的方法 - 不要使用代码编辑器修改/// 此方法的内容。
/// </summary>private void InitializeComponent(){this.msg = new System.Windows.Forms.TextBox();bel1 = new bel();bel2 = new bel();this.t_send = new System.Windows.Forms.TextBox();this.button1 = new System.Windows.Forms.Button();this.groupBox1 = new System.Windows.Forms.GroupBox();this.button2 = new System.Windows.Forms.Button();this.t_port = new System.Windows.Forms.TextBox();bel3 = new bel();this.t_rate = new System.Windows.Forms.TextBox();bel4 = new bel();this.t_bytesize = new System.Windows.Forms.TextBox();bel5 = new bel();this.t_stopbyte = new System.Windows.Forms.TextBox();bel6 = new bel();this.t_parity = new System.Windows.Forms.TextBox();this.button3 = new System.Windows.Forms.Button();this.button4 = new System.Windows.Forms.Button();this.textBox8 = new System.Windows.Forms.TextBox();bel7 = new bel();this.button5 = new System.Windows.Forms.Button();this.groupBox1.SuspendLayout();this.SuspendLayout();//// msg//this.msg.ForeColor = System.Drawing.Color.Green;this.msg.Location = new System.Drawing.Point(0, 0);this.msg.Multiline = true; = "msg";this.msg.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;this.msg.Size = new System.Drawing.Size(512, 264);this.msg.TabIndex = 0;this.msg.Text = "";//// label1//bel1.Location = new System.Drawing.Point(16, 24); = "label1";bel1.Size = new System.Drawing.Size(56, 16);bel1.TabIndex = 1;bel1.Text = "串口号:";//// label2//bel2.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(64)), ((System.Byte)(0)));bel2.Location = new System.Drawing.Point(8, 280); = "label2";bel2.Size = new System.Drawing.Size(80, 16);bel2.TabIndex = 1;bel2.Text = "设置数据包:";//// t_send//this.t_send.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;this.t_send.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(128)), ((System.Byte)(0)));this.t_send.Location = new System.Drawing.Point(80, 272);this.t_ = "t_send";this.t_send.Size = new System.Drawing.Size(344, 21);this.t_send.TabIndex = 2;this.t_send.Text = "";//// button1//this.button1.Location = new System.Drawing.Point(432, 272); = "button1";this.button1.Size = new System.Drawing.Size(40, 23);this.button1.TabIndex = 3;this.button1.Text = "发送";this.button1.Click += new System.EventHandler(this.button1_Click);//// groupBox1//this.groupBox1.Controls.Add(this.button2);this.groupBox1.Controls.Add(this.t_port);this.groupBox1.Controls.Add(bel1);this.groupBox1.Controls.Add(bel3);this.groupBox1.Controls.Add(this.t_rate);this.groupBox1.Controls.Add(bel4);this.groupBox1.Controls.Add(this.t_bytesize);this.groupBox1.Controls.Add(bel5);this.groupBox1.Controls.Add(this.t_stopbyte);this.groupBox1.Controls.Add(bel6);this.groupBox1.Controls.Add(this.t_parity);this.groupBox1.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(64)), ((System.Byte)(0)));this.groupBox1.Location = new System.Drawing.Point(8, 304); = "groupBox1";this.groupBox1.Size = new System.Drawing.Size(176, 216);this.groupBox1.TabIndex = 4;this.groupBox1.TabStop = false;this.groupBox1.Text = "参数设置";//// button2//this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Popup;this.button2.Location = new System.Drawing.Point(80, 184); = "button2";this.button2.TabIndex = 3;this.button2.Text = "应用设置";this.button2.Click += new System.EventHandler(this.button2_Click);//// t_port//this.t_port.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;this.t_port.Location = new System.Drawing.Point(80, 16);this.t_ = "t_port";this.t_port.Size = new System.Drawing.Size(80, 21);this.t_port.TabIndex = 2;this.t_port.Text = "1";//// label3//bel3.Location = new System.Drawing.Point(16, 58); = "label3";bel3.Size = new System.Drawing.Size(56, 16);bel3.TabIndex = 1;bel3.Text = "波特率:";//// t_rate//this.t_rate.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;this.t_rate.Location = new System.Drawing.Point(80, 50);this.t_ = "t_rate";this.t_rate.Size = new System.Drawing.Size(80, 21);this.t_rate.TabIndex = 2;this.t_rate.Text = "9600";//// label4//bel4.Location = new System.Drawing.Point(16, 92); = "label4";bel4.Size = new System.Drawing.Size(56, 16);bel4.TabIndex = 1;bel4.Text = "数据位:";//// t_bytesize//this.t_bytesize.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.t_bytesize.Location = new System.Drawing.Point(80, 84);this.t_ = "t_bytesize";this.t_bytesize.Size = new System.Drawing.Size(80, 21);this.t_bytesize.TabIndex = 2;this.t_bytesize.Text = "8";//// label5bel5.Location = new System.Drawing.Point(16, 126); = "label5";bel5.Size = new System.Drawing.Size(56, 16);bel5.TabIndex = 1;bel5.Text = "停止位:";//// t_stopbyte//this.t_stopbyte.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.t_stopbyte.Location = new System.Drawing.Point(80, 118);this.t_ = "t_stopbyte";this.t_stopbyte.Size = new System.Drawing.Size(80, 21);this.t_stopbyte.TabIndex = 2;this.t_stopbyte.Text = "1";//// label6//bel6.Location = new System.Drawing.Point(16, 160); = "label6";bel6.Size = new System.Drawing.Size(56, 16);bel6.TabIndex = 1;bel6.Text = "校验位:";//// t_parity//this.t_parity.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.t_parity.Enabled = false;this.t_parity.Location = new System.Drawing.Point(80, 152);this.t_ = "t_parity";this.t_parity.Size = new System.Drawing.Size(80, 21);this.t_parity.TabIndex = 2;this.t_parity.Text = "0";//// button3//this.button3.Location = new System.Drawing.Point(472, 272); = "button3";this.button3.Size = new System.Drawing.Size(40, 23);this.button3.TabIndex = 3;this.button3.Text = "清空";this.button3.Click += new System.EventHandler(this.button3_Click);//// button4this.button4.FlatStyle = System.Windows.Forms.FlatStyle.Popup;this.button4.Location = new System.Drawing.Point(432, 312); = "button4";this.button4.Size = new System.Drawing.Size(72, 23);this.button4.TabIndex = 6;this.button4.Text = "初始化";//// textBox8//this.textBox8.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;this.textBox8.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(128)), ((System.Byte)(0)));this.textBox8.Location = new System.Drawing.Point(288, 312); = "textBox8";this.textBox8.Size = new System.Drawing.Size(136, 21);this.textBox8.TabIndex = 7;this.textBox8.Text = "";//// label7//bel7.Location = new System.Drawing.Point(200, 320); = "label7";bel7.Size = new System.Drawing.Size(100, 16);bel7.TabIndex = 8;bel7.Text = "设置本机地址:";//// button5//this.button5.FlatStyle = System.Windows.Forms.FlatStyle.Popup;this.button5.Location = new System.Drawing.Point(440, 504); = "button5";this.button5.Size = new System.Drawing.Size(64, 23);this.button5.TabIndex = 9;this.button5.Text = "关闭串口";this.button5.Click += new System.EventHandler(this.button5_Click);//// Form1//this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);this.ClientSize = new System.Drawing.Size(512, 533);this.Controls.Add(this.button5);this.Controls.Add(this.textBox8);this.Controls.Add(bel7);this.Controls.Add(this.button4);this.Controls.Add(this.groupBox1);this.Controls.Add(this.button1);this.Controls.Add(this.t_send);this.Controls.Add(this.msg);this.Controls.Add(bel2);this.Controls.Add(this.button3); = "Form1";this.Text = "串口通讯(小y设计)";this.Closing += new ponentModel.CancelEventHandler(this.Form1_Closing);this.Load += new System.EventHandler(this.Form1_Load);this.groupBox1.ResumeLayout(false);this.ResumeLayout(false);}#endregion/// <summary>/// 应用程序的主入口点。