串口操作API 详解.doc_第1页
串口操作API 详解.doc_第2页
串口操作API 详解.doc_第3页
串口操作API 详解.doc_第4页
串口操作API 详解.doc_第5页
已阅读5页,还剩20页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

+串口API应用 嵌入式 发布时间:2008-06-14 12:50:15 /*initialSerial功能:串口初始化参数:无返回:无*/void initialSerial() /串口初始化char szComParams50;DCB dcb;char *m_com;char *m_baud;char *m_jiaoyan; m_com=Com1;m_baud=1200;m_jiaoyan=E;COMMTIMEOUTS CommTimeOuts;m_hIDComDev = NULL;m_hIDComDev = CreateFile(m_com, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); /打开串口if(m_hIDComDev=INVALID_HANDLE_VALUE)AfxMessageBox(打开串口错误0,请检查!);goto endd;if(m_hIDComDev =(HANDLE) -1)AfxMessageBox(打开串口错误,请检查!); goto endd;SetCommTimeouts(m_hIDComDev, &CommTimeOuts); /串口超时配置CommTimeOuts. ReadIntervalTimeout=0xFFFFFFFF;CommTimeOuts. ReadTotalTimeoutMultiplier = 0;CommTimeOuts. ReadTotalTimeoutConstant =5000;CommTimeOuts. WriteTotalTimeoutMultiplier = 0;CommTimeOuts. WriteTotalTimeoutConstant = 5000;PurgeComm(m_hIDComDev, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR ) ; m_com=Com1:38400,E,8,1;wsprintf(szComParams, m_com); /设置串口参数 dcb. DCBlength = sizeof(DCB);GetCommState(m_hIDComDev, &dcb);/int baud;baud = atoi(m_baud);dcb. BaudRate = baud; /设置波特率 dcb. ByteSize= 8; /设置校验字节if (!SetCommState(m_hIDComDev, &dcb)|(!SetupComm(m_hIDComDev,10000,10000)/设置串口和收发缓冲器的大小 DWORD dwError = GetLastError();CloseHandle(m_hIDComDev);PurgeComm(m_hIDComDev,PURGE_RXCLEAR|PURGE_TXCLEAR|PURGE_TXABORT|PURGE_RXABORT);/清收发缓冲器endd:;/*SendData功能:发送数据给串口参数:buff发送的数据send_length 长度返回: 成功 1 失败 0*/DWORD SendData( unsigned char buff,int send_length) /发送数据 int t;DWORD dwBytesWritten;if(!WriteFile(m_hIDComDev,buff,send_length,&dwBytesWritten,NULL)return 0;for (t=0;t0)ClearCommError(m_hIDComDev,&dwErrorFlags,&stat); if(stat.cbInQue = 0) /stat.cbInQue is bytes in input bufferreturn 0;dwBytesRead = min(dwBytesRead,(DWORD)stat.cbInQue); /获取字符个数if(!ReadFile(m_hIDComDev,rebuff,dwBytesRead,&dwBytesRead,NULL) /整体读入return 0;return dwBytesRead;下面三个函数中所用到结构本OR函数COMMTIMEOUTSThe COMMTIMEOUTS structure is used in the SetCommTimeouts and GetCommTimeouts functions to set and query the time-out parameters for a communications device. The parameters determine the behavior of ReadFile, WriteFile, ReadFileEx, and WriteFileEx operations on the device. typedef struct _COMMTIMEOUTS DWORD ReadIntervalTimeout; DWORD ReadTotalTimeoutMultiplier; DWORD ReadTotalTimeoutConstant; DWORD WriteTotalTimeoutMultiplier; DWORD WriteTotalTimeoutConstant; COMMTIMEOUTS,*LPCOMMTIMEOUTS; MembersReadIntervalTimeout Specifies the maximum time, in milliseconds, allowed to elapse between the arrival of two characters on the communications line. During a ReadFile operation, the time period begins when the first character is received. If the interval between the arrival of any two characters exceeds this amount, the ReadFile operation is completed and any buffered data is returned. A value of zero indicates that interval time-outs are not used. A value of MAXDWORD, combined with zero values for both the ReadTotalTimeoutConstant and ReadTotalTimeoutMultiplier members, specifies that the read operation is to return immediately with the characters that have already been received, even if no characters have been received. ReadTotalTimeoutMultiplier Specifies the multiplier, in milliseconds, used to calculate the total time-out period for read operations. For each read operation, this value is multiplied by the requested number of bytes to be read. ReadTotalTimeoutConstant Specifies the constant, in milliseconds, used to calculate the total time-out period for read operations. For each read operation, this value is added to the product of the ReadTotalTimeoutMultiplier member and the requested number of bytes. A value of zero for both the ReadTotalTimeoutMultiplier and ReadTotalTimeoutConstant members indicates that total time-outs are not used for read operations. WriteTotalTimeoutMultiplier Specifies the multiplier, in milliseconds, used to calculate the total time-out period for write operations. For each write operation, this value is multiplied by the number of bytes to be written. WriteTotalTimeoutConstant Specifies the constant, in milliseconds, used to calculate the total time-out period for write operations. For each write operation, this value is added to the product of the WriteTotalTimeoutMultiplier member and the number of bytes to be written. A value of zero for both the WriteTotalTimeoutMultiplier and WriteTotalTimeoutConstant members indicates that total time-outs are not used for write operations. PurgeCommThe PurgeComm function can discard all characters from the output or input buffer of a specified communications resource. It can also terminate pending read or write operations on the resource. BOOL PurgeComm( HANDLE hFile, / handle to communications resource DWORD dwFlags / action to perform); ParametershFile Handle to the communications resource. The CreateFile function returns this handle. dwFlags Specifies the action to take. This parameter can be a combination of the following values: ValueMeaningPURGE_TXABORTTerminates all outstanding overlapped write operations and returns immediately, even if the write operations have not been completed.PURGE_RXABORTTerminates all outstanding overlapped read operations and returns immediately, even if the read operations have not been completed.PURGE_TXCLEARClears the output buffer (if the device driver has one).PURGE_RXCLEARClears the input buffer (if the device driver has one).Return ValuesIf the function succeeds, the return value is nonzero.If the function fails, the return value is zero. To get extended error information, call GetLastError. /GetCommStateThe GetCommState function fills in a device-control block (a DCB structure) with the current control settings for a specified communications device. BOOL GetCommState( HANDLE hFile, / handle to communications device LPDCB lpDCB / pointer to device-control block structure); ParametershFile Handle to the communications device. The CreateFile function returns this handle. lpDCB Pointer to the DCB structure in which the control settings information is returned. Return ValuesIf the function succeeds, the return value is nonzero.If the function fails, the return value is zero. To get extended error information, call GetLastError. /SetCommStateThe SetCommState function configures a communications device according to the specifications in a device-control block (a DCB structure). The function reinitializes all hardware and control settings, but it does not empty output or input queues. BOOL SetCommState( HANDLE hFile, / handle to communications device LPDCB lpDCB / pointer to device-control block structure); ParametershFile Handle to the communications device. The CreateFile function returns this handle. lpDCB Pointer to a DCB structure containing the configuration information for the specified communications device. Return ValuesIf the function succeeds, the return value is nonzero.If the function fails, the return value is zero. To get extended error information, call GetLastError. /SetupCommThe SetupComm function initializes the communications parameters for a specified communications device. BOOL SetupComm( HANDLE hFile, / handle to communications device DWORD dwInQueue, / size of input buffer DWORD dwOutQueue / size of output buffer); ParametershFile Handle to the communications device. The CreateFile function returns this handle. dwInQueue Specifies the recommended size, in bytes, of the devices internal input buffer. dwOutQueue Specifies the recommended size, in bytes, of the devices internal output buffer. Return ValuesIf the function succeeds, the return value is nonzero.If the function fails, the return value is zero. To get extended error information, call GetLastError. /PurgeCommThe PurgeComm function can discard all characters from the output or input buffer of a specified communications resource. It can also terminate pending read or write operations on the resource. BOOL PurgeComm( HANDLE hFile, / handle to communications resource DWORD dwFlags / action to perform); ParametershFile Handle to the communications resource. The CreateFile function returns this handle. dwFlags Specifies the action to take. This parameter can be a combination of the following values: ValueMeaningPURGE_TXABORTTerminates all outstanding overlapped write operations and returns immediately, even if the write operations have not been completed.PURGE_RXABORTTerminates all outstanding overlapped read operations and returns immediately, even if the read operations have not been completed.PURGE_TXCLEARClears the output buffer (if the device driver has one).PURGE_RXCLEARClears the input buffer (if the device driver has one).Return ValuesIf the function succeeds, the return value is nonzero.If the function fails, the return value is zero. To get extended error information, call GetLastError. /COMSTATThe COMSTAT structure contains information about a communications device. This structure is filled by the ClearCommError function. typedef struct _COMSTAT DWORD fCtsHold : 1; / Tx waiting for CTS signal DWORD fDsrHold : 1; / Tx waiting for DSR signal DWORD fRlsdHold : 1; / Tx waiting for RLSD signal DWORD fXoffHold : 1; / Tx waiting, XOFF char received DWORD fXoffSent : 1; / Tx waiting, XOFF char sent DWORD fEof : 1; / EOF character sent DWORD fTxim : 1; / character waiting for Tx DWORD fReserved : 25; / reserved DWORD cbInQue; / bytes in input buffer DWORD cbOutQue; / bytes in output buffer COMSTAT, *LPCOMSTAT; MembersfCtsHold Specifies whether transmission is waiting for the CTS (clear-to-send) signal to be sent. If this member is TRUE, transmission is waiting. fDsrHold Specifies whether transmission is waiting for the DSR (data-set-ready) signal to be sent. If this member is TRUE, transmission is waiting. fRlsdHold Specifies whether transmission is waiting for the RLSD (receive-line-signal-detect) signal to be sent. If this member is TRUE, transmission is waiting. fXoffHold Specifies whether transmission is waiting because the XOFF character was received. If this member is TRUE, transmission is waiting. fXoffSent Specifies whether transmission is waiting because the XOFF character was transmitted. If this member is TRUE, transmission is waiting. Transmission halts when the XOFF character is transmitted to a system that takes the next character as XON, regardless of the actual character. fEof Specifies whether the end-of-file (EOF) character has been received. If this member is TRUE, the EOF character has been received. fTxim If this member is TRUE, there is a character queued for transmission that has come to the communications device by way of the TransmitCommChar function. The communications device transmits such a character ahead of other characters in the devices output buffer. fReserved Reserved; do not use. cbInQue Specifies the number of bytes received by the serial provider but not yet read by a ReadFile operation. cbOutQue Specifies the number of bytes of user data remaining to be transmitted for all write operations. This value will be zero for a nonoverlapped write. /一,异步非阻塞串口通讯的优点读写串行口时,既可以同步执行,也可以重叠(异步)执行。在同步执行时,函数直到操作完成后才返回。这意味着在同步执行时线程会被阻塞,从而导致效率下降。在重叠执行时,即使操作还未完成,调用的函数也会立即返回。费时的I/O操作在后台进行,这样线程就可以干别的事情。例如,线程可以在不同的句柄上同时执行I/O操作,甚至可以在同一句柄上同时进行读写操作。重叠一词的含义就在于此。二,异步非阻塞串口通讯的基本原理首先,确定要打开的串口名、波特率、奇偶校验方式、数据位、停止位,传递给CreateFile()函数打开特定串口;其次,为了保护系统对串口的初始设置,调用 GetCommTimeouts()得到串口的原始超时设置;然后,初始化DCB对象,调用SetCommState() 设置DCB,调用SetCommTimeouts()设置串口超时控制;再次,调用SetupComm()设置串口接收发送数据的缓冲区大小,串口的设置就基本完成,之后就可以启动读写线程了。 三,异步非阻塞串口通讯的基础知识下面来介绍并举例说明一下编写异步非阻塞串口通讯的程序中将会使用到的几个关键函数CreateFile()功能:打开串口设备函数原型HANDLE CreateFile(LPCTSTR lpFileName, / 串口名称字符串;如: COM1 或 COM2DWORD dwDesiredAccess, / 设置读写属性(访问模式 );一般为 GENERIC_READ|GENERIC_WRITE,DWORD dwShareMode, / 共享模式;必须为 0, 即不能共享LPSECURITY_ATTRIBUTES lpSecurityAttributes, / 安全属性;一般为NULLDWORD dwCreationDistribution, / 创建方式,串口设置必须设置此值; 在这里必须为 OPEN_EXISTINGDWORD dwFlagsAndAttributes, / 文件属性和标志;在这里我们设置成FILE_FLAG_OVERLAPPED ,实现异步I/OHANDLE hTemplateFile / 临时文件的句柄,通常为NULL );说明:如果调用成功,那么该函数返回文件的句柄,如果调用失败,则函数返回INVALID_HANDLE_VALUE。Forexample:Handle m_hComm = CreateFile(com1,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,0);CloseHandle();功能:关闭串口BOOL CloseHandle(HANDLE hObject / handle to object to close)这个,我想就不多说了吧!GetCommState()功能:获得串口状态BOOL GetCommState(HANDLE hFile, / handle of communications deviceLPDCB lpDCB / address of device-control block structure);SetCommState()功能:设置串口状态BOOL SetCommState(HANDLE hFile, / handle of communications deviceLPDCB lpDCB / address of device-control block structure);说明:在打开通信设备句柄后,常常需要对串行口进行一些初始化工作。这需要通过一个DCB结构来进行。DCB结构包含了诸如波特率、每个字符的数据位数、奇偶校验和停止位数等信息。在查询或配置置串行口的属性时,都要用DCB结构来作为缓冲区。调用GetCommState函数可以获得串口的配置,该函数把当前配置填充到一个DCB结构中。一般在用CreateFile打开串行口后,可以调用GetCommState函数来获取串行口的初始配置。要修改串行口的配置,应该先修改DCB结构,然后再调用SetCommState函数用指定的DCB结构来设置串行口Forexample:DCB dcb;memset(&dec,0,dizeof(dcb);if(!GetCommState(HComm,&dcb)/获取当前DCB配置return FALSE;dcb.BaudRate = CBR_9600;/修改数据传输率.if(SetCommState(hComm,&dcb)/设置新参数./错误处理BuildCommDCB()功能:初始化DCB结构BOOL BuildCommDCB(LPCTSTR lpDef, / pointer to device-control stringLPDCB lpDCB / pointer to device-control block);Forexample:DCB dcb;memset(&dcb,0,sizeof(dcb);dcb.DCBlength = sizeof(dcb);if(!BuildCommDCb(9600,n,8,1,&dcb)/baud=9600 parity=N data=8 stop=1./参数修改错误return FALSE;else./己准备就绪说明:功能同上面的例子。SetupComm()功能:设置I/O缓冲区的大小函数原型:BOOL SetupComm( HANDLE hFile, / handle to communications device DWORD dwInQueue, / size of input buffer DWORD dwOutQueue / size of output buffer);说明:除了在DCB中的设置外,程序一般还需要设置I/O缓冲区的大小和超时。Windows用I/O缓冲区来暂存串行口输入和输出的数据,如果通信的速率较高,则应该设置较大的缓冲区。调用SetupComm函数可以设置串行口的输入和输出缓冲区的大小。先介绍一个结构:COMMTIMEOUTS typedef struct _COMMTIMEOUTS DWORD ReadIntervalTimeout; / 读间隔超时 DWORD ReadTotalTimeoutMultiplier; / 读时间系数 DWORD ReadTotalTimeoutConstant; / 读时间常量 DWORD WriteTotalTimeoutMultiplier; / 写时间系数DWORD WriteTotalTimeoutConstant; / 写时间常量 COMMTIMEOUTS,*LPCOMMTIMEOUTS; 再介绍两个函数GetCommTimeouts功能:读取TimeOut的值函数原型:BOOL GetCommTimeouts(HANDLE hFile, / handle of communications deviceLPCOMMTIMEOUTS lpCommTimeouts / address of comm. time-outs structure);SetCommTimeouts功能:设置TimeOUt的值函数原型:BOOL SetCommTimeouts(HANDLE hFile, / handle of communications deviceLPCOMMTIMEOUTS lpCommTimeouts / address of communications time-out structure);这里顺便介绍一下TimeOut机制的两个性质:超时函数说明:在用ReadFile和WriteFile读写串行口时,需要考虑超时问题。如果在指定的时间内没有读出或写入指定数量的字符,那么ReadFile或WriteFile的操作就会结束。要查询当前的超时设置应调用GetCommTimeouts函数,该函数会填充一个COMMTIMEOUTS结构。调用SetCommTimeouts可以用某一个COMMTIMEOUTS结构的内容来设置超时。 有两种超时:间隔超时和总超时。间隔超时是指在接收时两个字符之间的最大时延,总超时是指读写操作总共花费的最大时间。写操作只支持总超时,而读操作两种超时均支持。用COMMTIMEOUTS结构可以规定读/写操作的超时,该结构的定义为: COMMTIMEOUTS结构的成员都以毫秒为单位。总超时的计算公式是: 总超时=时间系数要求读/写的字符数 + 时间常量 例如,如果要读入10个字符,那么读操作的总超时的计算公式为: 读总超时ReadTotalTimeoutMultiplier10 + ReadTotalTimeoutConstant 可以看出,间隔超时和总超时的设置是不相关的,这可以方便通信程序灵活地设置各种超时。 如果所有写超时参数均为0,那么就不使用写超时。如果ReadIntervalTimeout为0,那么就不使用读间隔超时,如果ReadTotalTimeoutMultiplier和ReadTotalTimeoutConstant都为0,则不使用读总超时。如果读间隔超时被设置成MAXDWORD并且两个读总超时为0,那么在读一次输入缓冲区中的内容后读操作就立即完成,而不管是否读入了要求的字符。 在用重叠方式读写串行口时,虽然ReadFile和WriteFile在完成操作以前就可能返回,但超时仍然是起作用的。在这种情况下,超时规定的是操作的完成时间,而不是ReadFile和WriteFile的返回时间。 Forexample:COMMTIMEOUTS ti

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论