如何用程序关闭一个已经打开的串口
调用 C++ 的API 封装了一个串口函数 只能正常打开串口关闭串口 想请教下如果串口已经被打开,我如何在程序里判断,并把他关闭 ,然后在打开
#include "stdafx.h"
#include "Uart.h"
#include <windows.h>
#include <stdio.h>
HANDLE UART_Open(int nPort, int nBuadRate)
{
char nt_port[10]={0};
sprintf(nt_port,"COM%d",nPort);
hCom = CreateFile(nt_port,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
//int ret = 0;
if(hCom==(HANDLE)-1)
{
AfxMessageBox("打开COM失败!!");
//TRACE("OPEN_PORT_FAIL\n");
// return OPEN_PORT_FAIL;
}
if(hCom == INVALID_HANDLE_VALUE)
{
AfxMessageBox("打开COM失败!!");
//TRACE("OPEN_PORT_FAIL\n");
// return OPEN_PORT_FAIL;
}
DCB dcb;
if(!GetCommState(hCom,&dcb)) //获取COM口的设备控制块
{
CloseHandle(hCom);
AfxMessageBox("获取串口参数失败!!");
// TRACE("GET_COM_STATA_FAIL\n");
// return GET_COM_STATA_FAIL;
}
dcb.BaudRate=nBuadRate;
dcb.ByteSize=8;
dcb.Parity=NOPARITY;
dcb.StopBits=ONESTOPBIT;
if(!SetCommState(hCom,&dcb)) //设置COM口的设备控制块
{
CloseHandle(hCom);
AfxMessageBox("设置串口参数失败!!");
// TRACE("SET_COM_STATA_FAIL\n");
// return SET_COM_STATA_FAIL;
}
SetupComm(hCom,1024,1024); //输入缓冲区和输出缓冲区的大小都是1024
COMMTIMEOUTS TimeOuts;
//设定读超时
TimeOuts.ReadIntervalTimeout=1000;
TimeOuts.ReadTotalTimeoutMultiplier=300;
TimeOuts.ReadTotalTimeoutConstant=2000;
//设定写超时
TimeOuts.WriteTotalTimeoutMultiplier=300;
TimeOuts.WriteTotalTimeoutConstant=2000;
if(!SetCommTimeouts(hCom,&TimeOuts)) //将超时参数写入设备控制
{
CloseHandle(hCom);
AfxMessageBox("设置串口超时失败!!");
// TRACE("SET_COM_TIMEOUT_FAIL\n");
// return SET_COM_TIMEOUT_FAIL;
}
PurgeComm(hCom,PURGE_TXCLEAR|PURGE_RXCLEAR); //清空缓冲区
return hCom;
}
int UART_Read(HANDLE hCom, char *buf, int buf_len)
{
int ret = 0;
DWORD len;
ret = ReadFile(hCom,buf,buf_len,&len,NULL);
if(!ret)
{
//TRACE("RECV_DATA_FAIL\n");
AfxMessageBox("读取数据失败!!");
return RECV_DATA_FAIL;
}
if(len == 0)
{
// TRACE("RECV_DATA_TIMEOUT\n");
AfxMessageBox("读取数据超时!!");
return RECV_DATA_TIMEOUT;
}
return 0;
}
int UART_Write(HANDLE hCom, char *buf, int buf_len)
{
int ret = 0;
DWORD len;
// ClearCommError(hCom,&dErrorflag,&comstat);
ret = WriteFile(hCom,buf,buf_len,&len,NULL);
if(!ret)
{
//TRACE("SEND_DATA_FAIL\n");
AfxMessageBox("写入数据失败!!");
return SEND_DATA_FAIL;
}
if(len==0)
{
//TRACE("SEND_DATA_TIMEOUT\n");
AfxMessageBox("写入数据超时!!");
return SEND_DATA_TIMEOUT;
}
PurgeComm(hCom,PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR); //清空缓冲区
return 0;
}
int UART_Close(HANDLE hCom)
{
int ret=0;
ret=CloseHandle(hCom);
if(!ret)
{
// TRACE("CLOSE_PORT_FAIL\n");
AfxMessageBox("关闭串口失败!!");
return CLOSE_PORT_FAIL ;
}
return 0;
}