分类: LINUX
2009-08-15 21:45:59
我的USB设备自己有驱动程序,用超级终端可以进行通信。只是因为某些原因还需要我自己写一个通信程序。想知道应该怎么查看设备的开发接口,怎么用 VC引入?用超级终端的时候,它是以设备的名字“xxmodem”做端口号的,不知道是端口几或者还是它名字本身就是一的端口号。我安装了windows的ddk,用了windows的API函数,程序如下,不知道有什么问题:
#include "stdio.h"
#include "windows.h"
#include "setupapi.h"
#include "hidsdi.h"
HANDLE hComm; //我定义的端口句柄
void OnSearch() //按我的理解它应该是搜索usb设备的存在
{
GUID guidHID;
HIDD_ATTRIBUTES strAttrib;
HDEVINFO hDevInfo;
BOOL bSuccess;
SP_DEVICE_INTERFACE_DATA strInterfaceData;
HidD_GetHidGuid(&guidHID);
HidD_GetAttributes(hComm, &strAttrib);
hDevInfo = SetupDiGetClassDevs(
&guidHID,
NULL,
0,
DIGCF_PRESENT ¦DIGCF_DEVICEINTERFACE);
bSuccess = SetupDiEnumDeviceInterfaces(
hDevInfo,
NULL,
&guidHID,
0,
&strInterfaceData);
}
BOOL OpenComm(const char *pPort, int nByteSize) //打开端口,用的windows的API函数
{
DCB dcb;
COMMTIMEOUTS timeouts =
{
100,
1,
500,
1,
100
};
hComm = CreateFile(pPort,
GENERIC_READ ¦ GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hComm == INVALID_HANDLE_VALUE)
return FALSE;
GetCommState(hComm, &dcb);
dcb.BaudRate = CBR_115200;
dcb.ByteSize = nByteSize;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
SetCommState(hComm, &dcb);
SetupComm(hComm, 4096, 1024);
SetCommTimeouts(hComm, &timeouts);
return TRUE;
}
BOOL CloseComm() //关闭端口
{
return CloseHandle(hComm);
}
void WriteComm(char *pData, int nLength) //写端口
{
int i=0;
DWORD dwNumWrite;
//我把向该设备写入的命令写了40次,保证它可以收到。如果它收到了命令,是会有返回数据的。
for(i=0;i <=40;i++){
WriteFile(hComm, "at+csms?\n", (DWORD)nLength, &dwNumWrite, NULL);
printf("%d\n",dwNumWrite);
}
}
int ReadComm(char *pData, int nLength) //读端口
{
DWORD dwNumRead=0;
//我设定的是如果没有数据返回就一直读该端口,有数据返回才停止
while(dwNumRead == 0){
ReadFile(hComm, pData, (DWORD)nLength, &dwNumRead, NULL);
printf("%d\n",dwNumRead);
}
return (int)dwNumRead;
}
void main() //主函数
{
const char *pPort = "***Modem"; //双引号里是在超级终端里看的该设备的名字
char *dir=malloc(10);
int nBaudRate = 115200;
int nParity = 0;
int nByteSize = 8;
int nStopBits = 1;
char *pData = "at\n";
char *pData1[60];
int nLength1 = 100;
int nLength = strlen(pData);
OnSearch;
OpenComm(pPort, nByteSize);
WriteComm(pData, nLength);
ReadComm(pData1, nLength1);
printf("%s\n\n\n",pData1);
CloseComm;
}