Programming for a Digilent's USB interface in C

From Hamsterworks Wiki!

Jump to: navigation, search

This is a small program written to test the throughput of the USB/EPP interface on the Digilent Nexys2 board.

Although the single byte register access, by using that handle arrays I get around 11MB/s.

/************************************************/
/* A test of the Digilent's DPCUTIL library for */
/* talking to a development board 		 */												
/*                                              */
/* Mike Field <hamster@snap.net.nz>  14/02/2011 */				   
/************************************************/ 
#include "stdafx.h"
#include "StdAfx.h"
#include <windows.h>
#include <stdio.h>
#include <time.h> 
#include "gendefs.h"
#include "dpcdefs.h"	/* holds error codes and data types for dpcutil	*/
#include "dpcutil.h"	/* holds declaration of DPCUTIL API calls		*/

char			device[cchShortString+1]; 

unsigned char buffer[16*1024*1024];
#define REPS 10

static int PutReg(unsigned char r, unsigned char *b, int len) {

	ERC		erc;
	HANDLE	hif;

	if (!DpcOpenData(&hif, device, &erc, NULL)) {
		goto fail;
	}

	if(len == 1)
	{
		if(!DpcPutReg(hif, r, *b, &erc, NULL)) {
			DpcCloseData(hif,&erc);
			goto fail;
		}
	}
	else
	{
		if(!DpcPutRegRepeat(hif, r, b, len, &erc, NULL)) {
			DpcCloseData(hif,&erc);
			goto fail;
		}
	}

	erc = DpcGetFirstError(hif);
	DpcCloseData(hif, &erc);

	if (erc == ercNoError) 
		return 0;

fail:
	return -1;
}
 
static int GetReg(unsigned char r) {

	unsigned char b;
	ERC		erc;
	HANDLE	hif;

	if (!DpcOpenData(&hif, device, &erc, NULL)) {
		goto fail;
	}

	if (!DpcGetReg(hif, r, &b, &erc, NULL)) {
		DpcCloseData(hif,&erc);
		goto fail;
	}

	erc = DpcGetFirstError(hif);
	DpcCloseData(hif, &erc);

	if (erc == ercNoError) 
		return b;
fail: 
	return -1;
}

/*  ------------------------------------------------------------ */
int main(int argc, char * argv[]) {
	int value;
	int erc = 0;
	int id,i;
	time_t t;

	/* initialize application
	*/
	for(i = 0; i < sizeof(buffer); i++)
	{
		int bit = i/(sizeof(buffer)/64);
		bit &= 0xf;
		if(bit > 8)
			bit = 15-bit;
		buffer[i] = 1<<bit;
	}

	if (!DpcInit(&erc)) {
		printf("Unable to initialise\n");
		return 0;
	}

	id = DvmgGetDefaultDev(&erc);
	if (id == -1) {
		printf("No default device\n");
		goto error;
	}

	DvmgGetDevName(id, device, &erc);

	value = GetReg(1);
	if(value < 0)	
		printf("Get Register failed\n");
	else
		printf("Register 1 returned %i\n", value);

	t = time(NULL);
	for(i = 0; i < REPS; i++)
	{
		if(PutReg(5,buffer,sizeof(buffer))<0)
			printf("Put Register failed\n");
	}
	t = time(NULL)-t;
	printf("Time is %i for %i bytes",(int)t,(int)(sizeof(buffer)*REPS));
	printf(" = %2.3fMB/s\n",(float)(sizeof(buffer)*REPS)/t/1024/1024);
error:
	DpcTerm(); 
	printf("Press enter\n");
 	getchar(); 
	return 0;
}
Personal tools