Exemple #1
0
// Read up to the specified number of bytes, return bytes actually read
u32 ser_read( int id, u8* dest, u32 maxsize )
{
  DWORD dwRxSize;
  FT_STATUS	ftStatus;
  DWORD dwBytesRead;

  if( ser_timeout == SER_INF_TIMEOUT ) {
    printf( "infinite timeout selected.\n" );
    FT_SetTimeouts(ftHandle[id], 10000000, 10000000); // a couple hours to timeout...
    dwRxSize = 0;
    ftStatus = FT_OK;
    while ((dwRxSize < maxsize) && (ftStatus == FT_OK)) {
      ftStatus = FT_GetQueueStatus(ftHandle[id], &dwRxSize);
    }

    if(ftStatus == FT_OK) {
      if((ftStatus = FT_Read(ftHandle[id], dest, maxsize, &dwBytesRead)) != FT_OK) {
	printf("Error FT_Read(%d)\n", ftStatus);
      }
      else {
	if( ser_dbg )
	  printf("FT_Read = %d\n", dwBytesRead);
      }
    }
    else {
      printf("Error FT_GetQueueStatus(%d)\n", ftStatus);
      return 0;
    }
    return (u32) dwBytesRead;
  }
  else
  {
  //  fd_set readfs;
  //  struct timeval tv;
  //  int retval;

    if( ser_timeout == 0 )
      ser_timeout = 1;
    //fprintf(stderr,"setting timeout to %u\n", ser_timeout );
    //fprintf(stderr,"read size: %d\n",maxsize);
    //fprintf(stderr,"id: %d\n",id);
    FT_SetTimeouts(ftHandle[id], ser_timeout, ser_timeout);

    if((ftStatus = FT_Read(ftHandle[id], dest, maxsize, &dwBytesRead)) != FT_OK) {
     // fprintf(stderr,"Error FT_Read(%d)\n", ftStatus);
    }
    else {
      ftStatus = FT_GetQueueStatus(ftHandle[id], &dwRxSize);

  	//  fprintf(stderr,"  - ser_read [%d | %02x] . %d\n", dwBytesRead, *dest & 0xFF, dwRxSize);
    }

    //fprintf(stderr,"read: %u\n",dwBytesRead);
    return (u32) dwBytesRead;
  }
}
Exemple #2
0
// USB 初期化
int InitUSB()
{
	FT_STATUS ftStatus;

	// USB をオープン
	ftStatus = FT_OpenEx("USBCONEMU", FT_OPEN_BY_DESCRIPTION, &ftHandle);
	if (ftStatus != FT_OK) return 1;

	// Output mode 設定
	ftStatus = FT_SetBitMode(ftHandle, 0x00, 0x40);
	if (ftStatus != FT_OK) return 1;

	// バッファサイズ設定
	ftStatus = FT_SetUSBParameters(ftHandle, MAX_BUFSIZE, 0);
	if (ftStatus != FT_OK) return 1;

	// デバイスリセット
	ftStatus = FT_ResetDevice(ftHandle);
	if (ftStatus != FT_OK) return 1;

	// バッファクリア
	ftStatus = FT_Purge(ftHandle, FT_PURGE_RX | FT_PURGE_TX);
	if (ftStatus != FT_OK) return 1;

	// Time Out 設定
	ftStatus = FT_SetTimeouts(ftHandle, NULL, NULL);
	if (ftStatus != FT_OK) return 1;

	Sleep(150);
	return 0;
}
Exemple #3
0
FT_STATUS ftdimut_setup() {
  FT_STATUS ftStatus; 
  unsigned char timer;

	ftStatus = FT_SetVIDPID(USB_VID, USB_PID);
  if(ftStatus != FT_OK) return ftStatus;
	ftStatus = FT_Open(0, &ftHandle);
  if(ftStatus != FT_OK) return ftStatus;
  ftStatus = FT_ResetDevice(ftHandle);
  if(ftStatus != FT_OK) return ftStatus;
  ftStatus = FT_Purge(ftHandle, FT_PURGE_RX | FT_PURGE_TX);
  if(ftStatus != FT_OK) return ftStatus;
  ftStatus = FT_SetBaudRate(ftHandle, 15625);
  if(ftStatus != FT_OK) return ftStatus;
  ftStatus = FT_SetDataCharacteristics(ftHandle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE);
  if(ftStatus != FT_OK) return ftStatus;
  ftStatus = FT_SetFlowControl(ftHandle, FT_FLOW_NONE, 0, 0);
  if(ftStatus != FT_OK) return ftStatus;
  ftStatus = FT_SetTimeouts(ftHandle, 1000, 1000);
  if(ftStatus != FT_OK) return ftStatus;
  ftStatus = FT_GetLatencyTimer(ftHandle, &timer);
  if(ftStatus != FT_OK) return ftStatus;
  ftStatus = FT_SetLatencyTimer(ftHandle, 1);
  if(ftStatus != FT_OK) return ftStatus;

  return FT_OK;
}
Exemple #4
0
void TellStick::aquireTellStick() {
	char *tempSerial = new char[serial().size()+1];
#ifdef _WINDOWS
	strcpy_s(tempSerial, serial().size()+1, serial().toLocal8Bit());
#else
	strcpy(tempSerial, serial().toLocal8Bit());
	int pid = 0x0C30;
	if (type() == 2) {
		pid = 0x0C31;
	}
	FT_SetVIDPID(0x1781, pid);
#endif
	FT_STATUS ftStatus = FT_OpenEx(tempSerial, FT_OPEN_BY_SERIAL_NUMBER, &d->ftHandle);
	delete tempSerial;
	if (ftStatus != FT_OK) {
		return;
	}
	//open = true;

	if (type() == 2) {
		FT_SetBaudRate(d->ftHandle, 115200);
	} else {
		FT_SetBaudRate(d->ftHandle, 9600);
	}
	FT_SetFlowControl(d->ftHandle, FT_FLOW_NONE, 0, 0);
	FT_SetTimeouts(d->ftHandle,1000,0);

	setUpgradeStep(2);
	QTimer::singleShot(0, this, SLOT(enterBootloader()));
}
/*
 * Class:     kinetic_Kinetic1090Puck
 * Method:    puckOpen
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_kinetic_Kinetic1090Puck_puckOpen(JNIEnv *env, jobject obj)
{
    // open the device
	FT_STATUS ftStatus = FT_OpenEx("Kinetic 1090 Puck Beavis 3A B", FT_OPEN_BY_DESCRIPTION, &ftHandle);
    if (ftStatus != FT_OK) {
        return -1;
    }

	// set the baud rate
	ftStatus = FT_SetBaudRate(ftHandle, 3000000);
    if (ftStatus != FT_OK) {
        return -1;
    }

	// set the data characteristics
	ftStatus = FT_SetDataCharacteristics(ftHandle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE);
    if (ftStatus != FT_OK) {
        return -1;
    }

	// set flow control
	ftStatus = FT_SetFlowControl(ftHandle, FT_FLOW_NONE, 0x11, 0x13);
	if (ftStatus != FT_OK) {
        return -1;
    }

	// set read and write timeouts
	ftStatus = FT_SetTimeouts(ftHandle, 5000, 1000);
	if (ftStatus != FT_OK) {
        return -1;
    }

	return 0;
}
Exemple #6
0
/*
 * Установка таймаута
 */
int FtdiDevices::setTimeouts(int rxTimeout, int txTimeout ) {
  FT_STATUS ftStatus;
  ftStatus = FT_SetTimeouts(m_ftHandleA, rxTimeout, txTimeout);
  if (!FT_SUCCESS(ftStatus)) {
      return false;
    }
  return true;
}
Exemple #7
0
extern "C" BOOL	ReadByteEx (BYTE *data, int timeout, BOOL warn)
{
	if(data == NULL)
		return FALSE;
	if (ParPort == -1)
	{
		DWORD BytesReceived = 0;
		FT_SetTimeouts(ftHandleA,timeout*1000,0);
		ftStatus = FT_Read(ftHandleA,RxBuffer,1,&BytesReceived);
		if (ftStatus == FT_OK)
		{
			if (BytesReceived == 1)
			{
				// FT_Read OK
				*data = RxBuffer[0];
				return TRUE;
			}
			else
			{
				// FT_Read Timeout
				if (warn)
					MessageBox(topHWnd, "USB Error: Read Timeout", "ReadByteEx", MB_OK | MB_ICONERROR);
				return FALSE;
			}
		}
		else
		{
			// FT_Read Failed
			if (warn)
				MessageBox(topHWnd, "USB Error: Read Failed", "ReadByteEx", MB_OK | MB_ICONERROR);
			return FALSE;
		}
	}
	else
	{
		BYTE a, b;
		time_t starttime = time(NULL);
		shadow |= 0x20;
		pwControl(shadow);	// set port to input mode
		b = prStatus();		// wait for ACK
		while (!((b ^ c) & 0x20))
		{
			b = prStatus();
			if (time(NULL) > starttime + (time_t)timeout)
			{
				if (warn)
					MessageBox(topHWnd, "Timeout on data transfer!", "ReadByte", MB_OK | MB_ICONERROR);
				return FALSE;
			}
		}
		c = b;
		a = prData();		// read data
		shadow ^= 0x02;
		pwControl(shadow);	// signal byte received
		*data = a;
		return TRUE;
	}
}
Exemple #8
0
/**
 *  Чтение данных с устройства
 */
int FtdiDevices::readData( char *data, DWORD size, unsigned int *rcnt ) {
  FT_STATUS ftStatus;
  DWORD     BytesReceived;

  QString msg = QString(" Исполнение операции чтения (READ)."\
                        " Дескриптор устройства = %1"\
                        " Размер = %2").arg( ( int )m_ftHandleA ).arg( size );

  /* Запись в лог сообщения */
  appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE, msg, appLogger.SYSTEM_LOGGER  );

  ftStatus = FT_SetTimeouts( m_ftHandleA, 100, 100 );
  if ( ftStatus != FT_OK ) {
    /* Запись в лог сообщения */
    appLogger.sendDataToViewer( appLogger.ERROR_MSG_TYPE,
                                                 " Операция установки таймаута не выполнена! ",
                                                 appLogger.SYSTEM_LOGGER );
  }
  else {
    /* Запись в лог сообщения */
    appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE,
                                                 " Операция установки таймаута выполнена! ",
                                                 appLogger.SYSTEM_LOGGER );
  }

  ftStatus = FT_Read( m_ftHandleA, data, size, &BytesReceived );

  /* Запись дампа пакета в лог */
  if ( BytesReceived != 0) {
    appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE, "Дамп ответа: ", appLogger.PROTOCOL_LOGGER );
    QString dump = "";
    for ( unsigned int i = 0; i < BytesReceived; i++ ) {
      dump += QString(" 0x%1 ").arg( (unsigned char)data[i], 0, 16 );
    }
    appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE, dump, appLogger.PROTOCOL_LOGGER );
  }
  *rcnt = BytesReceived;

  if ( ftStatus == FT_OK ) {
    if ( BytesReceived == size ) {
      /* Запись в лог сообщения */
        appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE,QString(" Все данные получены успешно! "), appLogger.SYSTEM_LOGGER );
      }
    else {
      /* Запись в лог сообщения */
        appLogger.sendDataToViewer( appLogger.WARNING_MSG_TYPE,QString(" Не все данные получены успешно! "), appLogger.SYSTEM_LOGGER );
        return FT_ERROR;
      }
    }
  else {
    /* Запись в лог сообщения */
      appLogger.sendDataToViewer( appLogger.ERROR_MSG_TYPE, QString(" Read выполнился с ошибкой! "), appLogger.SYSTEM_LOGGER );
      return FT_ERROR;
    }

  return FT_SUCCESSFUL;
}
Exemple #9
0
QString FTD2XXInterface::readLabel(uchar label, int *ESTA_code)
{
    FT_HANDLE ftdi = NULL;

    if (FT_Open(id(), &ftdi) != FT_OK)
        return QString();

    if(FT_ResetDevice(ftdi) != FT_OK)
        return QString();

    if(FT_SetBaudRate(ftdi, 250000) != FT_OK)
        return QString();

    if(FT_SetDataCharacteristics(ftdi, FT_BITS_8, FT_STOP_BITS_2, FT_PARITY_NONE) != FT_OK)
        return QString();

    if(FT_SetFlowControl(ftdi, 0, 0, 0) != FT_OK)
        return QString();

    QByteArray request;
    request.append(ENTTEC_PRO_START_OF_MSG);
    request.append(label);
    request.append(ENTTEC_PRO_DMX_ZERO); // data length LSB
    request.append(ENTTEC_PRO_DMX_ZERO); // data length MSB
    request.append(ENTTEC_PRO_END_OF_MSG);

    DWORD written = 0;
    if (FT_Write(ftdi, (char*) request.data(), request.size(), &written) != FT_OK)
        return QString();

    if (written == 0)
    {
        qDebug() << Q_FUNC_INFO << "Cannot write data to device";
        return QString();
    }

    uchar* buffer = (uchar*) malloc(sizeof(uchar) * 40);
    Q_ASSERT(buffer != NULL);

    int read = 0;
    QByteArray array;
    FT_SetTimeouts(ftdi, 500,0);
    FT_Read(ftdi, buffer, 40, (LPDWORD) &read);
    qDebug() << Q_FUNC_INFO << "----- Read: " << read << " ------";
    for (int i = 0; i < read; i++)
        array.append((char) buffer[i]);

    if (array[0] != ENTTEC_PRO_START_OF_MSG)
        qDebug() << Q_FUNC_INFO << "Reply message wrong start code: " << QString::number(array[0], 16);
    *ESTA_code = (array[5] << 8) | array[4];
    array.remove(0, 6); // 4 bytes of Enttec protocol + 2 of ESTA ID
    array.replace(ENTTEC_PRO_END_OF_MSG, '\0'); // replace Enttec termination with string termination

    FT_Close(ftdi);
    return QString(array);
}
Exemple #10
0
void
serial_set_timeout (int mseconds)
{
  if (verbose > 2)
  dprintf("timeout = %d\n", mseconds);
  if (mseconds == -1)
    mseconds = 0x7fffffff;
  timeout_val = mseconds;
  FT_SetTimeouts (handle, timeout_val, 0x7fffffff);
}
Exemple #11
0
BOOL	WriteByteEx (BYTE data, int timeout, BOOL warn)
{
	if (ParPort == -1)
	{
		DWORD BytesWritten = 0;
		FT_SetTimeouts(ftHandleA,10000,0);
		TxBuffer[0] = data;
		ftStatus = FT_Write(ftHandleA,TxBuffer,1,&BytesWritten);
		if (ftStatus == FT_OK)
		{
			if (BytesWritten == 1)
			{
				// FT_Read OK
				return TRUE;
			}
			else
			{
				// FT_Write Timeout
				if (warn)
					MessageBox(topHWnd, "USB Error: Write Timeout", "WriteByteEx", MB_OK | MB_ICONERROR);
				return FALSE;
			}
		}
		else
		{
			// FT_Write Failed
			StatusText("FT STATUS = %i", ftStatus);
			MessageBox(topHWnd, "USB Error: Write Failed", "WriteByteEx", MB_OK | MB_ICONERROR);
			return FALSE;
		}
	}
	else
	{
		time_t starttime = time(NULL);
		BYTE b;
		shadow &= 0xDF;
		pwControl(shadow);	// set port to output mode
		pwData(data);		// output data
		shadow ^= 0x01;
		pwControl(shadow);	// signal byte sent
		b = prStatus();		// wait for ACK
		while (!((b ^ c) & 0x10))
		{
			b = prStatus();
			if (time(NULL) > starttime + (time_t)timeout)
			{
				if (warn)
					MessageBox(topHWnd, "Timeout on data transfer!", "WriteByte", MB_OK | MB_ICONERROR);
				return FALSE;
			}
		}
		c = b;
		return TRUE;
	}
}
Exemple #12
0
int main(int argc, char *argv[])
{
	char * pcBufRead;
	DWORD dwBytesRead;
	FILE * fh;
	FT_HANDLE ftHandle;
	FT_STATUS ftStatus;
	int iport;
	
	if(argc > 1) {
		sscanf(argv[1], "%d", &iport);
	}
	else {
		iport = 0;
	}
	
	fh = fopen("target.bin", "wb+");
	if(fh == NULL) {
		printf("Cant open source file\n");
		return 1;
	}
		
	ftStatus = FT_Open(iport, &ftHandle);
	if(ftStatus != FT_OK) {
		/* 
			This can fail if the ftdi_sio driver is loaded
		 	use lsmod to check this and rmmod ftdi_sio to remove
			also rmmod usbserial
		 */
		printf("FT_Open(%d) failed\n", iport);
		return 1;
	}

	pcBufRead = (char *)malloc(BUF_SIZE);
	FT_ResetDevice(ftHandle);
	FT_SetBaudRate(ftHandle, 115200);
	FT_SetDtr(ftHandle);
	FT_SetRts(ftHandle);
	FT_SetFlowControl(ftHandle, FT_FLOW_RTS_CTS, 0, 0);
	FT_SetTimeouts(ftHandle, 0, 0);				// infinite timeouts	
	FT_SetBitMode(ftHandle, 0xFF, 0x01);
	FT_Read(ftHandle, pcBufRead, BUF_SIZE, &dwBytesRead);

	fwrite(pcBufRead, 1, dwBytesRead, fh);
	fclose(fh);
	free(pcBufRead);
	FT_Close(ftHandle);
	
	return 0;
}
Exemple #13
0
/**
    Open a power meter probe by a given serial number

    \param pm a pointer to a pm_context
    \param serial the serial number

    \retval  0 - all fine
    \retval -1 - open failed (wrong serial number?)
    \retval -2 - setting baudrate failed
    \retval -3 - setting data characteristics failed
    \retval -4 - setting flow control failed
    \retval -5 - setting timeouts failed
    \retval -6 - purging buffers failed
    \retval -7 - resetting device failed
*/
PM600X_EXPORT int pm_open(struct pm_context *pm, unsigned long serial)
{
	FT_STATUS ftstat;

	// convert the serial into a 8 digit string with leading zeroes
	char serial_string[12];
	snprintf(serial_string, 12, "%06lu", serial);

	// open the device by a given serial number
	ftstat = FT_OpenEx((void *)serial_string, FT_OPEN_BY_SERIAL_NUMBER, &pm->handle);
	if (ftstat != FT_OK)
		pm_error_return(-1, "open failed (wrong serial number?)");

	// get the device info to obtain the power meter type
	unsigned long id;
	ftstat = FT_GetDeviceInfo(pm->handle, NULL, &id, NULL, NULL, NULL);
	if (ftstat != FT_OK)
		pm_error_return(-8, "can not retrieve device info!");

	pm->type = id;

	// set baud rate to 115200
	ftstat = FT_SetBaudRate(pm->handle, FT_BAUD_115200);
	if (ftstat != FT_OK)
		pm_error_return(-2, "setting baudrate failed");

	// set data characteristics to 8n1
	ftstat = FT_SetDataCharacteristics(pm->handle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE);
	if (ftstat != FT_OK)
		pm_error_return(-3, "setting data characteristics failed");

	// set flow control to NONE
	ftstat = FT_SetFlowControl(pm->handle, FT_FLOW_NONE, 0, 0);
	if (ftstat != FT_OK)
		pm_error_return(-4, "setting flow control failed");

	// set timeouts to 1 second for writes and 3.5 seconds for reads. This should be enough when measuring with averaging == 10000
	ftstat = FT_SetTimeouts(pm->handle, 3500, 1000);
	if (ftstat != FT_OK)
		pm_error_return(-5, "setting timeouts failed");

	// purge bufffers just in case
	ftstat = FT_Purge(pm->handle, FT_PURGE_RX | FT_PURGE_TX);
	if (ftstat != FT_OK)
		pm_error_return(-6, "purging buffers failed");

	// reset the device via *RST
	return pm_reset(pm);
}
Exemple #14
0
bool CUSB::Open(char serialNumber[])
{
	if (isUSB_open) { ftStatus = FT_DEVICE_NOT_OPENED; return false; }

	m_posR = m_sizeR = m_posW = 0;
	ftStatus = FT_OpenEx(serialNumber, FT_OPEN_BY_SERIAL_NUMBER, &ftHandle);
	if (ftStatus != FT_OK) return false;

	ftStatus = FT_SetBitMode(ftHandle, 0xFF, 0x40);
	if (ftStatus != FT_OK) return false;

	FT_SetTimeouts(ftHandle,1000,1000);
	isUSB_open = true;
	return true;
}
Exemple #15
0
// Write up to the specified number of bytes, return bytes actually written
u32 ser_write( int id, const u8 *src, u32 size )
{
  u32 res;
  FT_STATUS	ftStatus;
  DWORD dwBytesWritten;
  
  FT_SetTimeouts(ftHandle[id], ser_timeout, ser_timeout);

  if((ftStatus = FT_Write(ftHandle[id], (char *) src, size, &dwBytesWritten)) != FT_OK) {
    printf("Error FT_Write(%d)\n", ftStatus);
  }
  if( ser_dbg )
    printf("  - ser_wrt  [%d | %02x] *\n", dwBytesWritten, *src & 0xFF);

  return (u32) dwBytesWritten;
}
Exemple #16
0
int gecko_opendevice()
{
	// Open by Serial Number
	status = FT_OpenEx("GECKUSB0", FT_OPEN_BY_SERIAL_NUMBER, &fthandle);
	if(status != FT_OK){
		eprintf("Error: Couldn't connect to USB Gecko. Please check Installation\n");
		return 0;
	}
	// Reset the Device
	status = FT_ResetDevice(fthandle);
	if(status != FT_OK){
		eprintf("Error: Couldnt Reset Device %d\n",status);
		status = FT_Close(fthandle);
		return 0;
	}
	// Set a 3 second timeout for this example
	status = FT_SetTimeouts(fthandle,3000,3000);
	if(status != FT_OK){
		eprintf("Error: Timeouts failed to set %d\n",status);
		status = FT_Close(fthandle);
		return 0;
	}
	// Purge RX buffer
	status = FT_Purge(fthandle,FT_PURGE_RX);
	if(status != FT_OK){
		eprintf("Error: Problem clearing buffers %d\n",status);
		status = FT_Close(fthandle);
		return 0;
	}
	// Purge TX buffer
	status = FT_Purge(fthandle,FT_PURGE_TX);
	if(status != FT_OK){
		eprintf("Error: Problem clearing buffers %d\n",status);
		status = FT_Close(fthandle);
		return 0;
	}
	// Set packet size in bytes - 65536 packet is maximum packet size (USB 2.0)
	status = FT_SetUSBParameters(fthandle,65536,0);
	if(status != FT_OK){
		eprintf("Error: Couldnt Set USB Parameters %d\n",status);
		status = FT_Close(fthandle);
		return 0;
	}
	// take breath
	sleep(1);
	return 1;
}
Exemple #17
0
bool CUsb3003DF2ETInterface::OpenDevice(void)
{
    FT_STATUS ftStatus;
    int baudrate = 921600;
    
    //sets serial VID/PID for a Standard Device NOTE:  This is for legacy purposes only.  This can be ommitted.
    ftStatus = FT_SetVIDPID(m_uiVid, m_uiPid);
    if (ftStatus != FT_OK) {FTDI_Error((char *)"FT_SetVIDPID", ftStatus ); return false; }
    
    ftStatus = FT_OpenEx((PVOID)m_szDeviceSerial, FT_OPEN_BY_SERIAL_NUMBER, &m_FtdiHandle);
    if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_OpenEx", ftStatus ); return false; }
    
    CTimePoint::TaskSleepFor(50);
    FT_Purge(m_FtdiHandle, FT_PURGE_RX | FT_PURGE_TX );
    CTimePoint::TaskSleepFor(50);
    
    ftStatus = FT_SetDataCharacteristics(m_FtdiHandle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE);
    if ( ftStatus != FT_OK ) { FTDI_Error((char *)"FT_SetDataCharacteristics", ftStatus ); return false; }
    
    ftStatus = FT_SetFlowControl(m_FtdiHandle, FT_FLOW_RTS_CTS, 0x11, 0x13);
    if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetFlowControl", ftStatus ); return false; }
    
    ftStatus = FT_SetRts (m_FtdiHandle);
    if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetRts", ftStatus ); return false; }
    
    // for DF2ET-3003 interface pull DTR low to take AMBE3003 out of reset.
    ftStatus = FT_SetDtr( m_FtdiHandle );
    CTimePoint::TaskSleepFor(50);
    if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetDtr", ftStatus); return false; }
    
    ftStatus = FT_SetBaudRate(m_FtdiHandle, baudrate );
    if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetBaudRate", ftStatus ); return false; }
    
    ftStatus = FT_SetLatencyTimer(m_FtdiHandle, 4);
    if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetLatencyTimer", ftStatus ); return false; }
    
    ftStatus = FT_SetUSBParameters(m_FtdiHandle, USB3XXX_MAXPACKETSIZE, 0);
    if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetUSBParameters", ftStatus ); return false; }
    
    ftStatus = FT_SetTimeouts(m_FtdiHandle, 200, 200 );
    if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetTimeouts", ftStatus ); return false; }
    
    // done
    return true;
}
bool DYNA_initialize(FT_HANDLE ftHandleDYNA)
{

    FT_STATUS ft_status;

    ft_status = FT_ResetDevice(ftHandleDYNA);
    if( ft_status != FT_OK )
        goto DYNA_init_error;

    ft_status = FT_SetDataCharacteristics(ftHandleDYNA, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE);
    if( ft_status != FT_OK )
        goto DYNA_init_error;

    ft_status = FT_SetFlowControl(ftHandleDYNA, FT_FLOW_NONE, (UCHAR)0, (UCHAR)0);
    if( ft_status != FT_OK )
        goto DYNA_init_error;

    ft_status = FT_SetLatencyTimer(ftHandleDYNA, LATENCY_TIME);
    if( ft_status != FT_OK )
        goto DYNA_init_error;

    ft_status = FT_SetUSBParameters(ftHandleDYNA, IN_TRASFER_SIZE, 0);
    if( ft_status != FT_OK )
        goto DYNA_init_error;

    ft_status = FT_SetTimeouts(ftHandleDYNA, 0, 0);
    if( ft_status != FT_OK )
        goto DYNA_init_error;

    ft_status = FT_Purge(ftHandleDYNA, FT_PURGE_RX|FT_PURGE_TX);
    if( ft_status != FT_OK )
        goto DYNA_init_error;

    ft_status = FT_SetBaudRate(ftHandleDYNA, 1000000);
    if( ft_status != FT_OK )
        goto DYNA_init_error;

    return true;

DYNA_init_error:
    qDebug() << "\n\nUSB2Dynamixel Initialization Error!";
    FT_Close(ftHandleDYNA);
    return false;
}
int dxl_hal_open()
{
	FT_STATUS ft_status;

	dxl_hal_close();

	ft_status = FT_Open( 1, &ghFt_Handle );
	if( ft_status != FT_OK )
		goto DXL_HAL_OPEN_ERROR;

	ft_status = FT_ResetDevice( ghFt_Handle );
	if( ft_status != FT_OK )
		goto DXL_HAL_OPEN_ERROR;

	ft_status = FT_SetDataCharacteristics( ghFt_Handle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE );
	if( ft_status != FT_OK )
		goto DXL_HAL_OPEN_ERROR;

	ft_status = FT_SetFlowControl( ghFt_Handle, FT_FLOW_NONE, (UCHAR)0, (UCHAR)0 );
	if( ft_status != FT_OK )
		goto DXL_HAL_OPEN_ERROR;

	ft_status = FT_SetLatencyTimer( ghFt_Handle, LATENCY_TIME );
	if( ft_status != FT_OK )
		goto DXL_HAL_OPEN_ERROR;

	ft_status = FT_SetUSBParameters( ghFt_Handle, IN_TRASFER_SIZE, 0 );
	if( ft_status != FT_OK )
		goto DXL_HAL_OPEN_ERROR;

	ft_status = FT_SetTimeouts( ghFt_Handle, 0, 0 );
	if( ft_status != FT_OK )
		goto DXL_HAL_OPEN_ERROR;

	ft_status = FT_Purge( ghFt_Handle, FT_PURGE_RX|FT_PURGE_TX );
	if( ft_status != FT_OK )
		goto DXL_HAL_OPEN_ERROR;

	return 1;

DXL_HAL_OPEN_ERROR:
	dxl_hal_close();
	return 0;
}
Exemple #20
0
extern "C" BOOL WriteBlock (BYTE* blockdata, int size)
{
	int i;
	if (ParPort == -1)
	{
		DWORD BytesWritten = 0;
  		if(usb_timeout_error) return FALSE;
		FT_SetTimeouts(ftHandleA,10000,0);
		ftStatus = FT_Write(ftHandleA, (LPVOID)blockdata, size, &BytesWritten);
		if (ftStatus == FT_OK)
		{ 
			if (BytesWritten == size) 
			{ 
				// FT_Read OK
				return TRUE;
			} 
			else 
			{ 
				// FT_Write Timeout 
				MessageBox(topHWnd, "USB Error: Write Timeout", "WriteBlock", MB_OK | MB_ICONERROR);
				return FALSE;  
			} 
		} 
		else 
		{ 
			// FT_Write Failed 
			StatusText("FT STATUS = %i", ftStatus);
			MessageBox(topHWnd, "USB Error: Write Failed", "WriteBlock", MB_OK | MB_ICONERROR);
			return FALSE;  
		}
	}
	else
	{
		BOOL success;
		for (i = 0; i < size; i++)
		{
			success = WriteByteEx(blockdata[i], 10, TRUE);
			if (!success)
				return FALSE;
		}
		return TRUE;
	}
}
Exemple #21
0
int main(int argc, char *argv[])
{
	char cBufRead[BUF_SIZE];
	DWORD dwBytesRead;
	FT_STATUS ftStatus;
	FT_HANDLE ftHandle;
	int iport;
	int i;
	
	if(argc > 1) {
		sscanf(argv[1], "%d", &iport);
	}
	else {
		iport = 0;
	}
	
	ftStatus = FT_Open(iport, &ftHandle);
	if(ftStatus != FT_OK) {
		/* 
			This can fail if the ftdi_sio driver is loaded
		 	use lsmod to check this and rmmod ftdi_sio to remove
			also rmmod usbserial
		 */
		printf("FT_Open(%d) failed, with error %d.\n", iport, (int)ftStatus);
		printf("Use lsmod to check if ftdi_sio (and usbserial) are present.\n");
		printf("If so, unload them using rmmod, as they conflict with ftd2xx.\n");
		return 1;
	}

	FT_SetTimeouts(ftHandle, 3000, 3000);	// 3 second read timeout
	
	for(i = 0; i < 10 ; i++) {
		FT_Read(ftHandle, cBufRead, BUF_SIZE, &dwBytesRead);
		if(dwBytesRead != BUF_SIZE)
			printf("Timeout %d\n", i);
		else
			printf("Read %d\n", (int)dwBytesRead);
	}
		
		
	FT_Close(ftHandle);
	return 0;
}
Exemple #22
0
bool CMmcUsbHndlBase::SetTimeouts(unsigned int dReadTimeout, unsigned int dWriteTimeout)
{

	if( !AreLibraryFunctionsLoaded() )
	{
		perror("Library not loaded");
        return false;
    }

	FT_STATUS ftStatus = FT_SetTimeouts(m_Handle, dReadTimeout, dWriteTimeout);

	if( ftStatus != FT_OK )
	{
		std::string errormsg = GetFtStatusDescription(ftStatus);
		errormsg += ":FT_GetStatus";
		perror(errormsg.c_str());
	}


	return (FT_OK == ftStatus);
}
Exemple #23
0
static FT_HANDLE OpenUSBDevice( int nType, int nId )
{
	FT_HANDLE	hndl = 0;	
	unsigned 	i;
	DWORD		dwDevs;
	FT_DEVICE_LIST_INFO_NODE *pNodes = 0;

	if( FT_CreateDeviceInfoList( &dwDevs) == FT_OK )
	{
		pNodes = (FT_DEVICE_LIST_INFO_NODE *)calloc( sizeof(FT_DEVICE_LIST_INFO_NODE) , dwDevs );
		if( FT_GetDeviceInfoList( pNodes, &dwDevs ) == FT_OK )
		{
			for( i = 0; i < dwDevs; i++ )
			{
				if( pNodes[i].Type == nType && pNodes[i].ID == nId )
				{
					if( FT_OpenEx( pNodes[i].Description, FT_OPEN_BY_DESCRIPTION, &hndl ) != FT_OK )
					{
						hndl = 0;
						goto cleanup;
					} /* if */
					if( FT_SetLatencyTimer( hndl, s_nUsbLatency ) != FT_OK ||
						FT_SetTimeouts( hndl, s_nReadTimeout, s_nWriteTimeout ) != FT_OK )
					{
						FT_Close( s_hndl );
						hndl = 0;
						goto cleanup;
					}
					break;
				} /* if */
			} /* for */
		} /* if */
	} /* if */

cleanup:
	if( pNodes )
		free( pNodes );

	return hndl;
}
Exemple #24
0
/* Open USB */
quint16 ftdiChip::Open()
{
FT_STATUS ftStatus;

if (hdUSB!=NULL){Close();}

ftStatus=FT_Open(numDevice,&hdUSB);
    if (ftStatus!=FT_OK){
        emit signalStatusError(tr("Error open USB"),true);
        return retErr;
        }
ftStatus=FT_SetUSBParameters(hdUSB,1024,1024);
if (ftStatus!=FT_OK){// Error setting buffer sizes USB
    emit signalStatusError(tr("Error setting buffer sizes USB"),true);
    return retErr;
    }
ftStatus = FT_SetTimeouts(hdUSB,10,1);
if(ftStatus != FT_OK){
  return retErr;
  }
return retOk;
}
static void FTClassicPort_setTimeouts(FTClassicPort *self,ULONG ReadTimeout,ULONG WriteTimeout){
	self->status = FT_SetTimeouts(self->handle,
		ReadTimeout, WriteTimeout);		
}
Exemple #26
0
/**
 * Чтение значения порта Б микросхемы ftdi
 */
char FtdiDevices::readFromPortB( bool isNeedLog ){
  DWORD BytesRead;
  char  data = 0;

  /* Запись в лог сообщения */
  if ( isNeedLog ) appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE,
                                               " Исполнение операции чтения (READ_PORTB) ",
                                               appLogger.SYSTEM_LOGGER );

  if ( listPorts.size() > -1 ) {

    ftStatus = FT_Open( 1 /* Порт Б */, &m_ftHandleB );
    if ( ftStatus != FT_OK ) {
      /* Запись в лог сообщения */
      if ( isNeedLog ) appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE,
                                                   " Операция открытия порта не выполнена! ",
                                                   appLogger.SYSTEM_LOGGER );
    }
    else {
      /* Запись в лог сообщения */
      if ( isNeedLog ) appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE,
                                                   " Операция открытия порта выполнена! ",
                                                   appLogger.SYSTEM_LOGGER );
    }

    ftStatus = FT_SetBitMode( m_ftHandleB, 0xFE, 0x01 );
    if ( ftStatus == FT_OK ) {
      /* Запись в лог сообщения */
      if ( isNeedLog ) appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE," Операция установки bitbang порта выполнена! ", appLogger.SYSTEM_LOGGER );
    } else {
      /* Запись в лог сообщения */
       if ( isNeedLog ) appLogger.sendDataToViewer( appLogger.ERROR_MSG_TYPE," Операция установки bitbang порта не выполнена! ", appLogger.SYSTEM_LOGGER );
    }

    ftStatus = FT_SetTimeouts( m_ftHandleB, 100, 100 );
    if ( ftStatus != FT_OK ) {
      /* Запись в лог сообщения */
      if ( isNeedLog ) appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE,
                                                   " Операция установки таймаута не выполнена! ",
                                                   appLogger.SYSTEM_LOGGER );
    }
    else {
      /* Запись в лог сообщения */
      if ( isNeedLog ) appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE,
                                                   " Операция установки таймаута выполнена! ",
                                                   appLogger.SYSTEM_LOGGER );
    }

    ftStatus = FT_Read( m_ftHandleB, &data, 1, &BytesRead );
    if ( ftStatus != FT_OK ) {
      /* Запись в лог сообщения */
      if ( isNeedLog ) appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE,
                                                   " Операция чтения из порта не выполнена! ",
                                                   appLogger.SYSTEM_LOGGER );
    }
    else {
      /* Запись в лог сообщения */
      if ( isNeedLog ) appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE,
                                                   " Операция чтения из порта выполнена! ",
                                                   appLogger.SYSTEM_LOGGER );
    }

    ftStatus = FT_Close( m_ftHandleB );
    if ( ftStatus != FT_OK ) {
      /* Запись в лог сообщения */
      if ( isNeedLog ) appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE,
                                  " Операция закрытия порта не выполнена! ",
                                  appLogger.SYSTEM_LOGGER );
    }
    else {
      /* Запись в лог сообщения */
      if ( isNeedLog ) appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE,
                                  " Операция закрытия порта выполнена! ",
                                  appLogger.SYSTEM_LOGGER );
    }
  }

  /* Запись в лог сообщения */
  if ( isNeedLog ) appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE,
                                               QString(" Значения порта = %1").arg( data ),
                                               appLogger.SYSTEM_LOGGER );

  return data;
}
Exemple #27
0
int main(int argc, char *argv[])
{
	int        retCode = -1; // Assume failure
	int        f = 0;
	FT_STATUS  ftStatus = FT_OK;
	FT_HANDLE  ftHandle = NULL;
	int        portNum = -1; // Deliberately invalid
	DWORD      bytesToWrite = 0;
	DWORD      bytesWritten = 0;
	int        inputRate = -1; // Entered on command line
	int        baudRate = 38400; // Rate to actually use
	int        rates[] = {50, 75, 110, 134, 150, 200, 
	                      300, 600, 1200, 1800, 2400, 4800, 
	                      9600, 19200, 38400, 57600, 115200, 
	                      230400, 460800, 576000, 921600};
	
	if (argc > 1)
	{
		sscanf(argv[1], "%d", &portNum);
	}
	
	if (portNum < 0)
	{
		// Missing, or invalid.  Just use first port.
		portNum = 0;
	}
	
	if (portNum > 16)
	{
		// User probably specified a baud rate without a port number
		printf("Syntax: %s [port number] [baud rate]\n", argv[0]);
		portNum = 0;
	}
	
	if (argc > 2)
	{
		sscanf(argv[2], "%d", &inputRate);

		for (f = 0; f < (int)(ARRAY_SIZE(rates)); f++)
		{
			if (inputRate == rates[f])
			{
				// User entered a rate we support, so we'll use it.
				baudRate = inputRate;
				break;
			}
		}
	}
	
	if (baudRate < 0)
		baudRate = 9600;
		
	printf("Trying FTDI device %d at %d baud.\n", portNum, baudRate);
	
	ftStatus = FT_Open(portNum, &ftHandle);
	if (ftStatus != FT_OK) 
	{
		printf("FT_Open(%d) failed, with error %d.\n", portNum, (int)ftStatus);
		printf("Use lsmod to check if ftdi_sio (and usbserial) are present.\n");
		printf("If so, unload them using rmmod, as they conflict with ftd2xx.\n");
		goto exit;
	}

	assert(ftHandle != NULL);

	ftStatus = FT_ResetDevice(ftHandle);
	if (ftStatus != FT_OK) 
	{
		printf("Failure.  FT_ResetDevice returned %d.\n", (int)ftStatus);
		goto exit;
	}
	
	ftStatus = FT_SetBaudRate(ftHandle, (ULONG)baudRate);
	if (ftStatus != FT_OK) 
	{
		printf("Failure.  FT_SetBaudRate(%d) returned %d.\n", 
		       baudRate,
		       (int)ftStatus);
		goto exit;
	}
	
	ftStatus = FT_SetDataCharacteristics(ftHandle, 
	                                     FT_BITS_8,
	                                     FT_STOP_BITS_1,
	                                     FT_PARITY_NONE);
	if (ftStatus != FT_OK) 
	{
		printf("Failure.  FT_SetDataCharacteristics returned %d.\n", (int)ftStatus);
		goto exit;
	}
	                          
	// Indicate our presence to remote computer
	ftStatus = FT_SetDtr(ftHandle);
	if (ftStatus != FT_OK) 
	{
		printf("Failure.  FT_SetDtr returned %d.\n", (int)ftStatus);
		goto exit;
	}

	// Flow control is needed for higher baud rates
	ftStatus = FT_SetFlowControl(ftHandle, FT_FLOW_RTS_CTS, 0, 0);
	if (ftStatus != FT_OK) 
	{
		printf("Failure.  FT_SetFlowControl returned %d.\n", (int)ftStatus);
		goto exit;
	}

	// Assert Request-To-Send to prepare remote computer
	ftStatus = FT_SetRts(ftHandle);
	if (ftStatus != FT_OK) 
	{
		printf("Failure.  FT_SetRts returned %d.\n", (int)ftStatus);
		goto exit;
	}

	ftStatus = FT_SetTimeouts(ftHandle, 3000, 3000);	// 3 seconds
	if (ftStatus != FT_OK) 
	{
		printf("Failure.  FT_SetTimeouts returned %d\n", (int)ftStatus);
		goto exit;
	}

	bytesToWrite = (DWORD)(sizeof(testPattern) - 1); // Don't write string terminator
	
	ftStatus = FT_Write(ftHandle, 
	                    testPattern,
	                    bytesToWrite, 
	                    &bytesWritten);
	if (ftStatus != FT_OK) 
	{
		printf("Failure.  FT_Write returned %d\n", (int)ftStatus);
		goto exit;
	}
	
	if (bytesWritten != bytesToWrite)
	{
		printf("Failure.  FT_Write wrote %d bytes instead of %d.\n",
		       (int)bytesWritten,
		       (int)bytesToWrite);
		goto exit;
	}

	// Success
	retCode = 0;
	printf("Successfully wrote %d bytes\n", (int)bytesWritten);

exit:
	if (ftHandle != NULL)
		FT_Close(ftHandle);

	return retCode;
}
Exemple #28
0
int dev_open_uart (int n_dev_indx, FT_HANDLE *ph_device)
{

    FT_STATUS ft_status;
    DWORD   dw_num_devs;
    LONG    devLocation;


    ft_status = FT_ListDevices(&dw_num_devs, NULL, FT_LIST_NUMBER_ONLY);
    if (ft_status != FT_OK) return FALSE;

    if (dw_num_devs == 0){
        // No devices were found
        return FALSE;
    }

    ft_status = FT_ListDevices((void*)n_dev_indx, &devLocation, FT_LIST_BY_INDEX | FT_OPEN_BY_LOCATION);
    if (ft_status != FT_OK) {
        return FALSE;
    }

    ft_status |= FT_ListDevices((void*)n_dev_indx, &devDescriptor, FT_LIST_BY_INDEX | FT_OPEN_BY_DESCRIPTION);
    ft_status |= FT_ListDevices((void*)n_dev_indx, &devSerial, FT_LIST_BY_INDEX | FT_OPEN_BY_SERIAL_NUMBER);

    if (ft_status != FT_OK){
        return FALSE;
    }
#define FT_Classic  0

#if FT_Classic
    ft_status |= FT_OpenEx((void*)devLocation, FT_OPEN_BY_LOCATION, ph_device);

    ft_status |= FT_SetTimeouts(*ph_device, 500, 500);
    ft_status |= FT_SetLatencyTimer(*ph_device, 2);

    // Divisor selection
    // BAUD = 3000000 / Divisor
    // Divisor = (N + 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875)
    // Divisor = 24 ==> Baud 125000 
    ft_status |= FT_SetDivisor(*ph_device, 3000000 / 125000);

    // Set UART format 8N1
    ft_status |= FT_SetDataCharacteristics(*ph_device, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE);

    if (ft_status != FT_OK){
        return FALSE;
    }


    // Just in case
    FT_Purge(*ph_device, FT_PURGE_TX | FT_PURGE_RX);
#else


    // Open a device for overlapped I/O using its serial number
    *ph_device = FT_W32_CreateFile(
        (LPCTSTR)devLocation,
        GENERIC_READ | GENERIC_WRITE,
        0,
        0,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED | FT_OPEN_BY_LOCATION,
        0);

    if (*ph_device == INVALID_HANDLE_VALUE)
    {
        // FT_W32_CreateDevice failed
        return FALSE;
    }

    // ----------------------------------------
    // --- Set comm parameters
    // ----------------------------------------

    FTDCB ftDCB;
    FTTIMEOUTS    ftTimeouts;
    FTCOMSTAT    ftPortStatus;
    DWORD   dw_port_error;

    if (!FT_W32_GetCommState(*ph_device, &ftDCB))
    {
        return FALSE;
    }

    // Divisor selection
    // BAUD = 3000000 / Divisor
    // Divisor = (N + 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875)
    // Divisor = 24 ==> Baud 125000 

    ftDCB.BaudRate = 38400;
    ftDCB.fBinary = TRUE;                       /* Binary Mode (skip EOF check)    */
    ftDCB.fParity = FALSE;                      /* Enable parity checking          */
    ftDCB.fOutxCtsFlow = FALSE;                 /* CTS handshaking on output       */
    ftDCB.fOutxDsrFlow = FALSE;                 /* DSR handshaking on output       */
    ftDCB.fDtrControl = DTR_CONTROL_DISABLE;    /* DTR Flow control                */
    ftDCB.fTXContinueOnXoff = FALSE;

    ftDCB.fErrorChar = FALSE;            // enable error replacement 
    ftDCB.fNull = FALSE;                // enable null stripping 
    ftDCB.fRtsControl = RTS_CONTROL_DISABLE;       // RTS flow control 
    ftDCB.fAbortOnError = TRUE;            // abort reads/writes on error 

    ftDCB.fOutX = FALSE;                        /* Enable output X-ON/X-OFF        */
    ftDCB.fInX = FALSE;                         /* Enable input X-ON/X-OFF         */
    ftDCB.fNull = FALSE;                        /* Enable Null stripping           */
    ftDCB.fRtsControl = RTS_CONTROL_DISABLE;    /* Rts Flow control                */
    ftDCB.fAbortOnError = TRUE;                 /* Abort all reads and writes on Error */

    // 8N1
    ftDCB.ByteSize = 8;                 /* Number of bits/byte, 4-8        */
    ftDCB.Parity = NOPARITY;            /* 0-4=None,Odd,Even,Mark,Space    */
    ftDCB.StopBits = ONESTOPBIT;        /* 0,1,2 = 1, 1.5, 2               */

    if (!FT_W32_SetCommState(*ph_device, &ftDCB))
    {
        return FALSE;
    }

    FT_W32_GetCommState(*ph_device, &ftDCB);

    // Set serial port Timeout values
    FT_W32_GetCommTimeouts(*ph_device, &ftTimeouts);

    ftTimeouts.ReadIntervalTimeout = 0;
    ftTimeouts.ReadTotalTimeoutMultiplier = 0;
    ftTimeouts.ReadTotalTimeoutConstant = 200;
    ftTimeouts.WriteTotalTimeoutConstant = 0;
    ftTimeouts.WriteTotalTimeoutMultiplier = 0;

    FT_W32_SetCommTimeouts(*ph_device, &ftTimeouts);

    FT_W32_ClearCommError(*ph_device, &dw_port_error, &ftPortStatus);
    FT_W32_PurgeComm(*ph_device, PURGE_TXCLEAR | PURGE_RXCLEAR | PURGE_RXABORT | PURGE_TXABORT);

#endif  // End of W32 device init

    return TRUE;
}
Exemple #29
0
int openSerialPorts(int baud) {
  char * 	pcBufRead = NULL;
  char * 	pcBufLD[MAX_DEVICES + 1];
  DWORD	dwRxSize = 0;
  DWORD 	dwBytesWritten, dwBytesRead;
  FT_STATUS	ftStatus;
  int	iNumDevs = 0;
  int	i, j;
  int	iDevicesOpen;	
  unsigned char ucMode = 0x00;

  printf( "warning: opening up to %d ports and assuming all are Safecast devices.\n", MAX_DEVICES );
  printf( "todo: make this more selective and safer.\n" );

  for(i = 0; i < MAX_DEVICES; i++) {
    pcBufLD[i] = cBufLD[i];
  }
  pcBufLD[MAX_DEVICES] = NULL;
  
  ftStatus = FT_ListDevices(pcBufLD, &iNumDevs, FT_LIST_ALL | FT_OPEN_BY_SERIAL_NUMBER);
  
  if(ftStatus != FT_OK) {
    printf("Error: FT_ListDevices(%d)\n", ftStatus);
    return -1;
  }
  
  for(i = 0; ( (i <MAX_DEVICES) && (i < iNumDevs) ); i++) {
    printf("Device %d Serial Number - %s\n", i, cBufLD[i]);
  }
  
  for(i = 0; ( (i <MAX_DEVICES) && (i < iNumDevs) ) ; i++) {
    /* Setup */
    if((ftStatus = FT_OpenEx(cBufLD[i], FT_OPEN_BY_SERIAL_NUMBER, &ftHandle[i])) != FT_OK){
      /* 
	 This can fail if the ftdi_sio driver is loaded
	 use lsmod to check this and rmmod ftdi_sio to remove
	 also rmmod usbserial
      */
      printf("Error FT_OpenEx(%d), device\n", ftStatus);
      return -1;
    }
    
    printf("Opened device %s\n", cBufLD[i]);
    
//    if(getandcheckCBUS(ftHandle[i]) ) {
 //     printf( "getandcheckCBUS failed, exiting.\n" );
 //     return -1;
 //   }
    
    iDevicesOpen++;
    if((ftStatus = FT_SetBaudRate(ftHandle[i], baud)) != FT_OK) {
      printf("Error FT_SetBaudRate(%d), cBufLD[i] = %s\n", ftStatus, cBufLD[i]);
      break;
    }

    if((ftStatus = FT_SetDataCharacteristics(ftHandle[i], FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_EVEN)) != FT_OK) {
      printf("Error FT_SetDataCharacteristics(%d) = %s\n", ftStatus, cBufLD[i]);
      break;
    }
    
    FT_SetTimeouts(ftHandle[i], 500, 500);	// 500 ms read/write timeout

  }
  
  iDevicesOpen = i;
  foundDevices = i; // record this in a global

  if(pcBufRead)
    free(pcBufRead);

  return 0; // we always use the 0th device for now
}
Exemple #30
0
int main(int argc, char* argv[])
{
    FT_HANDLE fthandle;
    FT_STATUS status;
    DWORD numdev = 0;

    // Open the first device connected to the system (which has index 0). You can use the various other
    // functions such as open_by_description to make this much more flexible and user friendly to let the user
    // choose which device to open. See the D2xx Programmers Guide for more information

    // Check how many FTDI devices are connected and installed. If one or more connected, open the first one
    status = FT_CreateDeviceInfoList(&numdev);

    if 	((status == FT_OK) && (numdev > 0) )
    {
        // Open the device now
        status = FT_Open(0, &fthandle);
        if(status != FT_OK)
            printf("status not ok %d\n", status);

        // Set the In transfer size. You can set up to 64K if required. Ideally, use a small value like this for
        // receiving a few bytes at a time or a larger value if you will be transferring large amounts of data
        status = FT_SetUSBParameters(fthandle, 256, 0);
        if(status != FT_OK)
            printf("status not ok %d\n", status);

        // Reset the device
        status = FT_ResetDevice(fthandle);
        if(status != FT_OK)
            printf("status not ok %d\n", status);

        // Set the handshaking mode in the driver, for I2C chips this has no affect on the external I2C interface
        // since it does not have handshake lines but this enables internal handshake in the driver
        status = FT_SetFlowControl(fthandle, FT_FLOW_RTS_CTS, FT_STOP_BITS_1, FT_PARITY_NONE);
        if(status != FT_OK)
            printf("status not ok %d\n", status);

        // Set Timeouts to ensure a Read or Write will return if unable to be completed
        // Setting both read and write timeouts to 5 seconds
        status = FT_SetTimeouts(fthandle, 5000, 5000);
        if(status != FT_OK)
            printf("status not ok %d\n", status);

        // Set Latency Timer (keeping it at default of 16ms here)
        status = FT_SetLatencyTimer(fthandle, 16);
        if(status != FT_OK)
            printf("status not ok %d\n", status);

        // Now write some data to the chips buffer
        char data_out[12] = "HELLO WORLD";
        DWORD w_data_len = 12;
        DWORD data_written;

        status = FT_Write(fthandle, data_out, w_data_len, &data_written);
        if(status != FT_OK)
            printf("status not ok %d\n", status);
        else
            printf("12 Bytes Sent, waiting for bytes to come back\n");
        /**********************************************************************/
// The I2C Master should now be able to read these 12 bytes from the FT-X over I2C. This example expects the
// I2C Master to send the bytes back over I2C to the FT-X
        /**********************************************************************/

        // Now read the data which the I2C master has written to the FT-X
        char data_in[12];
        DWORD data_read;
        DWORD MyBytesReceived = 0;
        DWORD SoftwareTimeout = 0;

        // Wait for the FT-X to send our 12 bytes back to the PC
        while((MyBytesReceived <12) && (SoftwareTimeout < 500))
        {
            FT_GetQueueStatus(fthandle, &MyBytesReceived);
            Sleep(1);
            SoftwareTimeout ++;
        }

        // Check if the loop exited due to timing out or receiving 12 bytes
        if(SoftwareTimeout == 500)
        {
            printf("Timed out waiting for data\n");
        }
        else
        {
            // Now read the received bytes
            status = FT_Read(fthandle, data_in, MyBytesReceived, &data_read);
            if(status != FT_OK)
                printf("status not ok %d\n", status);
            else
                printf("data read %s\n", data_in);
        }
        // Close the device
        status = FT_Close(fthandle);
    }
    else
    {
        printf("No FTDI devices connected to the computer \n");
    }

    printf("Press Return To End Program");
    getchar();
    printf("closed \n");
    return 0;
}