⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 i2c.c

📁 usb driver, sample for usb driver develop. rised for reference
💻 C
字号:

/*  Win NT/2000/XP Driver for DeVaSys USBLPTPD11(D) USB Development Board */
/*  CopyRight 2001 Craig Peacock, Craig.Peacock@beyondlogic.org   	  */
/*  Sunday 4th November 2001                        				  */

#include <stdio.h>
#include <windows.h>
#include <winioctl.h>

#include "USBLPT_IOCTL.h"

#define STATUS_NO_SUCH_DEVICE             0x002
#define STATUS_SUCCESS							0x3E5

HANDLE hUSBLPT;  /* Handle for USBLPT-PD11 Driver. Must be made */
		           /* global for compatibility with I2C Read and Write */
		           /* Functions below */

BYTE I2C_Read(BYTE * pbyData, BYTE byDevId, BYTE byCount)
{
  DWORD BytesReturned;
  UCHAR Buffer[2];
  BOOL error;

  Buffer[0] = byDevId;
  Buffer[1] = byCount;

  //printf("Read_I2C, byDevId = %d, byCount = %d \n",byDevId,byCount);

  error = DeviceIoControl(
                          	hUSBLPT,				/* Handle to device of Interest */
                          	IOCTL_READ_I2C,	/* Control code of operation to perform */
	                        &Buffer,				/* Pointer to buffer to supply input data */
        	                	2,						/* Size of input buffer */
                	        	pbyData,				/* Pointer to buffer to receive output data */
                        	byCount,				/* Size of output buffer */
                          	&BytesReturned,	/* Pointer to variable to receive output byte count */
                          	NULL					/* Pointer to overlapped structure for asynchronous operation */
                         	);

  //if (!error) printf("\n\nUSBLPTPD11: Error %d occured in I2C_Read IOCTL Function.\n",GetLastError());
  return(TRUE);
}

BYTE I2C_Write(BYTE byDevId, BYTE * pbyData, BYTE byCount, BYTE byWrMod)
{
  DWORD BytesReturned;
  UCHAR Buffer[40];
  BOOL error;
  UCHAR count;

  Buffer[0] = byDevId;
  Buffer[1] = byCount;

  //  printf("Write_I2C, byDevId = %d, byCount = %d \n",byDevId,byCount);

  /* Copy pbyData Buffer to input buffer */
  for (count = 0; count <= byCount; count++)
    Buffer[2+count] = pbyData[count];

  error = DeviceIoControl(
                          	hUSBLPT,				/* Handle to device of Interest */
                          	IOCTL_WRITE_I2C,  /* Control code of operation to perform */
	                        &Buffer,				/* Pointer to buffer to supply input data */
        	                	byCount+2,			/* Size of input buffer */
                	        	NULL,					/* Pointer to buffer to receive output data */
                        	0,						/* Size of output buffer */
                          	&BytesReturned, 	/* Pointer to variable to receive output byte count */
                          	NULL					/* Pointer to overlapped structure for asynchronous operation */
                         	);

  //if (!error) printf("\n\nUSBLPTPD11: Error %d occured in I2C_Write IOCTL Function\n",GetLastError());
  return (TRUE);
}

void StatusLED(BYTE Status)
{
  DWORD BytesReturned;
  BOOL error;

  error = DeviceIoControl(
                          	hUSBLPT,				/* Handle to device of Interest */
                          	IOCTL_STATUS_LED, /* Control code of operation to perform */
	                        &Status,				/* Pointer to buffer to supply input data */
        	                	1,						/* Size of input buffer */
                	        	NULL,					/* Pointer to buffer to receive output data */
                        	0,						/* Size of output buffer */
                          	&BytesReturned, 	/* Pointer to variable to receive output byte count */
                          	NULL					/* Pointer to overlapped structure for asynchronous operation */
                         	);

  //if (!error) printf("\n\nUSBLPTPD11: Error %d occured while setting Status LED\n",GetLastError());
}

void WaitForInterrupt(void)
{
  DWORD BytesReturned;
  BOOL error;
  long DelayuS = 1000000;

  error = DeviceIoControl(
                          	hUSBLPT,				/* Handle to device of Interest */
                          	IOCTL_WAIT_INTERRUPT, /* Control code of operation to perform */
	                        &DelayuS,			/* Pointer to buffer to supply input data */
        	                	4,						/* Size of input buffer */
                	        	NULL,					/* Pointer to buffer to receive output data */
                        	0,						/* Size of output buffer */
                          	&BytesReturned, 	/* Pointer to variable to receive output byte count */
                          	NULL					/* Pointer to overlapped structure for asynchronous operation */
                         	);

  //if (!error) printf("\n\nUSBLPTPD11: Error %d occured while waiting for Interrupt \n",GetLastError());
}

BYTE I2C_Init(void)
{
  DWORD BytesReturned;
  BOOL error;

  error = DeviceIoControl(
                          	hUSBLPT,			 /* Handle to device of Interest */
                          	IOCTL_INIT_I2C, /* Control code of operation to perform */
	                        NULL,	  		    /* Pointer to buffer to supply input data */
        	                	0,				    /* Size of input buffer */
                	        	NULL,				 /* Pointer to buffer to receive output data */
                        	0,				    /* Size of output buffer */
                          	&BytesReturned, /* Pointer to variable to receive output byte count */
                          	NULL				 /* Pointer to overlapped structure for asynchronous operation */
                         	);

  //if (!error) printf("\n\nUSBLPTPD11: Error %d occured in I2C_Init.\n",GetLastError());
  return(TRUE);
}

BYTE DetectDevice(WORD wLptBaseAddr)
{
  	DWORD BytesReturned;
   BOOL error;

   /* Detects if the DeVaSys USBLPT-PD11 is connected to the  */
   /* Parallel Port.        											  */

   error = DeviceIoControl(
                          	hUSBLPT,					/* Handle to device of Interest */
                          	IOCTL_DETECT_DEVICE,	/* Control code of operation to perform */
	                        NULL,						/* Pointer to buffer to supply input data */
        	                	0,							/* Size of input buffer */
                	        	NULL,	 				   /* Pointer to buffer to receive output data */
                        	0,							/* Size of output buffer */
                          	&BytesReturned, 		/* Pointer to variable to receive output byte count */
                          	NULL						/* Pointer to overlapped structure for asynchronous operation */
                         	);

  //if (!error) printf("\n\nUSBLPTPD11: Error %d occured while detecting USBLPT-PD11.\n",GetLastError());
  return error;
}

/* Functions related to installing, starting and detecting the USBLPT-PD11 development board */

void InstallUSBLPTPD11Driver(void)
{
 SC_HANDLE  SchSCManager;
 SC_HANDLE  schService;
 DWORD      err;
 CHAR 		DriverFileName[80];

 /* Get Current Directory. Assumes USBLPT-PD11.SYS driver is in this directory. */
 /* Doesn't detect if file exists, nor if file is on removable media - if this  */
 /* is the case then when windows next boots, the driver will fail to load and  */
 /* a error entry is made in the event viewer to reflect this */

 /* Get System Directory. This should be something like c:\windows\system32 or  */
 /* c:\winnt\system32 with a Maximum Character lenght of 20. As we have a       */
 /* buffer of 80 bytes and a string of 24 bytes to append, we can go for a max  */
 /* of 55 bytes */

 if (!GetSystemDirectory(DriverFileName, 55))
     {
      printf("USBLPT-PD11: Failed to get System Directory. Is System Directory Path > 55 Characters?\n");
      printf("USBLPT-PD11: Please manually copy driver to your system32/driver directory.\n");
     }

 /* Append our Driver Name */
 lstrcat(DriverFileName,"\\Drivers\\USBLPTPD11.SYS");
 printf("USBLPT-PD11: Copying driver to %s\n",DriverFileName);

 /* Copy Driver to System32/drivers directory. This fails if the file doesn't */
 /* exist. */

 if (!CopyFile("USBLPTPD11.SYS", DriverFileName, FALSE))
     {
      printf("USBLPT-PD11: Failed to copy driver to %s\n",DriverFileName);
      printf("USBLPT-PD11: Please manually copy driver to your system32/driver directory.\n");
     }

 /* Open Handle to Service Control Manager */
 SchSCManager = OpenSCManager (NULL,                 // machine (NULL == local)
                               NULL,                 // database (NULL == default)
                               SC_MANAGER_ALL_ACCESS // access required
                              );

 /* Create Service/Driver - This adds the appropriate registry keys in */
 /* HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services - It doesn't  */
 /* care if the driver exists, or if the path is correct. */
 schService = CreateService (SchSCManager,             // SCManager database
                                "USBLPT-PD11",         // name of service
                                "USBLPT-PD11",         // name to display
                                SERVICE_ALL_ACCESS,    // desired access
                                SERVICE_KERNEL_DRIVER, // service type
                                SERVICE_DEMAND_START,  // start type
                                SERVICE_ERROR_NORMAL,  // error control type
                                "System32\\Drivers\\USBLPTPD11.SYS",        // service's binary
                                NULL,                  // no load ordering group
                                NULL,                  // no tag identifier
                                NULL,                  // no dependencies
                                NULL,                  // LocalSystem account
                                NULL                   // no password
                                );

 if (schService == NULL)
    {
     err = GetLastError();
     if (err == ERROR_SERVICE_EXISTS)
         printf("USBLPT-PD11: Driver already exists. No action taken.\n");
     else {
         printf("USBLPT-PD11: Unknown error while creating Service.\n");
         exit(1);
        }
    }
    else printf("USBLPT-PD11: Driver successfully installed.\n");

 /* Close Handle to Service Control Manager */
 CloseServiceHandle (schService);
}


BYTE OpenHandletoUSBLPTPD11Driver(void)
{
 hUSBLPT = CreateFile(	"\\\\.\\usblptpd11_0",
								GENERIC_READ,
								0,
								NULL,
								OPEN_EXISTING,
								FILE_ATTRIBUTE_NORMAL,
								NULL);

 if(hUSBLPT == INVALID_HANDLE_VALUE) return(FALSE);
 else											 return(TRUE);
}


BYTE StartUSBLPTPD11Driver(void)
{
 SC_HANDLE  SchSCManager;
 SC_HANDLE  schService;
 BOOL       ret;
 DWORD      err;

 /* Open Handle to Service Control Manager */
 SchSCManager = OpenSCManager (NULL,                        // machine (NULL == local)
                               NULL,                        // database (NULL == default)
                               SC_MANAGER_ALL_ACCESS  	   // access required
                              );

 if (SchSCManager == NULL)
   if (GetLastError() == ERROR_ACCESS_DENIED) {
   		/* We do not have enough rights to open the SCM, therefore we must */
         /* be a poor user with only user rights. Check if we can open */
         /* handle to driver */
         if (OpenHandletoUSBLPTPD11Driver()) {
               printf("USBLPT-PD11: The USBLPT-PD11 driver is running. [USER RIGHTS]\n");
         		return(1); /* All done */
               }
        	printf("\nUSBLPT-PD11: You do not have rights to access the Service Control Manager and\n");
         printf("USBLPT-PD11: the USBLPT-PD11 driver is not installed or stated. Please ask \n");
         printf("USBLPT-PD11: your administrator to install the driver on your behalf.\n");
			exit(1);
         }

 do {
 		/* Open a Handle to the USBLPT-PD11 Service Database */
 		schService = OpenService (SchSCManager,  			// handle to service control manager database
      		                     "USBLPT-PD11",       // pointer to name of service to start
            		               SERVICE_ALL_ACCESS   // type of access to service
                  		         );

	 	if (schService == NULL)
			switch (GetLastError()){
				case ERROR_ACCESS_DENIED:
						printf("USBLPT-PD11: You do not have rights to the USBLPT-PD11 service database\n");
						exit(1);
		     	case ERROR_INVALID_NAME:
						printf("USBLPT-PD11: The specified service name is invalid.\n");
						exit(1);
				case ERROR_SERVICE_DOES_NOT_EXIST:
						printf("USBLPT-PD11: The USBLPT-PD11 driver does not exist. Installing driver.\n");
                 	printf("USBLPT-PD11: This can take up to 30 seconds on some machines . .\n");
						InstallUSBLPTPD11Driver();
                  break;
            }
		} while (schService == NULL);

 /* Start the USBLPT-PD11 Driver. Errors will occur here if */
 /* .SYS file doesn't exist */
 ret = StartService (schService,    // service identifier
                     0,             // number of arguments
                     NULL           // pointer to arguments
                    );

 if (ret) printf("USBLPT-PD11: The USBLPT-PD11 driver has been successfully started.\n");
 else {
     err = GetLastError();
     if (err == ERROR_SERVICE_ALREADY_RUNNING)
       printf("USBLPT-PD11: The USBLPT-PD11 driver is already running.\n");
     else {
       printf("USBLPT-PD11: Unknown error while starting USBLPT-PD11 driver service.\n");
       printf("USBLPT-PD11: Does USBLPTPD11.SYS exist in your \\System32\\Drivers Directory?\n");
       exit(1);
       }
    }

 /* Now driver is loaded and started, Open handle to USBLPT-PD11 */
 /* Driver so we can talk to it */

 if (!OpenHandletoUSBLPTPD11Driver()) {
	 printf("USBLPT-PD11: Couldn't create handle to USBLPT-PD11 driver, Please ensure driver is loaded.\n");
    }

 /* Close handle to Service Control Manager */
 CloseServiceHandle (schService);
 return(TRUE);
}

void StopUSBLPTPD11Driver(void)
{
 /* Close handle to USBLPT-PD11 Device Driver */
 CloseServiceHandle (hUSBLPT);
 printf("\nUSBLPT-PD11: Driver session closed\n");

 /* At this stage, choose not to stop and uninstall device          */
 /* driver. This helps speed development up by reducing unnecessary */
 /* load/unloads. There is little reason why you would need to stop */
 /* the driver */
}






⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -