串口通信源代码

合集下载

C#串口通信代码

C#串口通信代码

很久以前C#编的串口小程序,希望对初学C#串口编程的童鞋有所帮助~ 运行界面如下图以下是源代码:using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System丄inq;using System.Text;using System.Windows.Forms;using System.IO;using System.IO.Ports;namespace SerialPortTest_1{public partial class FormSerialPortTest1 : Form{private StreamReader sRead;public int iTextbox2 = 0;public FormSerialPortTest1(){InitializeComponent();}private void Form1_Load( object sender, EventArgs e) {string [] str = SerialPort .GetPortNames();if (str == null ){MessageBox .Show( " 本机没有串口!", "Error" );return ;comboBox1.Items.AddRange(str);comboBox1.SelectedIndex = 0;comboBox2.SelectedIndex = 6;this .toolStripStatusLabel1.Text=" 端口号:端口未打开"this .toolStripStatusLabel2.Text= " 波特率:端口未打开"this .toolStripStatusLabel3.Text= " 数据位:端口未打开"this .toolStripStatusLabel4.Text = " 停止位:端口未打开"}private void button1_Click( object sender, EventArgs e) {String str1=comboBox1.Text;String str2= comboBox2.Text;String str3= comboBox3.Text;String str4= comboBox4.Text;Int32 int2 =Convert .ToInt32(str2) ;Int32 int3 =Convert .ToInt32(str3) ;tryif (str1 == null ){MessageBox .Show( " 请先选择串口!return ;}" ,"Error" );serialPort1.PortName = str1;serialPort1.BaudRate = int2;serialPort1.DataBits = int3; switch (comboBox4.Text) {case "1" :serialPort1.StopBits = StopBitsbreak ;case "1.5" :serialPort1.StopBits = StopBitsbreak ;case "2" :serialPort1.StopBits = StopBitsbreak ; .One;.OnePointFive; .Two;defaul tMessageBox .Show( "Error :参数不正确", "Error" );break ;}if (serialPort1.IsOpen == true ){serialPort1.Close();}serialPort1.Open();MessageBox .Show( " 串口打开成功!",str1);this .toolStripStatusLabel1.Text = " 端口号:serialPort1.PortName + " " ;this .toolStripStatusLabel2.Text = " 波特率:serialPort1.BaudRate + " " ;this .toolStripStatusLabel3.Text = " 数据位:serialPort1.DataBits + " " ;this .toolStripStatusLabel4.Text = " 停止位:serialPort1.StopBits + II IIbutton1.Enabled = false ;comboBox1.Enabled = false ;comboBox2.Enabled = false ;comboBox3.Enabled = false ;comboBox4.Enabled = false ;}catch (Exception er){MessageBox .Show( "Error:" +er.Message, "Error" );return ;}}private void button2_Click( object sender, EventArgs e){button1.Enabled = true ;comboBox1.Enabled = true ;comboBox2.Enabled = true ;comboBox3.Enabled = true ;comboBox4.Enabled = true ;serialPort1.Close();this .toolStripStatusLabel1.Text = "端口号:端口未打开this .toolStripStatusLabel2.Text="波特率:端口未打开";this .toolStripStatusLabel3.Text= "数据位:端口未打开";this .toolStripStatusLabel4.Text = "停止位:端口未打开";}private void 退出XToolStripMenuItem_Click( object sender, EventArgs e){Application .Exit();// 发送private void button3_Click( object sender, EventArgs e) { if (button1.Enabled == true ){MessageBox .Show( " 请先打开串口!","Error" );return ;String str1; str1 = textBox1.Text;byte [] data = Encoding .Default.GetBytes(str1);if (checkBox1.Checked == true ){for (int i = 0; i < data.Length; i++){byte temp = data[i];string tempHex = temp.ToString( "X2" ) + " "serialPort1.Write(tempHex);}}else{serialPort1.Write(data, 0, data.Length);}}// 使用Control.Invoke public delegate void DeleUpdateTextbox(string dataRe);private void serialPort1_DataReceived( object sender, SerialDataReceivedEventArgs e){string dataRe;byte [] byteRead = new byte [serialPort1.BytesToRead];DeleUpdateTextbox deleupdatetextbox = new DeleUpdateTextbox (UpdateTextbox);serialPort1.Read(byteRead, 0, byteRead.Length);if (checkBox2.Checked == false ){dataRe = Encoding .Default.GetString(byteRead);textBox2.Invoke(deleupdatetextbox, dataRe);}else{for (int i = 0; i < byteRead.Length; i++){byte temp = byteRead[i];dataRe = temp.ToString( "X2" ) + " " ;textBox2.Invoke(deleupdatetextbox, dataRe);private void UpdateTextbox( string dataRe){if (iTextbox2 == 0){this .textBox2.Text = dataRe ;iTextbox2++;}else{textBox2.AppendText(dataRe );private void 关于AToolStripMenuItem_Click( object sender, EventArgs e){MessageBox .Show( "\n 敢攀世界科技高峰\n\n 版本号V0.2\n\n" , "爱岗敬业以德为尚");}private void button4_Click( object sender, EventArgs e) {String filename;openFileDialog1.FileName = ""; openFileDialog1.ShowDialog();filename = openFileDialog1.FileName;if (filename == ""){MessageBox .Show( " 请选择要发送的文件!", "Error" );return ;}textBox3.Text = filename;if (filename != null ){sRead = new StreamReader (filename);}button5.Enabled = true ;}private void button5_Click( object sender, EventArgs{string str3 = textBox3.Text;if (button1.Enabled == true ){MessageBox .Show( " 请先打开串口!", "Error"return ;}if (str3 == ""){MessageBox .Show( " 请选择要发送的文件!",return ;e)); "Error" );string str1;str1 = textBox4.Text;timer1.Interval = Convert .ToInt32(str1);timer1.Start();button2.Enabled = false ;button3.Enabled = false ;button4.Enabled = false ;button5.Enabled = false ;textBox1.Enabled = falsetextBox3.Enabled = falsetextBox4.Enabled = falseprivate void timer1_Tick( object sender, EventArgs e) string str1;str1 = sRead.ReadLine();if (str1 == null ){timer1.Stop();sRead.Close();MessageBox .Show( "发送完毕!", "NICE" );button2.Enabled = truebutton3.Enabled = truebutton4.Enabled = truetextBox1.Enabled = truetextBox3.Enabled = truetextBox4.Enabled = truereturn ;}Encoding .Default.GetBytes(str1); byte [] data =serialPort1.Write(data, 0, data.Length);private void button6_Click( object sender, EventArgs e) { timer1.Stop();button2.Enabled = truebutton3.Enabled = truebutton4.Enabled = truetextBox1.Enabled = truetextBox3.Enabled = truetextBox4.Enabled = trueprivate void textBox1_KeyDown( object sender, KeyEventArgs e) { if (e.KeyValue == 13)if (button1.Enabled == true )MessageBox .Show( " 请先打开串口!", "Error" );return ;}String str1;str1 = textBox1.Text;byte [] data = Encoding .Default.GetBytes(str1);serialPort1.Write(data, 0, data.Length);textBox1.Clear();return ;}private void button7_Click( object sender, EventArgs e) { textBox2.Clear();iTextbox2 = 0;private void button8_Click( object sender,EventArgs e) {textBox2.Clear();iTextbox2 = 0;namespace SerialPortTest_1{partial class FormSerialPortTest1{/// <summary>/// 必需的设计器变量。

C语言串口通信-源代码

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#上位机串口通信助手源代码详解

c#上位机串口通信助手源代码实例详解
一、功能
1软件打开时,自动检测有效COM端口
2软件打开时,自动复原到上次关闭时的状态
3不必关闭串口,即可直接进行更改初始化设置内容(串口号、波特率、数据位、停止位、校验位),可按更改后的信息自动将串口重新打开
4
5
6
7
8

9
10
二、
三、
1

端口号:
数据位:
校验位:
发送(byte):tbSendCount接收(byte):tbReceivedCount
清空计数按钮:btnClearCount按16进制显示:cb16Display
接收区清空内容按钮:btnClearReceived保存数据按钮:btnSaveFile
接收数据框:tbReceivedData发送数据框:tbSendData
自动发送:cbAutomaticSend间隔时间:tbSpaceTime
按16进制发送:cb16Send发送区清空内容按钮:btnClearSend
2创建一个方法类
按Ctrl+shift+A快捷键创建一个类,名字叫Methods,代码为:
tbSendData.Text=tbSendDataStr;
}
}
//发送文本框键盘按键检测
privatevoidtbSendData_KeyPress(objectsender,KeyPressEventArgse) {
if(cb16Send.Checked)
{
//正则匹配
stringpattern="[0-9a-fA-F]|\b";//\b:退格键
if(m.Success)。

C语言串口通信-源代码

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)< p="">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++;< p="">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++; //记录接收了多少个数据。

LabWindowscvi之RS-232串口通信编程源代码

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;}。

串口通信原代码

串口通信原代码

BOOL CSCommTestDlg::OnInitDialog(){CDialog::OnInitDialog();// if(m_ctrlComm.GetPortOpen())// m_ctrlComm.SetPortOpen(FALSE);int a = m_select.GetCurSel();m_select.SetCurSel(0); //初始默认选择串口1m_select.AddString("com1");m_select.AddString("com2");m_select.AddString("com3");m_select.AddString("com4");m_select.AddString("com5");m_select.SelectString(-1,"com1"); //AddString只是在组合框的列表框加入选项,并不能在组合框的编辑框中显示出来m_Speed.SetCurSel(0);m_Speed.AddString("9600");m_Speed.AddString("19200");m_Speed.AddString("38400");m_Speed.AddString("57600");m_Speed.SelectString(-1,"9600");m_Parity.SetCurSel(0);m_Parity.AddString("n");m_Parity.AddString("o");m_Parity.AddString("e");m_Parity.SelectString(-1,"n");m_DataBits.SetCurSel(0);m_DataBits.AddString("8");m_DataBits.AddString("7");m_DataBits.AddString("6");m_DataBits.SelectString(-1,"8");m_StopBits.SetCurSel(0);m_StopBits.AddString("1");m_StopBits.AddString("2");m_StopBits.SelectString(-1,"1");m_ctrlComm.SetSettings("9600,n,8,1"); //波特率9600,无校验,8个数据位,1个停止位m_ctrlComm.SetInputMode(1); //!!!!!1:表示以二进制方式检取数据m_ctrlComm.SetRThreshold(1);//参数1表示每当串口接收缓冲区中有多于或等于1个字符时将引发一个接收数据的OnComm事件m_ctrlComm.SetInputLen(0); //设置当前接收区数据长度为0m_ctrlComm.GetInput();//先预读缓冲区以清除残留数据void CSCommTestDlg::OnSelchangeComboSelect();// m_ctrlComm.SetCommPort(a); //选择com1void CSCommTestDlg::OnButtonOpenport();// Add "About..." menu item to system menu.// IDM_ABOUTBOX must be in the system command range.ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);ASSERT(IDM_ABOUTBOX < 0xF000);CMenu* pSysMenu = GetSystemMenu(FALSE);if (pSysMenu != NULL){CString strAboutMenu;strAboutMenu.LoadString(IDS_ABOUTBOX);if (!strAboutMenu.IsEmpty()){pSysMenu->AppendMenu(MF_SEPARA TOR);pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);}}// Set the icon for this dialog. The framework does this automatically// when the application's main window is not a dialogSetIcon(m_hIcon, TRUE); // Set big iconSetIcon(m_hIcon, FALSE); // Set small icon// TODO: Add extra initialization herereturn TRUE; // return TRUE unless you set the focus to a control}void CSCommTestDlg::OnSysCommand(UINT nID, LPARAM lParam){if ((nID & 0xFFF0) == IDM_ABOUTBOX){CAboutDlg dlgAbout;dlgAbout.DoModal();}else{CDialog::OnSysCommand(nID, lParam);}}// If you add a minimize button to your dialog, you will need the code below// to draw the icon. For MFC applications using the document/view model,// this is automatically done for you by the framework.void CSCommTestDlg::OnPaint(){if (IsIconic()){CPaintDC dc(this); // device context for paintingSendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);// Center icon in client rectangleint cxIcon = GetSystemMetrics(SM_CXICON);int cyIcon = GetSystemMetrics(SM_CYICON);CRect rect;GetClientRect(&rect);int x = (rect.Width() - cxIcon + 1) / 2;int y = (rect.Height() - cyIcon + 1) / 2;// Draw the icondc.DrawIcon(x, y, m_hIcon);}else{CDialog::OnPaint();}}// The system calls this to obtain the cursor to display while the user drags// the minimized window.HCURSOR CSCommTestDlg::OnQueryDragIcon(){return (HCURSOR) m_hIcon;}BEGIN_EVENTSINK_MAP(CSCommTestDlg, CDialog)//{{AFX_EVENTSINK_MAP(CSCommTestDlg)ON_EVENT(CSCommTestDlg, IDC_MSCOMM1, 1 /* OnComm */, OnComm, VTS_NONE)//}}AFX_EVENTSINK_MAPEND_EVENTSINK_MAP()void CSCommTestDlg::OnComm(){// TODO: Add your control notification handler code hereV ARIANT variant_inp;COleSafeArray safearray_inp;LONG len,k;BYTE rxdata[2048]; //设置BYTE数组An 8-bit integerthat is not signed.CString strtemp;if(m_ctrlComm.GetCommEvent()==2) //事件值为2表示接收缓冲区内有字符{ ////////以下你可以根据自己的通信协议加入处理代码variant_inp=m_ctrlComm.GetInput(); //读缓冲区safearray_inp=variant_inp; //V ARIANT型变量转换为ColeSafeArray型变量len=safearray_inp.GetOneDimSize(); //!!!!!!!得到有效数据长度for(k=0;k<len;k++)safearray_inp.GetElement(&k,rxdata+k);//转换为BYTE型数组for(k=0;k<len;k++) //将数组转换为Cstring型变量{BYTE bt=*(char*)(rxdata+k); //字符型strtemp.Format("%c",bt); //将字符送入临时变量strtemp存放m_strRXData+=strtemp; //加入接收编辑框对应字符串}}UpdateData(FALSE); //更新编辑框内容}void CSCommTestDlg::OnButtonManualsend(){// TODO: Add your control notification handler code hereUpdateData(TRUE); //读取编辑框内容m_ctrlComm.SetOutput(COleV ariant(m_strTXData));//发送数据void CSCommTestDlg::OnSelchangeComboSelect(){// TODO: Add your control notification handler code hereint a = m_select.GetCurSel();CString msg;m_select.SetCurSel(0); //初始默认选择串口1int FindString( int a, LPCTSTR lpszItem );//可以在当前所有行中查找指定的字符传的位置,//nStartAfter指明从那一行开始进行查找。

c#上位机串口通信助手源代码详解

c#上位机串口通信助手源代码详解

c#上位机串口通信助手源代码实例详解一、功能1软件打开时,自动检测有效COM端口2 软件打开时,自动复原到上次关闭时的状态3 不必关闭串口,即可直接进行更改初始化设置内容(串口号、波特率、数据位、停止位、校验位),可按更改后的信息自动将串口重新打开4 可统计接收字节和发送字节的个数5 接收数据可按16进制数据和非16进制数据进行整体转换6 可将接收到数据进行保存7 可设置自动发送,发送时间可进行实时更改8可按字符串、16进制字节、文件方式进行发送,字符串和16进制字节可分别进行存储,内容互不干扰9 按16进制发送时,可自动校验格式,不会输错10 可清空发送或接收区域的数据二、使用工具Visual Studio2015三、程序详解1 界面创建图1用winform创建如图1所示界面,控件名字分别为:端口号:cbxCOMPort 波特率:cbxBaudRate数据位:cbxDataBits 停止位:cbxStopBits校验位:label5 打开串口按钮:btnOpenCom发送(byte):tbSendCount 接收(byte):tbReceivedCount 清空计数按钮:btnClearCount 按16进制显示:cb16Display接收区清空内容按钮:btnClearReceived 保存数据按钮:btnSaveFile接收数据框:tbReceivedData 发送数据框:tbSendData自动发送:cbAutomaticSend 间隔时间:tbSpaceTime按16进制发送:cb16Send 发送区清空内容按钮:btnClearSend 读入文件按钮:btnReadFile 发送按钮:btnSend2 创建一个方法类按Ctrl+shift+A快捷键创建一个类,名字叫Methods,代码为:using System;using System.Collections;using System.Collections.Generic;using System.IO.Ports;using System.Linq;using System.Text;using System.Threading.Tasks;namespace串口助手sdd{class Methods{//获取有效的COM口public static string[] ActivePorts(){ArrayList activePorts = new ArrayList();foreach (string pname in SerialPort.GetPortNames()){activePorts.Add(Convert.ToInt32(pname.Substring(3)));}activePorts.Sort();string[] mystr = new string[activePorts.Count];int i = 0;foreach (int num in activePorts){mystr[i++] = "COM" + num.ToString();}return mystr;}//16进制字符串转换为byte字符数组public static Byte[] _16strToHex(string strValues){string[] hexValuesSplit = strValues.Split(' ');Byte[] hexValues = new Byte[hexValuesSplit.Length];Console.WriteLine(hexValuesSplit.Length);for (int i = 0; i < hexValuesSplit.Length; i++){hexValues[i] = Convert.ToByte(hexValuesSplit[i], 16);}return hexValues;}//byte数组以16进制形式转字符串public static string ByteTo16Str(byte[] bytes){string recData = null;//创建接收数据的字符串foreach (byte outByte in bytes)//将字节数组以16进制形式遍历到一个字符串内 {recData += outByte.ToString("X2") + " ";}return recData;}//16进制字符串转换字符串public static string _16strToStr(string _16str){string outStr = null;byte[] streamByte = _16strToHex(_16str);outStr = Encoding.Default.GetString(streamByte);return outStr;}}}2 Form1.cs的代码为:using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.IO.Ports;using System.Linq;using System.Text;using System.Text.RegularExpressions;using System.Threading.Tasks;using System.Windows.Forms;using System.IO;using System.Collections;namespace串口助手sdd{public partial class Form1 : Form{//声明变量SerialPort sp = new SerialPort();bool isSetProperty = false;//串口属性设置标志位private enum PortState//声明接口显示状态,枚举型{打开,关闭}string path = AppDomain.CurrentDomain.BaseDirectory + "confing.ini";//声明配置文件路径string tbSendDataStr = "";//发送窗口字符串存储string tbSendData16 = "";//发送窗口16进制存储List<byte> receivedDatas = new List<byte>();//接收数据泛型数组//接收串口数据private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) {byte[] ReceivedData = new byte[sp.BytesToRead];//创建接收字节数组sp.Read(ReceivedData, 0, ReceivedData.Length);//读取所接收到的数据receivedDatas.AddRange(ReceivedData);tbReceivedCount.Text = (Convert.ToInt32(tbReceivedCount.Text) + ReceivedData.Length).ToString();if (cb16Display.Checked)tbReceivedData.Text = Methods.ByteTo16Str(receivedDatas.ToArray());elsetbReceivedData.Text =Encoding.Default.GetString(receivedDatas.ToArray());sp.DiscardInBuffer();//丢弃接收缓冲区数据}//发送串口数据private void DataSend(){try{if (cb16Send.Checked){byte[] hexBytes = Methods._16strToHex(tbSendData16);sp.Write(hexBytes, 0, hexBytes.Length);tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + hexBytes.Length).ToString();}else{sp.WriteLine(tbSendDataStr);tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + tbSendDataStr.Length).ToString();}}catch (Exception ex){MessageBox.Show(ex.Message.ToString());return;}}//设置串口属性private void SetPortProperty(){sp.PortName = cbxCOMPort.Text.Trim();//设置串口名sp.BaudRate = Convert.ToInt32(cbxBaudRate.Text.Trim());//设置波特率switch (cbxStopBits.Text.Trim())//设置停止位{case"1": sp.StopBits = StopBits.One; break;case"1.5": sp.StopBits = StopBits.OnePointFive; break;case"2": sp.StopBits = StopBits.Two; break;default: sp.StopBits = StopBits.None; break;}sp.DataBits = Convert.ToInt32(cbxDataBits.Text.Trim());//设置数据位switch (cbxParity.Text.Trim())//设置奇偶校验位{case"无": sp.Parity = Parity.None; break;case"奇校验": sp.Parity = Parity.Odd; break;case"偶校验": sp.Parity = Parity.Even; break;default: sp.Parity = Parity.None; break;}sp.ReadTimeout = 5000;//设置超时时间为5sControl.CheckForIllegalCrossThreadCalls = false;//这个类中我们不检查跨线程的调用是否合法(因为.net 2.0以后加强了安全机制,,不允许在winform中直接跨线程访问控件的属性)//定义DataReceived事件的委托,当串口收到数据后出发事件sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);}//设置端口显示状态private void DisplayPortState(PortState portState){toolStripStatusLabel1.Text = cbxCOMPort.Text + "端口处于" + portState + "状态 " + cbxBaudRate.Text + " " + cbxDataBits.Text + " " + cbxStopBits.Text + " " + cbxParity.Text;}//重新打开串口private void AgainOpenPort(){if (sp.IsOpen){try{sp.Close();SetPortProperty();isSetProperty = true;sp.Open();}catch (Exception){isSetProperty = false;btnOpenCom.Text = "打开串口";DisplayPortState(PortState.关闭);MessageBox.Show("串口无效或已被占用!", "错误提示");return;}DisplayPortState(PortState.打开);}else{DisplayPortState(PortState.关闭);}}public Form1(){InitializeComponent();}//软件启动时加载事件private void Form1_Load(object sender, EventArgs e){#region加载配置文件Hashtable ht = new Hashtable();if (File.Exists(path)){try{string myline = "";string[] str = new string[2];using (StreamReader sr = new StreamReader(path)) {myline = sr.ReadLine();while (myline != null){str = myline.Split('=');ht.Add(str[0], str[1]);myline = sr.ReadLine();}}}catch(Exception ex){MessageBox.Show(ex.Message.ToString());}}#endregion#region设置窗口为固定大小且不可最大化this.MaximumSize = this.Size;this.MinimumSize = this.Size;this.MaximizeBox = false;#endregion#region列出常用的波特率cbxBaudRate.Items.Add("1200");cbxBaudRate.Items.Add("2400");cbxBaudRate.Items.Add("4800");cbxBaudRate.Items.Add("9600");cbxBaudRate.Items.Add("19200");cbxBaudRate.Items.Add("38400");cbxBaudRate.Items.Add("43000");cbxBaudRate.Items.Add("56000");cbxBaudRate.Items.Add("57600");cbxBaudRate.Items.Add("115200");if (ht.ContainsKey("cbxBaudRate"))cbxBaudRate.SelectedIndex =cbxBaudRate.Items.IndexOf(ht["cbxBaudRate"].ToString());elsecbxBaudRate.SelectedIndex = 3;cbxBaudRate.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region列出停止位cbxStopBits.Items.Add("1");cbxStopBits.Items.Add("1.5");cbxStopBits.Items.Add("2");if (ht.ContainsKey("cbxStopBits"))cbxStopBits.SelectedIndex =cbxStopBits.Items.IndexOf(ht["cbxStopBits"].ToString());elsecbxStopBits.SelectedIndex = 0;cbxStopBits.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region列出数据位cbxDataBits.Items.Add("8");cbxDataBits.Items.Add("7");cbxDataBits.Items.Add("6");cbxDataBits.Items.Add("5");if (ht.ContainsKey("cbxDataBits"))cbxDataBits.SelectedIndex =cbxDataBits.Items.IndexOf(ht["cbxDataBits"].ToString());elsecbxDataBits.SelectedIndex = 0;cbxDataBits.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region列出奇偶校验位cbxParity.Items.Add("无");cbxParity.Items.Add("奇校验");cbxParity.Items.Add("偶校验");if (ht.ContainsKey("cbxParity"))cbxParity.SelectedIndex =cbxParity.Items.IndexOf(ht["cbxParity"].ToString());elsecbxParity.SelectedIndex = 0;cbxParity.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region COM口重新加载cbxCOMPort.Items.Clear();//清除当前串口号中的所有串口名称 cbxCOMPort.Items.AddRange(Methods.ActivePorts());if (ht.ContainsKey("cbxCOMPort") &&cbxCOMPort.Items.Contains(ht["cbxCOMPort"].ToString()))cbxCOMPort.SelectedIndex =cbxCOMPort.Items.IndexOf(ht["cbxCOMPort"].ToString());elsecbxCOMPort.SelectedIndex = 0;cbxCOMPort.DropDownStyle = ComboBoxStyle.DropDownList; #endregion#region初始化计数器tbSendCount.Text = "0";tbSendCount.ReadOnly = true;tbReceivedCount.Text = "0";tbReceivedCount.ReadOnly = true;#endregion#region初始化当前时间toolStripStatusLabel3.Text = DateTime.Now.ToString();#endregion#region初始化串口状态toolStripStatusLabel1.ForeColor = Color.Blue;if (!isSetProperty)//串口未设置则设置串口属性{SetPortProperty();isSetProperty = true;}try{sp.Open();btnOpenCom.Text = "关闭串口";DisplayPortState(PortState.打开);}catch (Exception){//串口打开失败后,串口属性设置标志位设为falseisSetProperty = false;MessageBox.Show("串口无效或已被占用!", "错误提示"); }#endregion#region初始化间隔时间if (ht.ContainsKey("tbSpaceTime"))tbSpaceTime.Text = ht["tbSpaceTime"].ToString();elsetbSpaceTime.Text = "1000";#endregion#region初始化按16进制显示状态if (ht.ContainsKey("cb16Display") && ht["cb16Display"].ToString() == "True") cb16Display.Checked = true;elsecb16Display.Checked = false;#endregion#region初始化按16进制发送状态if (ht.ContainsKey("cb16Send") && ht["cb16Send"].ToString() == "True")cb16Send.Checked = true;elsecb16Send.Checked = false;#endregion#region初始化发送区文本if(ht.ContainsKey("tbSendData16") && ht.ContainsKey("tbSendDataStr")){tbSendData16 = ht["tbSendData16"].ToString();tbSendDataStr = ht["tbSendDataStr"].ToString();if (cb16Send.Checked)tbSendData.Text = ht["tbSendData16"].ToString();elsetbSendData.Text = ht["tbSendDataStr"].ToString();}#endregiontbSendData.Focus();}//显示当前时间private void timer1_Tick(object sender, EventArgs e){toolStripStatusLabel3.Text = DateTime.Now.ToString();}//点击打开串口按钮private void btnOpenCom_Click(object sender, EventArgs e){if (!sp.IsOpen)//串口没有打开时{if (!isSetProperty)//串口未设置则设置串口属性{SetPortProperty();isSetProperty = true;}try{sp.Open();btnOpenCom.Text = "关闭串口";DisplayPortState(PortState.打开);}catch (Exception){//串口打开失败后,串口属性设置标志位设为falseisSetProperty = false;MessageBox.Show("串口无效或已被占用!", "错误提示"); }}else//串口已经打开{try{sp.Close();isSetProperty = false;btnOpenCom.Text = "打开串口";DisplayPortState(PortState.关闭);}catch (Exception){MessageBox.Show("关闭串口时发生错误", "错误提示"); }}}//发送串口数据private void btnSend_Click(object sender, EventArgs e){if (tbSendData.Text.Trim() == "")//检测发送数据是否为空{MessageBox.Show("请输入要发送的数据!", "错误提示");return;}if (sp.IsOpen){DataSend();}else{MessageBox.Show("串口未打开!", "错误提示");}}//点击端口号选择下拉框按钮private void cbxCOMPort_SelectedIndexChanged(object sender, EventArgs e){AgainOpenPort();}//点击波特率选择下拉框按钮private void cbxBaudRate_SelectedIndexChanged(object sender, EventArgs e) {AgainOpenPort();}//点击数据位选择下拉框按钮private void cbxDataBits_SelectedIndexChanged(object sender, EventArgs e) {AgainOpenPort();}//点击停止位选择下拉框按钮private void cbxStopBits_SelectedIndexChanged(object sender, EventArgs e) {AgainOpenPort();}//点击校验位选择下拉框按钮private void cbxParity_SelectedIndexChanged(object sender, EventArgs e){AgainOpenPort();}//点击数据接收区清空按钮private void btnClearReceived_Click(object sender, EventArgs e){receivedDatas.Clear();tbReceivedData.Text = "";}//点击是否按16进制显示接收数据private void cb16Display_CheckedChanged(object sender, EventArgs e){if (cb16Display.Checked)tbReceivedData.Text = Methods.ByteTo16Str(receivedDatas.ToArray());elsetbReceivedData.Text =Encoding.Default.GetString(receivedDatas.ToArray());//点击是否按16进制发送数据private void cb16Send_CheckedChanged(object sender, EventArgs e){if (cb16Send.Checked){tbSendData.Text = tbSendData16;}else{tbSendData.Text = tbSendDataStr;}}//发送文本框键盘按键检测private void tbSendData_KeyPress(object sender, KeyPressEventArgs e){if (cb16Send.Checked){//正则匹配string pattern = "[0-9a-fA-F]|\b";//\b:退格键Match m = Regex.Match(e.KeyChar.ToString(), pattern);if (m.Success){if(e.KeyChar != '\b'){if (tbSendData.Text.Length % 3 == 2){tbSendData.Text += " ";tbSendData.SelectionStart = tbSendData.Text.Length;}e.KeyChar = Convert.ToChar(e.KeyChar.ToString().ToUpper()); }e.Handled = false;}else{e.Handled = true;}}else{e.Handled = false;}}//点击清空发送内容private void btnClearSend_Click(object sender, EventArgs e){tbSendData.Text = "";if (cb16Send.Checked)tbSendData16 = "";elsetbSendDataStr = "";//点击清空计数器数据private void btnClearCount_Click(object sender, EventArgs e){tbReceivedCount.Text = "0";tbSendCount.Text = "0";}//点击是否设置自动发送private void cbAutomaticSend_CheckedChanged(object sender, EventArgs e) {if (cbAutomaticSend.Checked){timer2.Enabled = true;timer2.Interval = Convert.ToInt32(tbSpaceTime.Text);}else{timer2.Enabled = false;}}//自动发送时间文本框键盘按键检测private void tbSpaceTime_KeyPress(object sender, KeyPressEventArgs e) {//正则匹配string pattern = "[0-9]|\b";Match m = Regex.Match(e.KeyChar.ToString(),pattern);if (m.Success){timer2.Interval = Convert.ToInt32(tbSpaceTime.Text);e.Handled = false;}else{e.Handled = true;}}//串口显示状态private void timer2_Tick(object sender, EventArgs e){if (sp.IsOpen){DataSend();}else{timer2.Enabled = false;cbAutomaticSend.Checked = false;MessageBox.Show("串口未打开!", "错误提示");return;}if (tbSendData.Text.Trim() == "")//检测发送数据是否为空{timer2.Enabled = false;cbAutomaticSend.Checked = false;MessageBox.Show("请输入要发送的数据!", "错误提示");return;}}//关闭窗口时出发的事件private void Form1_FormClosed(object sender, FormClosedEventArgs e){try{using (StreamWriter sw = new StreamWriter(path, false)){sw.WriteLine("cbxCOMPort=" + cbxCOMPort.Text);sw.WriteLine("cbxBaudRate=" + cbxBaudRate.Text);sw.WriteLine("cbxDataBits=" + cbxDataBits.Text);sw.WriteLine("cbxStopBits=" + cbxStopBits.Text);sw.WriteLine("cbxParity=" + cbxParity.Text);sw.WriteLine("cb16Display="+ cb16Display.Checked.ToString()); sw.WriteLine("tbSpaceTime=" + tbSpaceTime.Text);sw.WriteLine("cb16Send=" + cb16Send.Checked.ToString());sw.WriteLine("tbSendDataStr=" + tbSendDataStr);sw.WriteLine("tbSendData16=" + tbSendData16);sp.Close();}}catch(Exception ex){MessageBox.Show(ex.Message.ToString());}}//发送文本框按键抬起时出发的事件private void tbSendData_KeyUp(object sender, KeyEventArgs e){if (cb16Send.Checked){tbSendData16 = tbSendData.Text.Trim();}else{tbSendDataStr = tbSendData.Text;}}//点击读入文件按钮private void btnReadFile_Click(object sender, EventArgs e){openFileDialog1.Filter = "所有文件(*.*)|*.*";//文件筛选器的设定openFileDialog1.FilterIndex = 1;openFileDialog1.Title = "选择文件";openFileDialog1.FileName = "";openFileDialog1.ShowHelp = true;if(openFileDialog1.ShowDialog() == DialogResult.OK){using (FileStream fs = newFileStream(openFileDialog1.FileName,FileMode.Open)){byte[] bufferByte = new byte[fs.Length];fs.Read(bufferByte, 0, Convert.ToInt32(fs.Length));sp.Write(bufferByte, 0, bufferByte.Length);tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + bufferByte.Length).ToString();}}}//点击保存数据按钮private void btnSaveFile_Click(object sender, EventArgs e){saveFileDialog1.Filter = "所有文件(*.*)|*.*";if(saveFileDialog1.ShowDialog() == DialogResult.OK){string fName = saveFileDialog1.FileName;using(FileStream fs = File.Open(fName, FileMode.Append)){fs.Write(receivedDatas.ToArray(), 0, receivedDatas.Count);}}}}}需要源代码或有疑问的c#爱好者们,欢迎加入c#技术交流群(33647125),附加信息为”我以下载此文档”,进群后找群主索要源代码或进行技术交流。

STM32串口通信-代码实现

STM32串口通信-代码实现

STM32串⼝通信-代码实现代码实现功能实现:与上位机进⾏通信宏定义需要的GPIO//头⽂件中的引脚宏定义#ifndef _USART_H#define _USART_H#include "stm32f10x.h"#include <stdio.h>// 串⼝1-USART1//#define USART1 USART1#define USART1_CLK RCC_APB2Periph_USART1#define USART1_APBxClkCmd RCC_APB2PeriphClockCmd#define USART1_BAUDRATE 115200// USART GPIO 引脚宏定义#define USART1_GPIO_CLK (RCC_APB2Periph_GPIOA)#define USART1_GPIO_APBxClkCmd RCC_APB2PeriphClockCmd#define USART1_TX_GPIO_PORT GPIOA#define USART1_TX_GPIO_PIN GPIO_Pin_9#define USART1_RX_GPIO_PORT GPIOA#define USART1_RX_GPIO_PIN GPIO_Pin_10#define USART1_IRQ USART1_IRQn#define USART1_IRQHandler USART1_IRQHandlervoid USART_Config(void);void Usart_SendByte(USART_TypeDef *TX, uint8_t data);void Usart_Two_SendByte(USART_TypeDef *TX_usart, uint16_t data);void Usart_SendArray(USART_TypeDef *TX_usart, uint8_t *array, uint8_t num);void Usart_SendStr(USART_TypeDef *TX_usart, uint8_t *str);#endif串⼝初始化配置//这⾥只在这个函数使⽤可⽤static限制⼀下//中断分组配置函数static void NVIC_Configuration(void){NVIC_InitTypeDef NVIC_InitStructure;/* 嵌套向量中断控制器组选择 */NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);/* 配置USART为中断源 */NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQ;/* 抢断优先级*/NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;/* ⼦优先级 */NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;/* 使能中断 */NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;/* 初始化配置NVIC */NVIC_Init(&NVIC_InitStructure);}//串⼝初始化函数void USART_Config(void){GPIO_InitTypeDef GPIO_InitStructure;USART_InitTypeDef USART_InitStructure;// 打开串⼝GPIO的时钟//DEBUG_USART_GPIO_APBxClkCmd(DEBUG_USART_GPIO_CLK, ENABLE);RCC_APB2PeriphClockCmd(USART1_GPIO_CLK, ENABLE);// 打开串⼝外设的时钟//DEBUG_USART_APBxClkCmd(DEBUG_USART_CLK, ENABLE);RCC_APB2PeriphClockCmd(USART1_CLK, ENABLE);//将USART TX的GPIO配置为推挽复⽤模式GPIO_InitStructure.GPIO_Pin = USART1_TX_GPIO_PIN;GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(USART1_TX_GPIO_PORT,&GPIO_InitStructure);//将USART RX的GPIO配置为浮空输⼊模式GPIO_InitStructure.GPIO_Pin = USART1_RX_GPIO_PIN;GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(USART1_RX_GPIO_PORT, &GPIO_InitStructure);//配置串⼝的⼯作参数//波特率USART_ART_BaudRate = USART1_BAUDRATE;// 配置针数据字长USART_ART_WordLength = USART_WordLength_8b;// 配置停⽌位USART_ART_StopBits = USART_StopBits_1;// 配置校验位USART_ART_Parity = USART_Parity_No ;// 配置硬件流控制USART_ART_HardwareFlowControl =USART_HardwareFlowControl_None;// 配置⼯作模式,收发⼀起USART_ART_Mode = USART_Mode_Rx | USART_Mode_Tx; // 完成串⼝的初始化配置USART_Init(USART1, &USART_InitStructure);// 串⼝中断优先级配置NVIC_Configuration();// 使能串⼝接收中断USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);// 使能串⼝USART_Cmd(USART1, ENABLE);}给上位机发送数据提⽰:下⾯这些函数都在usart.c中哦(⊙o⊙)发送⼀个字节void Usart_SendByte(USART_TypeDef *TX_usart, uint8_t data){USART_SendData(TX_usart,data);//检测串⼝发送的数据//若没有数据来就会⼀直等待while(USART_GetFlagStatus(TX_usart,USART_FLAG_TXE) == RESET);发送两个字节void Usart_Two_SendByte(USART_TypeDef *TX_usart, uint16_t data){uint8_t temp_h,temp_l;temp_h = (data&0xff00) >> 8;temp_l = data&0xff;//发送⾼⼋位USART_SendData(TX_usart,temp_h);while(USART_GetFlagStatus(TX_usart,USART_FLAG_TXE) == RESET);//发送低⼋位USART_SendData(TX_usart,temp_l);while(USART_GetFlagStatus(TX_usart,USART_FLAG_TXE) == RESET);}发送⼋位数组void Usart_SendArray(USART_TypeDef *TX_usart, uint8_t *array, uint8_t num) {uint8_t i;for(i=0; i<num; i++){Usart_SendByte(TX_usart,array[i]);}while(USART_GetFlagStatus(TX_usart,USART_FLAG_TC) == RESET);}发送字符串void Usart_SendStr(USART_TypeDef *TX_usart, uint8_t *str){uint8_t i = 0;do{Usart_SendByte(TX_usart,str[i]);i++;}while(str[i] != '\0');while(USART_GetFlagStatus(TX_usart,USART_FLAG_TC) == RESET);}注意:要勾选keil中的 ues MicroLIB选项重定向c库函数调⽤//重定向c库函数printf到串⼝,重定向后可使⽤printf函数int fputc(int ch, FILE *f){/* 发送⼀个字节数据到串⼝ */USART_SendData(USART1, (uint8_t) ch);/* 等待发送完毕 */while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET); return (ch);}//重定向c库函数scanf到串⼝,重写向后可使⽤scanf、getchar等函数int fgetc(FILE *f){/* 等待串⼝输⼊数据 */while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET); return (int)USART_ReceiveData(USART1);}主程序测试#include "stm32f10x.h"#include "led.h"#include "key.h"#include "systick.h"#include "usart.h"int main(void){uint8_t array[] = {0x00,0x01,0x03,0x04,0x05};USART_Config();Usart_SendByte(USART1,100);Usart_Two_SendByte(USART1,0xff00);Usart_SendArray(USART1,array,5);Usart_SendStr(USART1,"陈⼀⼀哇龘\n");printf("chen yi yi wa\n\n\n\n");while(1){}}。

串口通信源代码

串口通信源代码
// txtest.cpp : 定义控制台应用程序的入口点。
//
#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语言串口通信-源代码

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++; //记录接收了多少个数据。

(完整版)MATLAB串口通信设计源码

(完整版)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' );。

vb串口通信源代码

vb串口通信源代码

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

串口通信源代码

串口通信源代码
Imports System.IO.Ports
Imports System.Threading
Imports System.Security.Permissions
'允许在程序内部各个线程对于窗体控件进行操作
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")>
'RTS
If CheckBox2.Checked = True Then
SerialPort1.RtsEnable = True
Button4.BackColor = Color.Red
Else
End Sub
Sub RTSWaveGenerate()
Do While True
Button7.BackColor = Color.Red
SerialPort1.RtsEnable = True
Thread.Sleep(Freq2 * Dutyfactor2 * 0.01)
Button2.Enabled = False
Button3.Enabled = Fa来自se End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
ComboBox1.Items.Add(port)
Next
ComboBox1.SelectedIndex = 0
Button2.Enabled = False
Button3.Enabled = False
End Sub

通讯串口:VBC++C#串口通信源代码+详细注释用的是axMSComm控件,通信方式...

通讯串口:VBC++C#串口通信源代码+详细注释用的是axMSComm控件,通信方式...

通讯串口:VBC++C#串口通信源代码+详细注释用的是axMSComm控件,通信方式...VBIf MSComm1.PortOpen = True Then MSComm1.PortOpen = FalsemPort = i1MSComm1.PortOpen = TrueMSComm1.InputMode = comInputModeBinaryMSComm1.InBufferCount = 0MSComm1.InputLen = 0MSComm1.Settings = "9600,N,8,1"MSComm1.RThreshold = 1MSComm1.OutBufferCount = 0C++/************************************************************** **///串行口初始化if(m_ctrlComm.GetPortOpen()) //如果串口已经打开,则关闭。

m_ctrlComm.SetPortOpen(FALSE);m_ctrlComm.SetCommPort(1); //选择com1if( !m_ctrlComm.GetPortOpen())m_ctrlComm.SetPortOpen(TRUE); //打开串口elseAfxMessageBox("不能打开串行口!");m_ctrlComm.SetSettings("9600,n,8,1"); //波特率9600,无校验,8个数据位,1个停止位m_ctrlComm.SetInputMode(1); //1:表示以二进制方式检取数据m_ctrlComm.SetRThreshold(1); //参数1表示每当串口接收缓冲区中有多于或等于1个字符时将引发一个接收数据的OnComm 事件m_ctrlComm.SetInputLen(0); //设置当前接收区数据长度为0 m_ctrlComm.GetInput(); //先预读缓冲区以清除残留数据/************************************************************** **/C#if (this.axMSComm1.PortOpen == true)this.axMSComm1.PortOpen = false;mPort = 1;//端口this.axMSComm1.Settings = "9600,n,8,1";//通信参数this.axMSComm1.InputMode = InputModeBinary;//接收数据的类型this.axMSComm1.RThreshold = 1; //接收缓冲区中接收到一个字符,就产生一次OnComm事件//this.axMSComm1.OnComm += new EventHandler(axMSComm1_OnComm); //注册一个OnComm事件this.axMSComm1.SThreshold = 0;//当发送缓冲区中字符数小于该值时,MSComm控件设置Commevent属性为ComEvSend,并产生OnComm事件。

串口通信代码

串口通信代码

串口通信代码TMSCOMN::~TMSCOMN(){if(hComs != INVALID_HANDLE_VALUE){CloseHandle(hComs);hComs = INVALID_HANDLE_VALUE;}};void TMSCOMN::CloseComs(){if(hComs != INVALID_HANDLE_VALUE){CloseHandle(hComs);hComs = INVALID_HANDLE_VALUE;}};AnsiString TMSCOMN::GetComError(){AnsiString Errors;if(ComReg==0) Errors = AnsiString("串口设备与串口工作良好"); else if(ComReg==1) Errors = AnsiString("串口未打开");else Errors = AnsiString(" 串口设备与串口未连接上");return Errors;};void TMSCOMN::SetRs232Coms(int NoComs,int Bps){AnsiString ComNo;DCB dcb;COMMTIMEOUTS TimeOuts;char str[100];ComErr = AnsiString("");if(hComs != INVALID_HANDLE_VALUE){CloseHandle(hComs);hComs = INVALID_HANDLE_VALUE;}ComNo = AnsiString("COM")+AnsiString(NoComs+1);hComs=CreateFile(ComNo.c_str(),GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,0);if(hComs == INVALID_HANDLE_VALUE){ComReg = 1; ComErr = AnsiString("串口RS232未打开");Application->MessageBoxA("串口RS232打开出错!","错误",MB_OK|MB_ICONERROR); }else{GetCommState(hComs,&dcb);if(Bps==0) dcb.BaudRate = CBR_300;else if(Bps==1) dcb.BaudRate = CBR_1200;else if(Bps==2) dcb.BaudRate = CBR_2400;else if(Bps==3) dcb.BaudRate = CBR_4800;else if(Bps==4) dcb.BaudRate = CBR_9600;else if(Bps==5) dcb.BaudRate = CBR_19200;else if(Bps==6) dcb.BaudRate = CBR_38400;dcb.ByteSize = 8;dcb.Parity = NOPARITY;dcb.StopBits = ONESTOPBIT;SetCommState(hComs,&dcb);TimeOuts.ReadIntervalTimeout=0; //读间隔超时TimeOuts.ReadTotalTimeoutMultiplier=10; //读时间系数TimeOuts.ReadTotalTimeoutConstant=100; //读时间常量TimeOuts.WriteTotalTimeoutMultiplier=10; //写时间系数TimeOuts.WriteTotalTimeoutConstant=100; //写时间常数SetCommTimeouts(hComs, &TimeOuts); // 保存设置值生效lpOverlapped.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);ComReg = 0;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)==0){ComReg = 2;sprintf(str,"串口%d 与设备PM300未连接上!",(NoComs+1));ComErr = AnsiString(str);Application->MessageBoxA(str,"错误",MB_OK|MB_ICONERROR);}}};void TMSCOMN::SetRs485Coms(int NoComs,int Bps)AnsiString ComNo;DCB dcb;COMMTIMEOUTS TimeOuts;char str[100];ComErr = AnsiString("");if(hComs != INVALID_HANDLE_VALUE){CloseHandle(hComs);hComs = INVALID_HANDLE_VALUE;}ComNo = AnsiString("COM")+AnsiString(NoComs+1);hComs=CreateFile(ComNo.c_str(),GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,0);if(hComs == INVALID_HANDLE_VALUE){ComReg = 1; ComErr = AnsiString("串口RS485未打开");Application->MessageBoxA("串口RS485打开出错!","错误",MB_OK|MB_ICONERROR); }else{GetCommState(hComs,&dcb);if(Bps==0) dcb.BaudRate = CBR_300;else if(Bps==1) dcb.BaudRate = CBR_1200;else if(Bps==2) dcb.BaudRate = CBR_2400;else if(Bps==3) dcb.BaudRate = CBR_4800;else if(Bps==4) dcb.BaudRate = CBR_9600;else if(Bps==5) dcb.BaudRate = CBR_19200;else if(Bps==6) dcb.BaudRate = CBR_38400;dcb.ByteSize = 8;dcb.Parity = NOPARITY; //MARKPARITYdcb.StopBits = ONESTOPBIT;SetCommState(hComs,&dcb);TimeOuts.ReadIntervalTimeout=0; //读间隔超时TimeOuts.ReadTotalTimeoutMultiplier=10; //读时间系数TimeOuts.ReadTotalTimeoutConstant=100; //读时间常量TimeOuts.WriteTotalTimeoutMultiplier=10; //写时间系数TimeOuts.WriteTotalTimeoutConstant=100; //写时间常数SetCommTimeouts(hComs, &TimeOuts); // 保存设置值生效lpOverlapped.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);ComReg = 0;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)==0){ComReg = 2;sprintf(str,"串口%d 与485设备未连接上!",(NoComs+1));ComErr = AnsiString(str);Application->MessageBoxA(str,"错误",MB_OK|MB_ICONERROR);}}};void TMSCOMN::SendData(char *str,int Len){unsigned long lrc;PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,Len,&lrc,&lpOverlapped);};void TMSCOMN::GetData(char *str,int &Len){COMSTAT cs;DWORD dwError;ClearCommError(hComs,&dwError,&cs);dwError = cs.cbInQue;if(cs.cbInQue>0) ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped); str[dwError]=0;Len = dwError;};float TMSCOMN::StrToFloat(unsigned char *Datas){union{float f;unsigned char c[4];}covf;covf.c[0] = Datas[3];covf.c[1] = Datas[2];covf.c[2] = Datas[1];covf.c[3] = Datas[0];return covf.f;};void TMSCOMN::GetPm300dks(int &dIks , float &dUks){if(SysData.DadoNo==14 && SysData.R1Irang==0) dIks = 2000 /5;else if(SysData.DadoNo==14 && SysData.R1Irang==1) dIks = 1500 /5;else if(SysData.DadoNo==14 && SysData.R1Irang==2) dIks = 1000 /5;else if(SysData.DadoNo==14 && SysData.R1Irang==3) dIks = 500 /5;else if(SysData.DadoNo==14 && SysData.R1Irang==4) dIks = 250 /5;else if(SysData.DadoNo==14 && SysData.R1Irang==5) dIks = 100 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==0) dIks = 4000 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==1) dIks = 3000 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==2) dIks = 2500 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==3) dIks = 2000 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==4) dIks = 1500 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==5) dIks = 1000 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==6) dIks = 500 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==7) dIks = 250 /5;else if(SysData.DadoNo==15 && SysData.R1Irang==8) dIks = 100 /5;else if(SysData.DadoNo==16 && SysData.R1Irang==0 && SysData.R1Way==0) dIks = 3000 /5;else if(SysData.DadoNo==16 && SysData.R1Irang==1 && SysData.R1Way==0) dIks = 2000 /5;else if(SysData.DadoNo==16 && SysData.R1Irang==2 && SysData.R1Way==0) dIks = 1000 /5;else if(SysData.DadoNo==16 && SysData.R1Irang==3 && SysData.R1Way==0) dIks = 500 /5;else if(SysData.DadoNo==16 && SysData.R1Irang==4 && SysData.R1Way==0) dIks = 250 /5;else if(SysData.DadoNo==16 && SysData.R1Irang==5 && SysData.R1Way==0) dIks = 100 /5;else if(SysData.DadoNo==16 && SysData.R1Irang==0 && SysData.R1Way==1) dIks = 200 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==0 && SysData.R1Way==0) dIks = 4000 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==1 && SysData.R1Way==0) dIks = 3000 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==2 && SysData.R1Way==0) dIks = 2500 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==3 && SysData.R1Way==0) dIks = 2000 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==4 && SysData.R1Way==0) dIks = 1500 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==5 && SysData.R1Way==0) dIks = 1000 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==6 && SysData.R1Way==0) dIks = 500/5;else if(SysData.DadoNo==17 && SysData.R1Irang==7 && SysData.R1Way==0) dIks = 250 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==8 && SysData.R1Way==0) dIks = 100 /5;else if(SysData.DadoNo==17 && SysData.R1Irang==0 && SysData.R1Way==1) dIks = 200 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==0) dIks = 4000 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==1) dIks = 3000 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==2) dIks = 2500 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==3) dIks = 2000 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==4) dIks = 1500 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==5) dIks = 1000 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==6) dIks = 500 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==7) dIks = 250 /5;else if(SysData.DadoNo==18 && SysData.R1Irang==8) dIks = 100 /5;else if(SysData.DadoNo==19 && SysData.R1Irang==0) dIks = 2500 /5;else if(SysData.DadoNo==19 && SysData.R1Irang==1) dIks = 1500 /5;else if(SysData.DadoNo==19 && SysData.R1Irang==2) dIks = 1000 /5;else if(SysData.DadoNo==19 && SysData.R1Irang==3) dIks = 500 /5;else if(SysData.DadoNo==19 && SysData.R1Irang==4) dIks = 250 /5;else if(SysData.DadoNo==19 && SysData.R1Irang==5) dIks = 100 /5;else dIks = 1;if(SysData.DadoNo==14) dUks =1;else if(SysData.DadoNo==15) dUks =1;else if(SysData.DadoNo==16 && SysData.R1Urang==0 && SysData.R1Way==0) dUks = 1; else if(SysData.DadoNo==16 && SysData.R1Urang==1 && SysData.R1Way==0) dUks = 1; else if(SysData.DadoNo==16 && SysData.R1Urang==2 && SysData.R1Way==0) dUks = 607.4/209;else if(SysData.DadoNo==16 && SysData.R1Urang==0 && SysData.R1Way==1) dUks = 10000/100;else if(SysData.DadoNo==16 && SysData.R1Urang==1 && SysData.R1Way==1) dUks = 6000 /600;else if(SysData.DadoNo==17 && SysData.R1Urang==0 && SysData.R1Way==0) dUks = 1; else if(SysData.DadoNo==17 && SysData.R1Urang==1 && SysData.R1Way==0) dUks = 1; else if(SysData.DadoNo==17 && SysData.R1Urang==2 && SysData.R1Way==0) dUks = 607.4/209;else if(SysData.DadoNo==17 && SysData.R1Urang==0 && SysData.R1Way==1) dUks = 10000/100;else if(SysData.DadoNo==17 && SysData.R1Urang==1 && SysData.R1Way==1) dUks = 6000 /600;else if(SysData.DadoNo==18) dUks =1;else if(SysData.DadoNo==19) dUks =1;else dUks =1;};void TMSCOMN::SetPM300UI(){int dIks;float dUks;unsigned long fbl;COMSTAT cs;DWORD dwError;GetCommModemStatus(hComs,&Stats);if(Stats&16){GetPm300dks(dIks,dUks);PurgeComm(hComs,PURGE_RXCLEAR);strcpy(FileBuffer,":SEL:CLR\r");WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped); strcpy(FileBuffer,":SEL:CH1;:SEL:CH2;:SEL:CH3\r");WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped); strcpy(FileBuffer,":SEL:VLT;:SEL:AMP;:SEL:WAT;:SEL:FRQ\r");WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped); strcpy(FileBuffer,":CFG1,4\r");WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped); sprintf(FileBuffer,":CFG38,%.3f\r",dUks);WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped); sprintf(FileBuffer,":CFG39,%d\r",dIks);WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped); strcpy(FileBuffer,"*TRG\r");WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped); }};void TMSCOMN::BegPM300Data(){unsigned long fbl;COMSTAT cs;DWORD dwError;GetCommModemStatus(hComs,&Stats);if(ComReg==0 && (Stats&16)){strcpy(FileBuffer,":FRD?\r");WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped);ComRs = 1;}};void TMSCOMN::GetPM300UI(double *RData,int RsUu){static int Counts;static char str[1025],StrData[100];int i,j,Len;double dtemp;COMSTAT cs;DWORD dwError;ZeroMemory(str,sizeof(char)*1025);GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0 && ComRs == 1) {ClearCommError(hComs,&dwError,&cs);for(;(dwError==0)&&((Stats)&16);){if(cs.cbInQue>0){Counts = 0;Len = cs.cbInQue;for(i=0;i<Len;i++){ReadFile(hComs,&(FileBuffer[i]),1,&dwError,&lpOverlapped);if(FileBuffer[i]=='\r') { FileBuffer[i+1]=0; break; }}FileBuffer[Len] = 0;strcat(str,FileBuffer);if(FileBuffer[i]=='\r') break;}else{Sleep(50);Counts++;if(Counts > 69) {ResetPm300(); SetPM300UI(); Counts =0; return;}}ClearCommError(hComs,&dwError,&cs);GetCommModemStatus(hComs,&Stats);}ComReg=0;ComErr = AnsiString("");}else if(ComReg==0 ){ComReg=2;ComErr = AnsiString("串口Rs232与Pm300断开连接");MainF->DisplayHint(NULL);}//RData[0] = 230; RData[4] = 230; RData[8] = 230; RData[15] = 230; RData[12] = 50; //RData[3] = 0.9; RData[7] = 0.9; RData[11]= 0.9; RData[14] = 0.9;if(ComReg!=0 ) return;Len=strlen(str);for(i=0,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[2] = atof(StrData)/1000.0;// * SysData.AcLa / 5000;for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[6] = atof(StrData)/1000.0;// * SysData.AcLb / 5000;for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[10] = atof(StrData)/1000.0;// * SysData.AcLc / 5000;for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[0] = atof(StrData);for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[4] = atof(StrData);for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[8] = atof(StrData);for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[1] = atof(StrData);// * SysData.AcLa / 5;for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[5] = atof(StrData);// * SysData.AcLb / 5;for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;RData[9] = atof(StrData);// * SysData.AcLc / 5;for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;if(RsUu==1 || RsUu==4) RData[12] = atof(StrData);for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;if(RsUu==2) RData[12] = atof(StrData);if(RsUu==4) RData[12] = RData[12] + atof(StrData);for(i++,j=0;i<Len;i++)if(str[i]!='\r'&&str[i]!=',') StrData[j++]=str[i]; else break;StrData[j]=0;if(RsUu==3) RData[12] = atof(StrData);if(RsUu==4) RData[12] = (RData[12] + atof(StrData))/3.0;dtemp = RData[0]*RData[1];if(dtemp>0.0001) RData[3] = RData[2]*1000/dtemp;else RData[3] = 1;dtemp = RData[4]*RData[5];if(dtemp>0.0001) RData[7] = RData[6]*1000/dtemp;else RData[7] = 1;dtemp = RData[8]*RData[9];if(dtemp>0.0001) RData[11] = RData[10]*1000/dtemp;else RData[11] = 1;if(RData[3] > 1) RData[3] =1; else if(RData[3] < -1) RData[3] =-1;if(RData[7] > 1) RData[7] =1; else if(RData[7] < -1) RData[7] =-1;if(RData[11]> 1) RData[11]=1; else if(RData[11]< -1) RData[11]=-1;if(SysData.R1Udx == 2){if(RsUu==1) {RData[17]=RData[0]*RData[1]/1000.0; RData[13]=RData[2]; RData[14]=RData[3]; RData[15]=RData[0];}else if(RsUu==2) {RData[17]=RData[4]*RData[5]/1000.0; RData[13]=RData[6]; RData[14]=RData[7]; RData[15]=RData[4];}else if(RsUu==3) {RData[17]=RData[8]*RData[9]/1000.0; RData[13]=RData[10]; RData[14]=RData[11]; RData[15]=RData[8];}else if(RsUu==4) {RData[17]=RData[0]*RData[1]/1000.0; RData[13]=RData[2];RData[14]=RData[3]; RData[15]=RData[0];}}else{RData[13] = RData[2] + RData[6] + RData[10];RData[14] = (RData[3] + RData[7] + RData[11])/3.0;RData[15] = (RData[0] + RData[4] + RData[8] )/3.0;RData[17] = (RData[0]*RData[1] + RData[4]*RData[5] + RData[8]*RData[9])/1000.0; }RData[28] = sqrt(fabs(RData[17]*RData[17] - RData[13]*RData[13]));RData[24] = SysData.R1Ux; RData[25] = SysData.R1Fr;RData[26] = SysData.R1Ur; RData[27] = SysData.R1Pr;RData[31] = SysData.R1PF;};void TMSCOMN::ClearPm300Data(double *RData){RData[0] = 0; RData[1] = 0; RData[2] = 0; RData[3] = 1;RData[4] = 0; RData[5] = 0; RData[6] = 0; RData[7] = 1;RData[8] = 0; RData[9] = 0; RData[10]= 0; RData[11]= 1;RData[12]= 0; RData[13]= 0; RData[14]= 1; RData[15]= 0;RData[17]= 0; RData[28]= 0;};void TMSCOMN::ResetPm300(){int dIks;float dUks;unsigned long fbl;COMSTAT cs;DWORD dwError;GetCommModemStatus(hComs,&Stats);if(Stats&16){PurgeComm(hComs,PURGE_TXCLEAR);PurgeComm(hComs,PURGE_RXCLEAR);PurgeComm(hComs,PURGE_TXABORT);PurgeComm(hComs,PURGE_RXABORT);Sleep(100);strcpy(FileBuffer,":DVC\r");WriteFile(hComs,FileBuffer,strlen(FileBuffer),&fbl,&lpOverlapped);Sleep(3000);}};bool TMSCOMN::SetZW1401dUk(unsigned char Base,float dUK){unsigned char str[102];unsigned long lrc;COMSTAT cs;DWORD dwError;union{unsigned short i;unsigned char c[2];}cov;union{float f;unsigned char c[4];}covf;bool BoolT = false;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0) { ///设置电压倍率系数 0x1f00 str[0] = Base; str[1] = 0x16;str[2] = 0x1F; str[3] = 0x00; //寄存器地址str[4] = 0x00; str[5] = 0x02; //寄存器个数str[6] = 0x04; //寄存器字节个数covf.f = dUK;str[7] = covf.c[3];str[8] = covf.c[2];str[9] = covf.c[1];str[10]= covf.c[0];cov.i=CRC16(str,11);str[11] = cov.c[1]; str[12] = cov.c[0];PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,13,&lrc,&lpOverlapped);Sleep(100);ZeroMemory(str,100);ClearCommError(hComs,&dwError,&cs);ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped);if(cs.cbInQue == 8 && str[0]==Base && str[1]==0x16){cov.i=CRC16(str,6);if(str[6] == cov.c[1] && str[7] == cov.c[0]) BoolT = true; }}return BoolT;};bool TMSCOMN::GetZW1401dUV(unsigned char Base, double &dUs) {unsigned char str[102];unsigned long lrc;COMSTAT cs;DWORD dwError;union{unsigned short i;unsigned char c[2];}cov;double dtemp;bool BoolT = false;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0) {str[0] = Base; str[1] = 0x03;str[2] = 0x10; str[3] = 0x00;str[4] = 0x00; str[5] = 0x02;cov.i=CRC16(str,6);str[6] = cov.c[1]; str[7] = cov.c[0];PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,8,&lrc,&lpOverlapped);Sleep(100);ZeroMemory(str,100);ClearCommError(hComs,&dwError,&cs);ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped);if(cs.cbInQue == 9 && str[0]== Base && str[1]==0x03){cov.i=CRC16(str,7);if(str[7] == cov.c[1] && str[8] == cov.c[0]){dUs = StrToFloat(&(str[3])); // 线电压BoolT = true;}}}return BoolT;};bool TMSCOMN::SetZW1402dIk(unsigned char Base,float dIK){unsigned char str[102];unsigned long lrc;COMSTAT cs;DWORD dwError;union{unsigned short i;unsigned char c[2];}cov;union{float f;unsigned char c[4];}covf;bool BoolT = false;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0) { ///设置电流倍率系数 0x1f02 str[0] = Base; str[1] = 0x16;str[2] = 0x1F; str[3] = 0x02; //寄存器地址str[4] = 0x00; str[5] = 0x02; //寄存器个数str[6] = 0x04; //寄存器字节个数covf.f = dIK;str[7] = covf.c[3];str[8] = covf.c[2];str[9] = covf.c[1];str[10]= covf.c[0];cov.i=CRC16(str,11);str[11] = cov.c[1]; str[12] = cov.c[0];PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,13,&lrc,&lpOverlapped);Sleep(100);ZeroMemory(str,100);ClearCommError(hComs,&dwError,&cs);ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped);if(cs.cbInQue == 8 && str[0]==Base && str[1]==0x16){cov.i=CRC16(str,6);if(str[6] == cov.c[1] && str[7] == cov.c[0]) BoolT = true; }}return BoolT;};bool TMSCOMN::GetZW1402dIA(unsigned char Base, double &dIs) {unsigned char str[102];unsigned long lrc;COMSTAT cs;DWORD dwError;union{unsigned short i;unsigned char c[2];}cov;double dtemp;bool BoolT = false;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0){str[0] = Base; str[1] = 0x03;str[2] = 0x10; str[3] = 0x02;str[4] = 0x00; str[5] = 0x02;cov.i=CRC16(str,6);str[6] = cov.c[1]; str[7] = cov.c[0];PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,8,&lrc,&lpOverlapped);Sleep(100);ZeroMemory(str,100);ClearCommError(hComs,&dwError,&cs);ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped);if(cs.cbInQue == 9 && str[0]== Base && str[1]==0x03){cov.i=CRC16(str,7);if(str[7] == cov.c[1] && str[8] == cov.c[0]){dIs = StrToFloat(&(str[3])); // 中线电流BoolT = true;}}}return BoolT;};bool TMSCOMN::SetZW5433dUIk(unsigned char Base, float dUk, float dIk){unsigned char str[102];unsigned long lrc;COMSTAT cs;DWORD dwError;union{unsigned short i;unsigned char c[2];}cov;union{float f;unsigned char c[4];}covf;bool BoolT1 = false , BoolT2 = false;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0){ ///设置电压与电流倍率系数 0x1f00 0x1f02 str[0] = Base; str[1] = 0x16;str[2] = 0x1F; str[3] = 0x00; //寄存器地址str[4] = 0x00; str[5] = 0x02; //寄存器个数str[6] = 0x04; //寄存器字节个数covf.f = dUk; //设置电压倍率系数 0x1f00str[7] = covf.c[3];str[8] = covf.c[2];str[9] = covf.c[1];str[10]= covf.c[0];cov.i=CRC16(str,11);str[11] = cov.c[1]; str[12] = cov.c[0];PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,13,&lrc,&lpOverlapped);Sleep(100);ZeroMemory(str,100);ClearCommError(hComs,&dwError,&cs);ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped);if(cs.cbInQue == 8 && str[0]==Base && str[1]==0x16){cov.i=CRC16(str,6);if(str[6] == cov.c[1] && str[7] == cov.c[0]) BoolT1 = true; }str[0] = Base; str[1] = 0x16;str[2] = 0x1F; str[3] = 0x02; //寄存器地址str[4] = 0x00; str[5] = 0x02; //寄存器个数str[6] = 0x04; //寄存器字节个数covf.f = dIk; //设置电流倍率系数 0x1f02str[7] = covf.c[3];str[8] = covf.c[2];str[9] = covf.c[1];str[10]= covf.c[0];cov.i=CRC16(str,11);str[11] = cov.c[1]; str[12] = cov.c[0];PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,13,&lrc,&lpOverlapped);Sleep(100);ZeroMemory(str,100);ClearCommError(hComs,&dwError,&cs);ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped);if(cs.cbInQue == 8 && str[0]==Base && str[1]==0x16){cov.i=CRC16(str,6);if(str[6] == cov.c[1] && str[7] == cov.c[0]) BoolT2 = true; }}return (BoolT1 && BoolT2);};bool TMSCOMN::GetZW5433dPQ(unsigned char Base, double &dPs, double &dQs) {unsigned char str[102];unsigned long lrc;COMSTAT cs;DWORD dwError;union{unsigned short i;unsigned char c[2];}cov;double dtemp;bool BoolT = false;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0){str[0] = Base; str[1] = 0x03;str[2] = 0x16; str[3] = 0x14;str[4] = 0x00; str[5] = 0x06;cov.i=CRC16(str,6);str[6] = cov.c[1]; str[7] = cov.c[0];PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,8,&lrc,&lpOverlapped);Sleep(100);ZeroMemory(str,100);ClearCommError(hComs,&dwError,&cs);ReadFile(hComs,str,cs.cbInQue,&dwError,&lpOverlapped);if(cs.cbInQue == 17 && str[0]==Base && str[1]==0x03){cov.i=CRC16(str,15);if(str[15] == cov.c[1] && str[16] == cov.c[0]){dPs = StrToFloat(&(str[3])) /1000.0; // 并联总有功dQs = StrToFloat(&(str[11]))/1000.0; // 并联总无功BoolT = true;}}}return BoolT;};void TMSCOMN::OutSideSend(double dU,double dI,double df,double dP){int i,IdU,IdF,IdA,IdP;unsigned char str[255];unsigned long lrc;GetCommModemStatus(hComs,&Stats);if(((Stats)&16)&&(hComs != INVALID_HANDLE_VALUE)&& ComReg==0){if(dU>999.9) IdU = dU/100.0;else IdU = dU*10;IdA = dI;IdF = df*10;IdP = dP;if((dU*10 - IdU)>0.5) IdU++;if((dI - IdA)>0.5) IdA++;if((df*10 - IdF)>0.5) IdF++;if((dP - IdP)>0.5) IdP++;if(IdU<0 || IdU>9999) IdU = 0;if(IdA<0 || IdA>9999) IdA = 0;if(IdF<0 || IdF>9999) IdF = 0;if(IdP<0 || IdP>9999) IdP = 0;ZeroMemory(str,sizeof(char)*250);sprintf(str,":%04d%04d%04d%04d;",IdF,IdU,IdA,IdP);str[0] = 0xFF;for(i=1;i<17;i++) str[i]= str[i] - 0x30;str[1] = (str[1]<<4) + (str[2] & 0x0F);str[2] = (str[3]<<4) + (str[4] & 0x0F);str[3] = (str[5]<<4) + (str[6] & 0x0F);str[4] = (str[7]<<4) + (str[8] & 0x0F);str[5] = (str[9]<<4) + (str[10] & 0x0F);str[6] = (str[11]<<4)+ (str[12] & 0x0F);str[7] = (str[13]<<4)+ (str[14] & 0x0F);str[8] = (str[15]<<4)+ (str[16] & 0x0F);str[9] = (str[1]+str[2] + str[3]+str[4] + str[5]+str[6] + str[7]+str[8]) & 0x7F;PurgeComm(hComs,PURGE_RXCLEAR);WriteFile(hComs,str,10,&lrc,&lpOverlapped);Sleep(50);} };。

C#结合串口通信类实现串口通信源代码

C#结合串口通信类实现串口通信源代码

mycom是串口通信类,在本blog前一篇中有完整代码。

(C#串口通信编程类(修改版)) 下面是串口通讯测试程序的源代码,将mycom类放在此项目中可以实现简单的串口通信,希望读者能通过这个程序对串口通信过程有一个初步的了解:usingSystem;usingSystem.Drawing;usingSystem.Collections;ponentModel;usingSystem.Windows.Forms;usingSystem.Data;usingSystem.Threading;namespaceBusApp{///<summary>///Form1的摘要说明。

///</summary>publicclassForm1:System.Windows.Forms.Form{bellabel1;bellabel2;privateSystem.Windows.Forms.Buttonbutton1;privateSystem.Windows.Forms.GroupBoxgroupBox1;bellabel3;bellabel4;bellabel5;bellabel6;privateSystem.Windows.Forms.Buttonbutton2;privateSystem.Windows.Forms.Buttonbutton3;privateSystem.Windows.Forms.Buttonbutton4;privateSystem.Windows.Forms.TextBoxtextBox8;bellabel7;publicintiPort=1;//1,2,3,4publicintiRate=9600;//1200,2400,4800,9600publicbytebSize=8;//8bitspublicbytebParity=0;//0-4=no,odd,even,mark,spacepublicbytebStopBits=1;//0,1,2=1,1.5,2publicintiTimeout=1000;publicmycommycom1=newmycom();publicbyte[]recb;privateSystem.Windows.Forms.TextBoxmsg;privateSystem.Windows.Forms.TextBoxt_port;privateSystem.Windows.Forms.TextBoxt_rate;privateSystem.Windows.Forms.TextBoxt_bytesize;privateSystem.Windows.Forms.TextBoxt_stopbyte;privateSystem.Windows.Forms.TextBoxt_parity; privateSystem.Windows.Forms.TextBoxt_send; privateSystem.Windows.Forms.Buttonbutton5;//readTimeOut ///<summary>///必需的设计器变量。

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