2 m0 37251658 m0_37251658 于 2017.01.04 17:26 提问

VC++中使用API编写串口通信程序,调用函数时提示串口句柄未定义 5C

初学者,好多地方不懂,以下是部分代码

#include
#include
#include

bool openport(char*portname)
{
HANDLE hComm;
hComm=CreateFile(portname,
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
0);
if(hComm == INVALID_HANDLE_VALUE)
{
CloseHandle(hComm);
return FALSE;
}
else
{
return TRUE;
}
}

bool setupdcb(int rate_arg)
{

DCB dcb;
int rate=rate_arg;
memset(&dcb,0,sizeof(dcb));
if(!GetCommState(hComm,&dcb))
{
    return false;
}
dcb.DCBlength=sizeof(dcb);
dcb.BaudRate=rate;
dcb.Parity=NOPARITY;

dcb.fParity = 0;
dcb.StopBits = ONESTOPBIT;
dcb.ByteSize = 8;
dcb.fOutxCtsFlow = 0;
dcb.fOutxDsrFlow = 0;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fDsrSensitivity = 0;
dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcb.fOutX = 0;
dcb.fInX = 0;
dcb.fErrorChar = 0;
dcb.fBinary = 1;
dcb.fNull = 0;
dcb.fAbortOnError = 0;
dcb.wReserved = 0;
dcb.XonLim = 2;
dcb.XoffLim = 4;
dcb.XonChar = 0x13;
dcb.XoffChar = 0x19;
dcb.EvtChar = 0;
if(!SetCommState(hComm,&dcb))
{
return false;
}
else
{
return true;
}
}

......

void main()
{
bool open;
open=openport("com2");
if(open)
printf("open comport success");
if(setupdcb(9600))
printf("setupDCB success\n");
if(setuptimeout(0,0,0,0,0))
printf("setuptimeout success\n");
SetCommMask(hComm, EV_RXCHAR);
PurgeComm(hComm,PURGE_RXCLEAR|PURGE_TXCLEAR|PURGE_RXABORT|PURGE_TXABORT);
system("pause") ;
}

以上是部分程序代码

报错信息
D:\TEST C++\T1\testport\testport.cpp(34) : error C2065: 'hComm' : undeclared identifier

提示if(!GetCommState(hComm,&dcb))报错,串口句柄未定义,求解决,谢谢各位大神了

4个回答

shen_wei
shen_wei   Ds   Rxr 2017.01.04 17:39
finchcn
finchcn   2017.01.05 07:33

hcomm为openport的局部变量,其他函数无法使用,你声明为全局变量好了

VisualEleven
VisualEleven   Ds   Rxr 2017.01.06 11:18

你可以将'hComm拿到函数外面,当成全局变量使用~

a29562268
a29562268   2017.01.13 19:00

串口句柄定义的是局部变量,改为成员变量或者全局变量

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!