int32 ATIDAQHardwareInterface::ReadSingleSample( float64 buffer[] )
{
    int32 retVal; /*the return code*/
    unsigned long numRawSamples; /*the number of raw gauge value samples*/
    numRawSamples = m_uiNumChannels * m_uiAveragingSize;
    unsigned int i, j; /*loop/array indices*/
    float64 * rawBuffer = new float64[numRawSamples]; /*the buffer which holds the
                                                                                                raw, unaveraged gauge values*/
    float64 timeOut = ( numRawSamples / m_f64SamplingFrequency ) + 1; /*allow a full second
                for Windows timing inaccuracies	(definitely overkill, but whatever)*/
    int32 read; /*number samples read*/
    retVal = DAQmxReadAnalogF64( *m_thDAQTask, m_uiAveragingSize, timeOut, DAQmx_Val_GroupByScanNumber,
                                 rawBuffer, numRawSamples, &read, NULL );

    for ( i = 0; i < m_uiNumChannels; i++ )
    {
        /*sum the raw values, storing the sum in the first raw data point*/
        for ( j = 1; j < m_uiAveragingSize; j++ )
        {
            rawBuffer[i] += rawBuffer[ i + ( j * m_uiNumChannels ) ];
        }
        /*store the average values in the output buffer*/
        buffer[i] = rawBuffer[i] / m_uiAveragingSize;
    }

    delete []rawBuffer; /*gotta keep up with those unmanaged pointers*/

    return retVal;
}
int32 CVICALLBACK EveryNCallback(TaskHandle taskHandle, int32 everyNsamplesEventType, uInt32 nSamples, void *callbackData)
{
	int32           error=0;
	char            errBuff[2048]={'\0'};
	int32           nRead;
	float64         data[1000];
	int				i;

	DAQmxErrChk2 ("ReadAnalogF64", DAQmxReadAnalogF64(taskHandle,1000,10.0,DAQmx_Val_GroupByChannel,data,1000,&nRead,NULL));
	
	printf ("[%10u]", taskHandle);

	for (i = 0; i < DEV_NUM; i++) {
		if(taskHandle == gTaskHandle[i]) {
			gReadTotal[i] += nRead;
		}
		printf("\t%10d", gReadTotal[i]);
	}
	printf ("\r");
	fflush(stdout);

Error:

	return 0;
}
int32 DAQManager::EveryNCallback(TaskHandle taskHandle)
{
	int32       read = 0;
	qDebug() << "Callback Triggered";
	DAQmxReadAnalogF64(taskHandle, SAMPLE_COUNT, 10.0, DAQmx_Val_GroupByScanNumber, voltageData, SAMPLE_COUNT, &read, NULL);
	dataAcquired = 1;
	return 0;
}
/******************************************************************************
**
** Acquisition des valeur de la tache d'acquisition
**
******************************************************************************/
int NI6211::readAcquisition(double *dataA)
{
    int error;
    int32 read;

    /*------ DAQmx Read Code ------*/
    DAQmxErrChk( DAQmxReadAnalogF64(*taskRead,1000,DAQmx_Val_WaitInfinitely,DAQmx_Val_GroupByChannel,dataA,2000,&read,NULL));
    //DAQmxReadAnalogF64(*taskReadO,1000,DAQmx_Val_WaitInfinitely,DAQmx_Val_GroupByChannel,dataO,1000,&read,NULL);

Erreur:
    checkError(error);
    return read;
}
Exemple #5
0
int main(void)
{
	int32       error=0;
	TaskHandle  taskHandle=0;
	int32       read;
	float64     data[1000];
	char        errBuff[2048]={'\0'};
	int	i;

	/*********************************************/
	// DAQmx Configure Code
	/*********************************************/
	DAQmxErrChk (DAQmxCreateTask("",&taskHandle));
	DAQmxErrChk (DAQmxCreateAIVoltageChan(taskHandle,"Dev1/ai0","",DAQmx_Val_Cfg_Default,-10.0,10.0,DAQmx_Val_Volts,NULL));
	DAQmxErrChk (DAQmxCfgSampClkTiming(taskHandle,"",10000.0,DAQmx_Val_Rising,DAQmx_Val_FiniteSamps,1000));

	/*********************************************/
	// DAQmx Start Code
	/*********************************************/
	DAQmxErrChk (DAQmxStartTask(taskHandle));

	/*********************************************/
	// DAQmx Read Code
	/*********************************************/
	DAQmxErrChk (DAQmxReadAnalogF64(taskHandle,1000,10.0,DAQmx_Val_GroupByChannel,data,1000,&read,NULL));

	printf("Acquired %d points\n",read);

	for (i = 0; i < 1000; i++) {
		printf ("data[%d] = %f\n", i, data[i]);
	}

Error:
	if( DAQmxFailed(error) )
		DAQmxGetExtendedErrorInfo(errBuff,2048);
	if( taskHandle!=0 )  {
		/*********************************************/
		// DAQmx Stop Code
		/*********************************************/
		DAQmxStopTask(taskHandle);
		DAQmxClearTask(taskHandle);
	}
	if( DAQmxFailed(error) )
		printf("DAQmx Error: %s\n",errBuff);
	printf("End of program, press Enter key to quit\n");
	getchar();
	return 0;
}
Exemple #6
0
int32 Tweezers::CurrentRun(float64* curr, float64* indata, void* lpParam)
{
	threadinfo* t = (threadinfo*)lpParam;

	// config and start analog tast
	DAQmxErrRtn(DAQmxCfgSampClkTiming(AOtaskHandle,"",10*float64(1/(*t->delta*1E-3)),DAQmx_Val_Rising,DAQmx_Val_FiniteSamps,(*t->cycles*10*t->nofFrames)));
	DAQmxErrRtn(DAQmxCfgOutputBuffer(AOtaskHandle, t->nofFrames*10));
	DAQmxErrRtn(DAQmxCfgDigEdgeStartTrig(AOtaskHandle, "PFI0", DAQmx_Val_Rising));
	DAQmxErrRtn(DAQmxWriteAnalogF64(AOtaskHandle,t->nofFrames*10,0,10.0,DAQmx_Val_GroupByChannel,curr,&written,NULL));
	DAQmxErrRtn(DAQmxStartTask(AOtaskHandle));

	cerr << "\nTrying to allocate buffer for " << (*t->cycles * t->nofFrames) << " frames\n";
	// config and start pulse channel with parameters set by user
	//DAQmxErrRtn(DAQmxCfgImplicitTiming(DOtaskHandle, DAQmx_Val_FiniteSamps,*t->cycles * t->nofFrames));
	DAQmxErrRtn(DAQmxCfgImplicitTiming(DOtaskHandle, DAQmx_Val_ContSamps,1));
	DAQmxErrRtn(DAQmxCfgDigEdgeStartTrig(DOtaskHandle, "PFI0", DAQmx_Val_Rising));
	DAQmxErrRtn(DAQmxStartTask(DOtaskHandle));

	// config analog in task
	DAQmxErrRtn(DAQmxCfgSampClkTiming(AItaskHandle,"Ctr0Out",100,DAQmx_Val_Rising,DAQmx_Val_FiniteSamps,*t->cycles * t->nofFrames));
	DAQmxErrRtn(DAQmxStartTask(AItaskHandle));

	// set trigger line to 1 - GO!
	DAQmxWriteDigitalLines(TRtaskHandle,1,1,10,DAQmx_Val_GroupByChannel,trigdata[1],&written,NULL);
	
	// wait until cam trigger task is done
	DAQmxWaitUntilTaskDone(AOtaskHandle,-1);
	
	// reset trigger line
	DAQmxWriteDigitalLines(TRtaskHandle,1,1,10,DAQmx_Val_GroupByChannel,trigdata[0],&written,NULL);

    // read protocol samples
	DAQmxReadAnalogF64(AItaskHandle,*t->cycles * t->nofFrames,5.0,DAQmx_Val_GroupByChannel,indata,*t->cycles * t->nofFrames*2,&read,NULL);

	//read indeed current
	ofstream strom;
	strom.open("newcurrent.txt", ofstream::app);
	for(int i=0;i<t->nofFrames;i++)
		strom<<i*(*t->delta*1E-3)<<"\t"<<indata[i]<<endl;
		strom.close();
	
	// stop tasks, disable trigger
	DAQmxStopTask(AOtaskHandle);
	DAQmxStopTask(DOtaskHandle);
	DAQmxStopTask(AItaskHandle);
	DAQmxDisableStartTrig(AOtaskHandle);
	DAQmxDisableStartTrig(DOtaskHandle);
}
BOOL CForceChartDlg::DAQ(CString changeDeviceName, short changeFirstChannel)
{
	TaskHandle  taskHandle = 0;
	int32       read;
	CString cstrChannelList;
	cstrChannelList.Format( _T("/ai%d"), changeFirstChannel );
	DAQmxCreateTask("AAencoderTask", &taskHandle);
	DAQmxCreateAIVoltageChan(taskHandle, changeDeviceName+cstrChannelList, "AAencoderChannel", DAQmx_Val_RSE, 0, 5, DAQmx_Val_Volts, NULL);
	//UpdateData(TRUE);
	DAQmxCfgSampClkTiming(taskHandle, "OnboardClock", 100, DAQmx_Val_Rising, DAQmx_Val_ContSamps, 20);
	//UpdateData(TRUE);
	DAQmxStartTask(taskHandle);
	DAQmxReadAnalogF64(taskHandle, 10, 0.2, DAQmx_Val_GroupByChannel, G0, 10, &read, NULL);
	DAQmxStopTask(taskHandle);
	DAQmxClearTask(taskHandle);
	return TRUE;
}
int32 ATIDAQHardwareInterface::ReadBufferedSamples( int numSamples, float64 buffer[] )
{
    int32 retVal; /*the return value*/
    int32 sampsPerChannel = m_uiAveragingSize * numSamples; /*samples per channel*/
    unsigned int numRawSamples = sampsPerChannel * m_uiNumChannels; /*the total number of individual gauge readings
                                                                                                                                        to be read*/
    float64 timeOut = ( sampsPerChannel / m_f64SamplingFrequency ) + 1; /*timeout value. allows a full second of
                                                                                                                                                slack*/
    float64 * rawBuffer = new float64[ numRawSamples ];
    int32 read; /*number of samples read.*/
    unsigned int rawSetSize = m_uiNumChannels * m_uiAveragingSize; /*the number of raw data sets per one output set*/
    int i, j, k; /*generic loop/array indices*/
    retVal = DAQmxReadAnalogF64( *m_thDAQTask, sampsPerChannel, timeOut, DAQmx_Val_GroupByScanNumber,
                                 rawBuffer, numRawSamples, &read, NULL );
    /*
        precondition: rawBuffer has the raw samples from the DAQ hardware.  rawSetSize is the number of
                data points in one output reading (one raw data point is a single reading of all 6 or 7 gauges).
        postcondition: buffer has the output (averaged) data points.  the first data point in each raw 'set' has the
                sum of all the readings in that set. i = numSamples, j = m_uiNumChannels, k = m_uiAveragingSize
        */
    for ( i = 0; i < numSamples; i++ )
    {
        unsigned int firstDataPointInSetIndex = i * rawSetSize; /*the position of the first element
                                                                                                                                in the first data point in the raw
                                                                                                                                set we're currently averaging*/
        for ( j = 0; (unsigned int)j < m_uiNumChannels; j++ )
        {
            unsigned int sumIndex = firstDataPointInSetIndex + j; /*the index where we're storing
                                                                                                                                  the sum of the gauge we're averaging
                                                                                                                                  the raw values for*/
            for ( k = 1; (unsigned int)k < m_uiAveragingSize; k++ )
            { /*put the sum of this set into the first reading in the set*/
                rawBuffer[ sumIndex ] += rawBuffer[ sumIndex + ( k * m_uiNumChannels ) ];
            }

            /*put the averages into the output buffer*/
            buffer[ ( i * m_uiNumChannels ) + j ] = rawBuffer[ sumIndex ] / m_uiAveragingSize;
        }
    }
    delete [] rawBuffer; /*keep up with those unmanaged pointers*/
    return retVal;
}
Exemple #9
0
	float64 EXPORT_API *EOGReturnData(TaskHandle taskHandle)
	//int32 EXPORT_API *EOGReturnData(TaskHandle taskHandle)
	{
		float64		*ret = new float64[2];
		//int32		*ret = new int32[2];
		int32       error = 0;
		int32       read;
		char        errBuff[2048] = { '\0' };

		/*********************************************/
		// DAQmx Read Code
		/*********************************************/

		DAQmxErrChk(DAQmxReadAnalogF64(taskHandle, numSamples, 10.0, DAQmx_Val_GroupByChannel, data, 2, &read, NULL));
		// DAQmxErrChk(DAQmxReadAnalogF64(taskHandle, 1000, 10.0, DAQmx_Val_GroupByScanNumber, data, 1000, &read, NULL));
		// now call the callback we have set and send the data
		
		//ret[0] = 4.02;
		//ret[1] = -2.34;

		if (read > 0) {		
			for (int n = 0; n < 2; n++)
			{
				ret[n] = data[n];
			}	
		}

		return ret;

	Error:
		if (DAQmxFailed(error))
		{
			DAQmxGetExtendedErrorInfo(errBuff, 2048);
			Cleanup();
			printf("DAQmx Error: %s\n", errBuff);
		}
		return 0;
	}
Exemple #10
0
int32 CVICALLBACK EveryNCallback(TaskHandle taskHandle, int32 everyNsamplesEventType, uInt32 nSamples, void *callbackData)
{
    int32 error = 0;
    char errBuff[2048];
    int32 read;

    int32 sampsPerChan = daq6220pvt.sampsPerChan;
    int32 buff_size = daq6220pvt.sampsPerChan*16;

    int   fd;

    epicsPrintf("**** DAQmxReadAnalogF64 ****\n");

    DAQmxErrChk(DAQmxReadAnalogF64(daq6220pvt.taskHandle, sampsPerChan, 10.0, DAQmx_Val_GroupByChannel, daq6220pvt.data,
                                     buff_size, &read, NULL));

    fd = open(DATAFILE_6220, O_WRONLY | O_CREAT);
    write(fd, daq6220pvt.data, buff_size*8);
    close(fd);

    epicsPrintf("**** File Save Byte : %d ****\n", buff_size*8);

    return 0;

Error:
    if( DAQmxFailed(error) )
        DAQmxGetExtendedErrorInfo(errBuff,2048);

    if( daq6220pvt.taskHandle!=0 ) {
        DAQmxStopTask(daq6220pvt.taskHandle);
        DAQmxClearTask(daq6220pvt.taskHandle);
    }
    if( DAQmxFailed(error) )
        epicsPrintf("DAQmx Error(6220): %s\n",errBuff);

    return -1;
}
Exemple #11
0
int32 CVICALLBACK EveryNCallback6220(TaskHandle taskHandle, int32 everyNsamplesEventType, uInt32 nSamples, void *callbackData)
{
    int32 error = 0;
    char errBuff[2048];
    int32 read;

    int32 sampsPerChan = daq6220pvt.rate;
    int32 buff_size = daq6220pvt.rate*16;

    int	i, j, ind;
    float64        *data;

    data = (float64 *)malloc(sizeof(float64)*buff_size);

    DAQmxErrChk(DAQmxReadAnalogF64(daq6220pvt.taskHandle, sampsPerChan, 10.0, DAQmx_Val_GroupByChannel, data,
                                     buff_size, &read, NULL));

    ind = 0;
    daq6220pvt.totalRead += sampsPerChan;

    for(i=0; i < 16; i++) {
        if(daq6220pvt.mdsput[i]) {
            if(daq6220pvt.fp[i] != NULL) {
                ind = i*sampsPerChan;
                fwrite(&data[ind], sizeof(float64)*sampsPerChan, 1, daq6220pvt.fp[i]);
                fflush(daq6220pvt.fp[i]);

                if(daq6220pvt.totalRead >= daq6220pvt.sampsPerChan) {
                    fclose(daq6220pvt.fp[i]);
                    daq6220pvt.fp[i] = NULL;
                    epicsPrintf("*** data file save finish... ***\n");
                }
            }
        }
    }

    if(daq6220pvt.totalRead >= daq6220pvt.sampsPerChan) {
        DaqQueueData queueData;

        daq6220pvt.totalRead = 0;

        SetDaqFinshStop(&daq6220pvt);
        daq6220pvt.status = DAQ_STATUS_STOP;

        queueData.opcode = OP_CODE_DAQ_MDSPLUS;
        epicsMessageQueueSend(daq6220pvt.DaqQueueId, (void *)&queueData, sizeof(DaqQueueData));
    }

    free(data);
    data = NULL;

    epicsPrintf("**** NI 6220 File Save Byte : %ld ****\n", buff_size*8);

    return 0;

Error:
    if( DAQmxFailed(error) )
        DAQmxGetExtendedErrorInfo(errBuff,2048);

    if( daq6220pvt.taskHandle!=0 ) {
        DAQmxStopTask(daq6220pvt.taskHandle);
        DAQmxClearTask(daq6220pvt.taskHandle);
    }
    if( DAQmxFailed(error) )
        epicsPrintf("DAQmx Error(6220): %s\n",errBuff);

    return -1;
}
Exemple #12
0
// [outputData, sampsPerChanRead] = readAnalogData(task, numSampsPerChan, outputFormat, timeout, outputVarSizeOrName)
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	//Read input arguments

	// Get the task handle
	mxArray *mxTaskID = mxGetProperty(prhs[0],0,"taskID");
	mxClassID clsID = mxGetClassID(mxTaskID);
	localAssert(clsID==TASKHANDLE_MXCLASS);
	TaskHandle *taskIDPtr = (TaskHandle*)mxGetData(mxTaskID);
	TaskHandle taskID = *taskIDPtr;

	//Determine if this is a buffered read operation
	uInt32 bufSize = 0;
	int32 status = DAQmxGetBufInputBufSize(taskID,&bufSize);
	if (status) {
		handleDAQmxError(status,"DAQmxGetBufInputBufSize");
	}

	// Handle input arguments

	int32 numSampsPerChan = 0; // this does take negative vals in the case of DAQmx_Val_Auto
	if ((nrhs < 2) || mxIsEmpty(prhs[1]) || mxIsInf(mxGetScalar(prhs[1]))) {
		if (bufSize==0)
			numSampsPerChan = 1;
		else
			numSampsPerChan = DAQmx_Val_Auto;
	} else {
		numSampsPerChan = (int) mxGetScalar(prhs[1]);
	}
	
	char outputFormat[10];
	if ((nrhs < 3) || mxIsEmpty(prhs[2]))
		strcpy_s(outputFormat,"scaled");
	else
		mxGetString(prhs[2], outputFormat, 10);

	double timeout;
	if ((nrhs < 4) || mxIsEmpty(prhs[3]) || mxIsInf(mxGetScalar(prhs[3])))
		timeout = DAQmx_Val_WaitInfinitely;
	else
		timeout = mxGetScalar(prhs[3]);

	bool outputData; //Indicates whether to return an outputData argument
	int outputVarSampsPerChan = 0; // this CAN take negative values in case of DAQmx_Val_Auto
	char outputVarName[MAXVARNAMESIZE];	
	if ((nrhs < 5) || mxIsEmpty(prhs[4])) {
		outputData = true;
		outputVarSampsPerChan = numSampsPerChan; //If value is DAQmx_Val_Auto, then the # of samples available will be queried before allocting array
	} else {
		outputData = mxIsNumeric(prhs[4]);
		if (outputData) {
			if (nlhs < 2) {
				mexErrMsgTxt("There must be two output arguments specified if a preallocated MATLAB variable is not specified");
			}
			outputVarSampsPerChan = (int) mxGetScalar(prhs[4]);
		} else {
			mxGetString(prhs[4],outputVarName,MAXVARNAMESIZE);
		}
	}

	//Determine output data type
	mxClassID outputDataClass;
	mxArray *mxRawDataArrayAI = mxGetProperty(prhs[0],0,"rawDataArrayAI"); //Stored in MCOS Task object as an empty array of the desired class!
	mxClassID rawDataClass = mxGetClassID(mxRawDataArrayAI); 

	char errorMessage[30];
	if (!_strcmpi(outputFormat,"scaled"))
		outputDataClass = mxDOUBLE_CLASS;
	else if (!_strcmpi(outputFormat,"native"))
		outputDataClass = rawDataClass;
	else {
		sprintf_s(errorMessage,"Unrecognized output format: %s\n",outputFormat);
		mexErrMsgTxt(errorMessage);
	}		

	//Determine # of output channels
	uInt32 numChannels; 
	DAQmxGetReadNumChans(taskID,&numChannels); //Reflects number of channels in Task, or the number of channels specified by 'ReadChannelsToRead' property
	
	//Determine output buffer/size (creating if needed)
	mxArray *mxOutputDataBuf = NULL;
	if (outputData)	{
		if (outputVarSampsPerChan == DAQmx_Val_Auto) {
			uInt32 buf = 0;
			status = DAQmxGetReadAvailSampPerChan(taskID,&buf);
			if (status) {
				handleDAQmxError(status, mexFunctionName());
			}
			outputVarSampsPerChan = buf;
		}

		//localAssert(outputVarSampsPerChan >= 0);
		localAssert(outputVarSampsPerChan > 0);
		mxOutputDataBuf = mxCreateNumericMatrix(outputVarSampsPerChan,numChannels,outputDataClass,mxREAL);
	} else {
		localAssert(false);
		////I don't believe this is working
		//mxOutputDataBuf = mexGetVariable("caller", outputVarName);
		//outputVarSampsPerChan = mxGetM(mxOutputDataBuf);
		////TODO: Add check to ensure WS variable is of correct class
	}

	void* outputDataPtr = mxGetData(mxOutputDataBuf);
	localAssert(outputDataPtr!=NULL);

	uInt32 arraySizeInSamps = outputVarSampsPerChan * numChannels;
	localAssert(mxGetNumberOfElements(mxOutputDataBuf)==(size_t)arraySizeInSamps);
	int32 numSampsPerChanRead;

	
	if (outputDataClass == mxDOUBLE_CLASS) //'scaled' 
		// float64 should be double
		status = DAQmxReadAnalogF64(taskID,numSampsPerChan,timeout,fillMode,
				(float64*) outputDataPtr, arraySizeInSamps, &numSampsPerChanRead, NULL);
	else { //'raw'
		switch (outputDataClass)
		{
			case mxINT16_CLASS:
				status = DAQmxReadBinaryI16(taskID, numSampsPerChan, timeout, fillMode, (int16*) outputDataPtr, arraySizeInSamps, &numSampsPerChanRead, NULL);
				break;
			case mxINT32_CLASS:
				status = DAQmxReadBinaryI32(taskID, numSampsPerChan, timeout, fillMode, (int32*) outputDataPtr, arraySizeInSamps, &numSampsPerChanRead, NULL);
				break;
			case mxUINT16_CLASS:
				status = DAQmxReadBinaryU16(taskID, numSampsPerChan, timeout, fillMode, (uInt16*) outputDataPtr, arraySizeInSamps, &numSampsPerChanRead, NULL);
				break;
			case mxUINT32_CLASS:
				status = DAQmxReadBinaryU32(taskID, numSampsPerChan, timeout, fillMode, (uInt32*) outputDataPtr, arraySizeInSamps, &numSampsPerChanRead, NULL);
				break;
		}
	}

	//Return output data
	if (!status)
	{
		//mexPrintf("Successfully read %d samples of data\n", numSampsRead);

		if (outputData) {
			if (nlhs > 0)
				plhs[0] = mxOutputDataBuf;
			else				
				mxDestroyArray(mxOutputDataBuf); //If you don't read out, all the reading was done for naught
		} else {
			//I don't believe this is working
			localAssert(false);
			//mexPutVariable("caller", outputVarName, mxOutputDataBuf);
			//
			//if (nlhs >= 0) //Return empty value for output data
			//	plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL);
		}
			

		if (nlhs>1) { //Return number of samples actually read
			plhs[1] = mxCreateDoubleScalar(0.0);	
			double *sampsReadOutput = mxGetPr(plhs[1]);
			*sampsReadOutput = (double)numSampsPerChanRead;
		}
	} else { //Read failed
		handleDAQmxError(status, mexFunctionName());
	}

}
Exemple #13
0
void motorControl::controlLoop(void)
{
    int32       error=0;
    float cotexDrive = 0.0;
    bool keepReading=TRUE;
    bool32 isLate = {0};
    double tick=0.0,tock=0.0;
    float64 motorCommand[3]={0.0,0.0,0.0},errorForce[2]= {0.0,0.0},integral[2]={0.0,0.0},EMG={0.0};
    char        errBuff[2048]={'\0'};
    FILE *dataFile;
    time_t t = time(NULL);
    tm* timePtr = localtime(&t);
    char fileName[200];
    char dataSample[600]="";
    char dataTemp[100]="";
    sprintf_s(
            fileName,
            "C:\\data\\realTimeData%4d_%02d_%02d_%02d_%02d_%02d.txt",
            timePtr->tm_year+1900, 
            timePtr->tm_mon+1, 
            timePtr->tm_mday, 
            timePtr->tm_hour, 
            timePtr->tm_min, 
            timePtr->tm_sec
            );
    dataFile = fopen(fileName,"w");
    //fprintf(dataFile,"Time, Load Cell1, Load Cell2, Motor Command1, Motor Command2, Length 1, Length2, Velocity1, Velocity2, EMG1, EMG2, is sample missed\n");
    //fprintf(dataFile,"Time, Load Cell1, Load Cell2, Length 1, Length2, Velocity1, Velocity2, EMG1, EMG2, GammaStat, GammaDyn, is sample missed\n");
    //fprintf(dataFile,"Time, Load Cell1, Load Cell2, Length 1, Length2, motorRef1, motorRef2, spindleIa1, spindleIa2, spindleII1, spindleII2, EMG1, EMG2, GammaStat, GammaDyn, is sample missed\n");
    //fprintf(dataFile,"Time, Length 1, Length2, EMG1, EMG2, GammaStat, GammaDyn, is sample missed\n");
    fprintf(dataFile,header);
    DAQmxErrChk (DAQmxStartTask(loadCelltaskHandle));
    DAQmxErrChk (DAQmxStartTask(motorTaskHandle));
    DAQmxErrChk (DAQmxStartTask(encodertaskHandle[0]));
    DAQmxErrChk (DAQmxStartTask(encodertaskHandle[1]));
    timeData.resetTimer();
    tick = timeData.getCurrentTime();
    float64 goffsetLoadCell[2]={0};
    int expProtocol = 0;
    int expProtocoAdvance = 0;
    while(live)
    {
        WaitForSingleObject(hIOMutex, INFINITE);
        //desire Forced, muscle Length, muscle Velocity PIPES should be read here
        
        DAQmxErrChk(DAQmxWaitForNextSampleClock(loadCelltaskHandle,10, &isLate));
        DAQmxErrChk (DAQmxReadAnalogF64(loadCelltaskHandle,-1,10.0,DAQmx_Val_GroupByScanNumber,loadCellData,2,NULL,NULL));
        DAQmxErrChk (DAQmxWriteAnalogF64(motorTaskHandle,1,FALSE,10,DAQmx_Val_GroupByChannel,motorCommand,NULL,NULL));
        DAQmxErrChk (DAQmxReadCounterF64(encodertaskHandle[0],1,10.0,encoderData1,1,NULL,0));
        DAQmxErrChk (DAQmxReadCounterF64(encodertaskHandle[1],1,10.0,encoderData2,1,NULL,0));
        if (dataAcquisitionFlag[1]){
            EMG = muscleEMG[0];
            if (EMG > 6)
                EMG = 6;
            if (EMG < -6)
                EMG = -6;
        }
        else
            EMG = 0;
        tock = timeData.getCurrentTime();
        if (resetMuscleLength)
        {
            muscleLengthOffset[0] = 2 * PI * shaftRadius * encoderData1[0] / 365;
            muscleLengthOffset[1] = 2 * PI * shaftRadius * encoderData2[0] / 365;
            resetMuscleLength = FALSE;
        }
        muscleLength[0] = ((2 * PI * shaftRadius * encoderData1[0] / 365) - muscleLengthOffset[0]);
        //muscleLength[0] = 0.95 + (muscleLength[0] + 0.0059)*24.7178;
        //muscleLength[0] = 0.95 + (muscleLength[0] + 0.0059)*40;
        muscleLength[0] = encoderBias[0] + muscleLength[0] *encoderGain[0];
        muscleLength[1] = ((2 * PI * shaftRadius * encoderData2[0] / 365) - muscleLengthOffset[1]);
        //muscleLength[1] = 1 + (muscleLength[1] - 0.0058)*30 + 0.5;
        //muscleLength[1] = 0.95 + (muscleLength[1] - 0.0058)*24.4399;
        muscleLength[1] = encoderBias[1] + muscleLength[1] *encoderGain[1];
        muscleVel[0] = (muscleLength[0] -  muscleLengthPreviousTick[0]) / (tock - tick);
        muscleVel[1] = (muscleLength[1] -  muscleLengthPreviousTick[1]) / (tock - tick);

        muscleLengthPreviousTick[0] = muscleLength[0];
        muscleLengthPreviousTick[1] = muscleLength[1];
        
        loadCellData[0] = (loadCellData[0] * loadCellScale1) - loadCellOffset1;
        loadCellData[1] = (loadCellData[1] * loadCellScale2) - loadCellOffset2;
        errorForce[0] = motorRef[0] - loadCellData[0];
        errorForce[1] = motorRef[1] - loadCellData[1];
        integral[0] = integral[0] + errorForce[0] * (tock - tick);
        integral[1] = integral[1] + errorForce[1] * (tock - tick);
        motorCommand[0] = integral[0] * I;
        motorCommand[1] = integral[1] * I;
        motorCommand[2] = EMG;
        if (motorCommand[0] > motorMaxVoltage)
            motorCommand[0] = motorMaxVoltage;
        if (motorCommand[0] < motorMinVoltage)
            motorCommand[0] = motorMinVoltage;
        if (motorCommand[1] > motorMaxVoltage)
            motorCommand[1] = motorMaxVoltage;
        if (motorCommand[1] < motorMinVoltage)
            motorCommand[1] = motorMinVoltage;
        printf("F1: %+6.2f; F2: %+6.2f;L1: %+6.2f; L2: %+6.2f;, Dyn: %d, Sta: %d, \r",loadCellData[0],loadCellData[1],muscleLength[0],muscleLength[1],gammaDynamic1, gammaStatic1);
        ReleaseMutex( hIOMutex);
        //fprintf(dataFile,"%.3f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%d\n",tock,loadCellData[0],loadCellData[1],motorRef[0],motorRef[1], muscleLength[0], muscleLength[1], muscleVel[0],muscleVel[1], muscleEMG[0], muscleEMG[1], isLate);
        //fprintf(dataFile,"%.3f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%d,%d,%d\n",tock,loadCellData[0],loadCellData[1], muscleLength[0], muscleLength[1], muscleVel[0],muscleVel[1], muscleEMG[0], muscleEMG[1], gammaStatic, gammaDynamic, isLate);
        //fprintf(dataFile,"%.3f,%.6f,%.6f,%.6f,%.6f,%d,%d,%d\n",tock, muscleLength[0], muscleLength[1], muscleEMG[0], muscleEMG[1], gammaStatic, gammaDynamic, isLate);
        sprintf(dataSample,"%.3f,%d,%.6f,%.6f,%.6f,%.6f",tock,expProtocol,muscleLength[0], muscleLength[1], loadCellData[0],loadCellData[1]);
        if (dataAcquisitionFlag[0]){
            sprintf(dataTemp,",%.6f,%.6f",motorRef[0],motorRef[1]);
            strcat (dataSample, dataTemp);
        }
        if (dataAcquisitionFlag[1]){
            sprintf(dataTemp,",%.6f,%.6f",muscleEMG[0], muscleEMG[1]);
            strcat (dataSample, dataTemp);
        }
         if (dataAcquisitionFlag[2]){
            sprintf(dataTemp,",%.6f,%.6f",spindleIa[0], spindleIa[1]);
            strcat (dataSample, dataTemp);
        }
        if (dataAcquisitionFlag[3]){
            sprintf(dataTemp,",%.6f,%.6f",spindleII[0], spindleII[1]);
            strcat (dataSample, dataTemp);
        }
        if (dataAcquisitionFlag[4]){
            sprintf(dataTemp,",%d,%d",muscleSpikeCount[0], muscleSpikeCount[1]);
            strcat (dataSample, dataTemp);
        }
        if (dataAcquisitionFlag[5]){
            sprintf(dataTemp,",%u,%u",raster_MN_1[0], raster_MN_1[1]);
            strcat (dataSample, dataTemp);
        }
        if (dataAcquisitionFlag[6]){
            sprintf(dataTemp,",%u,%u",raster_MN_2[0], raster_MN_2[1]);
            strcat (dataSample, dataTemp);
        }
        if (dataAcquisitionFlag[7]){
            sprintf(dataTemp,",%u,%u",raster_MN_3[0], raster_MN_3[1]);
            strcat (dataSample, dataTemp);
        }
        if (dataAcquisitionFlag[8]){
            sprintf(dataTemp,",%u,%u",raster_MN_4[0], raster_MN_4[1]);
            strcat (dataSample, dataTemp);
        }
        if (dataAcquisitionFlag[9]){
            sprintf(dataTemp,",%u,%u",raster_MN_5[0], raster_MN_5[1]);
            strcat (dataSample, dataTemp);
        }
        if (dataAcquisitionFlag[10]){
            sprintf(dataTemp,",%u,%u",raster_MN_6[0], raster_MN_6[1]);
            strcat (dataSample, dataTemp);
        }
        if (dataAcquisitionFlag[11]){
            cortexDrive[0] = max((cortexVoluntaryAmp -0) * sin (2 * 3.1416 * cortexVoluntaryFreq * tick), 0);
            cortexDrive[1] = max((cortexVoluntaryAmp -0) * sin (2 * 3.1416 * cortexVoluntaryFreq * tick + 3.1416), 0);
        }
        //sprintf(dataTemp,",%d,%d,%d,%d,%.3f,%.3f,%d\n",gammaStatic1, gammaDynamic1, gammaStatic2, gammaDynamic2, cortexDrive[0], cortexDrive[1],newTrial);
        sprintf(dataTemp,"\n");
        if (trialTrigger == 1){
            expProtocoAdvance = 1;
            trialTrigger = 0;
        }
        if (trialTrigger == 2){
            expProtocoAdvance = 10;
            trialTrigger = 0;
        }
        if (trialTrigger == 3){
            expProtocoAdvance = 11;
            trialTrigger = 0;
        }
        expProtocol = 0;
        switch(expProtocoAdvance){
            case 1:
                expProtocol = -1000;
                expProtocoAdvance = 2;
                break;
            case 2:
                expProtocol = gammaDynamic1;
                expProtocoAdvance = 3;
                break;
            case 3:
                expProtocol = gammaStatic1;
                expProtocoAdvance = 4;
                break;
            case 4:
                expProtocol =  cortexDrive[0];
                expProtocoAdvance = 5;
                break;
            case 5:
                expProtocol = gammaDynamic2;
                expProtocoAdvance = 6;
                break;
            case 6:
                expProtocol = gammaStatic2;
                expProtocoAdvance = 7;
                break;
            case 7:
                expProtocol =  cortexDrive[1];
                expProtocoAdvance = 8;
                break;
            case 8: 
                expProtocol = angle;
                expProtocoAdvance = 9;
                break;
            case 9:
                expProtocol = velocity;
                expProtocoAdvance = 0;
                break;
            case 10:
                expProtocol = -1;
                expProtocoAdvance = 0;
                break;
            case 11:
                expProtocol = -2;
                expProtocoAdvance = 0;
                break;
        }
        strcat (dataSample, dataTemp);
        fprintf(dataFile,dataSample);
        tick = timeData.getCurrentTime();

    }
    isControlling = FALSE;
    DAQmxStopTask(motorTaskHandle);
    fclose(dataFile);
Error:
	if( DAQmxFailed(error) ) {
		DAQmxGetExtendedErrorInfo(errBuff,2048);
		/*********************************************/
		// DAQmx Stop Code
		/*********************************************/
		DAQmxStopTask(loadCelltaskHandle);
		DAQmxClearTask(loadCelltaskHandle);
        DAQmxStopTask(encodertaskHandle);
		DAQmxClearTask(encodertaskHandle);
        DAQmxStopTask(motorTaskHandle);
		DAQmxClearTask(motorTaskHandle);
        DAQmxStopTask(motorEnableHandle);
		DAQmxClearTask(motorEnableHandle);
		printf("DAQmx Error: %s\n",errBuff);
        printf("Motor control Error\n");
	}
}
Exemple #14
0
int32 Tweezers::Run(float64* force, float64* indata, void* lpParam)
{
	threadinfo* t = (threadinfo*)lpParam;

	// init output data array
	float64 out_data[1];
	out_data[0] = 0.0;

	register int i = 0,j = 0;

	// # of samples to be generated per cycle
	register int nofSamples = (int)(t->nofFrames/(*t->cycles)) * (*t->delta)*1E-3 * Srate_HTSP;
	//cerr<<nofSamples<<" samples\n";

	// setup HTSP timing and deactivate onboard memory
	DAQmxErrRtn(DAQmxCfgSampClkTiming(AOtaskHandle,"OnboardClock",Srate_HTSP,DAQmx_Val_Rising,DAQmx_Val_HWTimedSinglePoint,nofSamples));
	DAQmxSetRealTimeConvLateErrorsToWarnings(AOtaskHandle, TRUE);

	// setup start trigger
	DAQmxErrRtn(DAQmxCfgDigEdgeStartTrig(AOtaskHandle, "PFI0", DAQmx_Val_Rising));

	// setup counter task and start trigger
	// maybe change trigger to digital line? need to use ContSamps, otherwise limited frame #
	//DAQmxErrRtn(DAQmxCreateCOPulseChanTime(DOtaskHandle,"Dev1/Ctr0","",DAQmx_Val_Seconds,DAQmx_Val_Low,0,1E-3*(*t->delta)/2,1E-3*(*t->delta/2)));
	DAQmxErrRtn(DAQmxCfgImplicitTiming(DOtaskHandle, DAQmx_Val_ContSamps, 1));

	// setup start trigger
	DAQmxErrRtn(DAQmxCfgDigEdgeStartTrig(DOtaskHandle, "PFI0", DAQmx_Val_Rising));

	// setup analog in task
	DAQmxErrRtn(DAQmxCfgSampClkTiming(AItaskHandle,"Ctr0Out",100,DAQmx_Val_Rising,DAQmx_Val_FiniteSamps,*t->cycles * t->nofFrames));
	//DAQmxErrRtn(DAQmxCfgDigEdgeStartTrig(AItaskHandle, "PFI0", DAQmx_Val_Rising));

	// start tasks (still waiting for edge trigger from TRtask)
	DAQmxErrRtn(DAQmxStartTask(DOtaskHandle));
	DAQmxErrRtn(DAQmxStartTask(AOtaskHandle));
	DAQmxErrRtn(DAQmxStartTask(AItaskHandle));

	// precalulate number of loop runs to speed up loop
	int samps = (nofSamples * (*t->cycles) - 1);
	
	// write first sample outside loop, so there is enough time to send the TR start trigger
	out_data[0] = current(force[0],t->dist);

	DAQmxErrRtn(DAQmxWriteAnalogF64(AOtaskHandle,1,true,-1,DAQmx_Val_GroupByChannel,out_data,&written,NULL));

	// GO!
	DAQmxErrRtn(DAQmxWriteDigitalLines(TRtaskHandle,1,1,10,DAQmx_Val_GroupByChannel,trigdata[1],&written,NULL));

	// 1 kHz sample generation loop
	while(!(*t->bead_lost &&
			// [email protected]: 05/10/2012 16:16 - dont stop recording if bead is lost in Creep-noint protocol
			*t->protocol != "Creep-noint"
			// end of change
		) && i < samps)
	{
		j = (++i % nofSamples);
		//cerr<<j<<"\r";
		out_data[0] = current(force[j],t->dist);
		DAQmxErrRtn(DAQmxWaitForNextSampleClock(AOtaskHandle, 1.0, &islate));
		DAQmxErrRtn(DAQmxWriteAnalogF64(AOtaskHandle,1,true,-1,DAQmx_Val_GroupByChannel,out_data,&written,NULL));
		if(islate)
		{
			cerr<<i++<<"\n****** late write - out of sync! *******\n";
			*t->bead_lost = TRUE;
			t->syncerror = TRUE;
		}
	}

	printf("DEBUG: bead_lost(%d) protocol(%s) i(%d) samps(%d)\n",
		*t->bead_lost, *t->protocol, i, samps);

	// wait for last sample to be generated
	DAQmxErrRtn(DAQmxWaitForNextSampleClock(AOtaskHandle, 1.0, &islate));

	// make sure enough trigger pulses are generated
	Sleep(*t->delta * 5);

	// stop tasks
	DAQmxErrRtn(DAQmxStopTask(DOtaskHandle));
	DAQmxErrRtn(DAQmxStopTask(AOtaskHandle));

	// number of frames actually taken
	t->FramesTaken = 1 + floor(t->nofFrames * (double)i/(double)(nofSamples * (*t->cycles)));

	// read protocol samples
	DAQmxReadAnalogF64(AItaskHandle,t->FramesTaken,5.0,DAQmx_Val_GroupByChannel,indata,t->FramesTaken*2,&read,NULL);

	DAQmxErrRtn(DAQmxStopTask(AItaskHandle));
	
	// disable start triggers
	DAQmxErrRtn(DAQmxDisableStartTrig(DOtaskHandle));
	DAQmxErrRtn(DAQmxDisableStartTrig(AOtaskHandle));
	
	// reset trigger line
	DAQmxErrRtn(DAQmxWriteDigitalLines(TRtaskHandle,1,1,10,DAQmx_Val_GroupByChannel,trigdata[0],&written,NULL));

}
Exemple #15
0
int main(int argc, char *argv[]){
	int			sampletime = 1; // in s
	int			numSamples;
	int32       error = 0;
	TaskHandle  taskHandle = 0;
	int32       read;
	float64     *data;
	char		filename[2048] = {'\0'};
	char        errBuff[2048] = {'\0'};
	int	recording = 1;
	float64     state = -10; // used to detect edge  
	FILE *pFile; // file id for output twophoton times file
	
	if(argc<2){
		customerror("Not enough arguments given.");
	}

    sampletime = atoi( argv[1]);
	if(sampletime<1){
		customerror("Sampletime given is incorrect.");
	}

	strncpy(filename,argv[2],2048);
	
	// calculate number of samples needed
	numSamples = sampletime *(int) (SAMPLE_FREQUENCY+1);

	// allocating buffer
	data = (float64*)malloc( numSamples *sizeof( float64 ));

	// open file
	pFile = fopen(filename,"w");
	if (pFile==NULL){
		customerror("Failed to open %s", filename);
	}

/*
	char curdir[FILENAME_MAX];
	memset(curdir, 0, sizeof(curdir));
	if (!GetCurrentDir(curdir, sizeof(curdir))) {
		customerror("Couldn't get current directory!");
	}
	printf("Current directory: %s\n", curdir);
*/
	printf("Filename: %s\n", filename);

	// DAQmx Configure Code
	printf("DAQmx Configure Code\n");
	DAQmxErrChk (DAQmxCreateTask("",&taskHandle));
	DAQmxErrChk (DAQmxCreateAIVoltageChan(taskHandle,"Dev1/ai0","",DAQmx_Val_Cfg_Default,-10.0,10.0,DAQmx_Val_Volts,NULL));
	DAQmxErrChk (DAQmxCfgSampClkTiming(taskHandle,"",SAMPLE_FREQUENCY,DAQmx_Val_Rising,DAQmx_Val_FiniteSamps,numSamples));
	//DAQmxErrChk (DAQmxCfgDigEdgeStartTrig(taskHandle,"/Dev1/PFI0",DAQmx_Val_Rising));
	//DAQmxErrChk (DAQmxCfgDigEdgeRefTrig(taskHandle,"/Dev1/PFI0",DAQmx_Val_Rising,100));

	// DAQmx Start Code
	printf("DAQmx Start Code\n");
	DAQmxErrChk (DAQmxStartTask(taskHandle));
	printf("Acquiring for %d seconds a total of %d samples at %f Hz\n", sampletime, numSamples, SAMPLE_FREQUENCY);

	// DAQmx Read Code
	printf("DAQmx Read Code\n");
	DAQmxErrChk (DAQmxReadAnalogF64(taskHandle,-1,sampletime+1,0,data,numSamples,&read,NULL));
	printf("read = %d\n",read);
	parse_times(data, read, &state, pFile);
	if( read<numSamples ){
		customerror("Error occurred. Acquired fewer than the requested number of samples. ");
	}
	
	printf("Acquired %d points\n",read);

Error:
	if( DAQmxFailed(error) )
		DAQmxGetExtendedErrorInfo(errBuff,2048);
	if( taskHandle!=0 ) {
		// DAQmx Stop Code
		DAQmxStopTask(taskHandle);
		DAQmxClearTask(taskHandle);
	}
	if( DAQmxFailed(error) )
		printf("DAQmx Error: %s\n",errBuff);

	free(data);
	fclose(pFile);

	//printf("End of program, press Enter key to quit\n");
	//getchar();
	return 0;
}
// from LifetimeAcq(float xVolts, float yVolts, ScanStruct scanStructure, char FILE_NAME[]);
int LifetimeAcq::lifetimeAcq(float xVolts, float yVolts,ScanEngine* scanStruct, char FILE_NAME[])
{
	int				status = 0;
	int				error;
	long			sampsRead = 0;
	unsigned long	totRead = 0;
	char			errBuff[2048];
	double*			acqData;

	if (VERBOSE)
	{
		/*	
		cout << "Hit Enter to acquire " << NUM_TRIGS << " triggers of " << numSamps		//NEED IMPLEMENTATION
											<< " samples each. \n";
		cout << "Data will be written to " <<FILE_NAME << " (Hit enter to begin)";
		c = cin.get();
		cout << "\nAcquiring...";
		*/
	}
	acqData = new double[totSamps];


	status = this->configDAQmxTasks(xVolts, yVolts, scanStruct);
	
	
	//_____Start the tasks_____
	DAQmxStartTask(aoTaskHandle);
	DAQmxStartTask(acqTaskHandle);
	DAQmxStartTask(ctrTaskHandle);

	

	//_____Perform read_____
	while( totRead < totSamps )
	{
		DAQmxErrChk (DAQmxReadAnalogF64(acqTaskHandle,totSamps,-1,DAQmx_Val_GroupByScanNumber,
						acqData,totSamps,&sampsRead,NULL));

		if( sampsRead > 0 )
		{
			totRead += sampsRead;
			//cout << "Acquired "<< totRead << " samples.\n";
		}
	}


	

//status = WriteTheLTAcqData( acqData, FILE_NAME);
	status =this->stopTasks();
	delete [] acqData;
	acqData = NULL;
	if (VERBOSE)
	{
		/*																			NEED IMPLEMENTATION
		cout << "\nAcquired " << totSamps << " samples. (Hit enter to end)";
		c = cin.get();
		*/
	}
		return 1;

Error:
	if (acqData)
	{
		delete [] acqData;
		acqData = NULL;
	}
	if( DAQmxFailed(error) )
		DAQmxGetExtendedErrorInfo(errBuff,2048);


	status = this->stopTasks();


	if( DAQmxFailed(error) )
	{
		/*
		cout << "DAQmx Error: "<<errBuff << "\n";				NEED IMPLEMENTATION
		c = cin.get();
		*/
	}
		return 0;

}