예제 #1
0
/* Writing data 9 bit to USB */
quint16 ftdiChip::Bit9Write(QByteArray &buff, quint16 repet)
{
    FT_STATUS ftStatus;
    DWORD nmin,i=0,leng = buff.size();
    char *pdata = buff.data();

    while (i<repet)
            {
            ftStatus=FT_SetDataCharacteristics(hdUSB,FT_BITS_8,FT_STOP_BITS_1,FT_PARITY_MARK);    //  устанавливает FT_PARITY_MARK FT_PARITY_ODD
            if (ftStatus!=FT_OK){
                    emit signalStatusError(tr("USB write error status"),true);
                    return retErr;// error
                    }
            ftStatus=Write(pdata,1,&nmin);
            if (ftStatus==retErr){
                    return retErr;// error
                    }
            ftStatus=FT_SetDataCharacteristics(hdUSB,FT_BITS_8,FT_STOP_BITS_1,FT_PARITY_SPACE);   //  сбрасывает бит FT_PARITY_SPACE FT_PARITY_EVEN
            if (ftStatus!=FT_OK){
                    emit signalStatusError(tr("USB write error status"),true);
                    return retErr;// error
                    }
            pdata++;
            ftStatus=Write(pdata,(leng-1),&nmin);
            if (ftStatus==retErr){
                    return retErr;// error
                    }
            i++;
            }

    return retOk;
}
예제 #2
0
FT_STATUS OpenDevice(DeviceParams_t* device)
{
	FT_STATUS status;
	FT_SetVIDPID(device->vid, device->pid);
	status = FT_OpenEx((PVOID) device->serial, FT_OPEN_BY_SERIAL_NUMBER, &(device->handle));
	
	if(status == FT_OK)
	{
		status = FT_SetDataCharacteristics(device->handle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE);
	}

	if(status == FT_OK)
	{
		status = FT_SetBaudRate(device->handle, device->baud);
	}

	if(status == FT_OK)
	{
		// pthread_mutex_init(&device->rxEvent.eMutex, NULL);
    // pthread_cond_init(&device->rxEvent.eCondVar, NULL);
    	
    // status = FT_SetEventNotification(device->handle, FT_EVENT_RXCHAR, (PVOID) &(device->rxEvent));
    
		// pthread_create(&(device->thread), NULL, ReadData, (void*)device);
	}

	printf ("Open state [%x]\r\n", status);
	return status;
}
예제 #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;
}
예제 #4
0
/*
 * 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;
}
예제 #5
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);
}
예제 #6
0
bool CMmcUsbHndlBase::Configure()
{

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

	bool oResult = true;
	const BYTE LATENCY_TIMER(2);
    const DWORD INPUT_TRANSFER_SIZE(128);
    const DWORD OUTPUT_TRANSFER_SIZE(128);
    FT_STATUS ftStatus = FT_OK;

	//Data Characteristics:ByteSize, StopBit, Parity
    if(FT_OK != (ftStatus = FT_SetDataCharacteristics(m_Handle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE)))
    {
    	std::string errormsg = GetFtStatusDescription(ftStatus);
    	errormsg += ":FT_SetDataCharacteristics";
    	perror(errormsg.c_str());
        oResult = false;
    }

    //FlowControl: Dtr, Rts, Xon, Xoff
    if(FT_OK != (ftStatus = FT_SetFlowControl(m_Handle, FT_FLOW_NONE, 0, 0)))
    {
    	std::string errormsg = GetFtStatusDescription(ftStatus);
		errormsg += ":FT_SetFlowControl";
		perror(errormsg.c_str());
        oResult = false;
    }

    //LatencyTimer
    if(FT_OK != (ftStatus = FT_SetLatencyTimer(m_Handle, LATENCY_TIMER)))
    {
    	std::string errormsg = GetFtStatusDescription(ftStatus);
		errormsg += ":FT_SetLatencyTimer";
		perror(errormsg.c_str());
        oResult = false;
    }

    //TransferSize
    if(FT_OK != (ftStatus = FT_SetUSBParameters(m_Handle, INPUT_TRANSFER_SIZE, OUTPUT_TRANSFER_SIZE)))
    {
    	std::string errormsg = GetFtStatusDescription(ftStatus);
		errormsg += ":FT_SetUSBParameters";
		perror(errormsg.c_str());
        oResult = false;
    }

	return oResult;
}
예제 #7
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);
}
예제 #8
0
int closeSerialPorts() {
  int i;
  FT_STATUS	ftStatus;

  /* Cleanup */
  for(i = 0; i < foundDevices; i++) {
    if((ftStatus = FT_SetDataCharacteristics(ftHandle[i], FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE)) != FT_OK) {
      printf("Error FT_SetDataCharacteristics(%d) = %s\n", ftStatus, cBufLD[i]);
      break;
    }
    FT_Close(ftHandle[i]);
    printf("Closed device %s\n", cBufLD[i]);
  }
  return 0;
}
예제 #9
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;
}
예제 #10
0
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;
}
예제 #11
0
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;
}
예제 #12
0
/* SET PARAMETR USB*/
quint16 ftdiChip::setParametersUSB(quint64 Speed, quint8 DataBit, quint8 StopBit, quint8 Parity)
{
FT_STATUS ftStatus;

ftStatus=FT_SetBaudRate(hdUSB,Speed);
if (ftStatus){
    emit signalStatusError(tr("Error setting parameters <speed FTDI>"),true);
    return retErr;
    }
parameter.setSpeed(Speed);
ftStatus=FT_SetDataCharacteristics(hdUSB,(UCHAR)DataBit,(UCHAR)StopBit,(UCHAR)Parity);
if (ftStatus!=FT_OK){
    emit signalStatusError(tr("Error setting parameters <databit FTDI>"),true);
    return retErr;
    }
parameter.setDataBit(DataBit);
parameter.setStopBit(StopBit);
parameter.setParity(Parity);
emit signalStatusOk(tr("Parameters is successful!"));
return retOk;
}
예제 #13
0
파일: ftdimodule.cpp 프로젝트: gen1izh/cpp
bool FtdiDevices::setDataCharacteristics() {
  UCHAR WordLength;
  UCHAR StopBits;
  FT_STATUS ftStatus;
  WordLength = (UCHAR)(FT_INDEX_DATA_BITS_8 + FT_BITS_7);

  switch(FT_INDEX_STOP_BITS_1) {
  default:
    StopBits = FT_STOP_BITS_1;
    break;
  case 1:
    StopBits = FT_STOP_BITS_2;
    break;
  }

  ftStatus = FT_SetDataCharacteristics(m_ftHandleA, WordLength, StopBits,
    (UCHAR)FT_INDEX_PARITY_NONE);
  if (!FT_SUCCESS(ftStatus)) {
    return false;
  }
  return true;
}
예제 #14
0
파일: d2xx.c 프로젝트: GBert/openwrt-misc
void
serial_init (char *port, int baud)
{
  char *chipname;

  switch (board_type)
    {
    case BT_powermeter:
      chipname = "FT232R PowerMeter";
      break;
    case BT_powermeterproto:
      chipname = "FT232R PowerMeter";
      break;
    default:
      chipname = "FT232R - R8C";
      break;
    }

  Fail (FT_OpenEx (chipname, FT_OPEN_BY_DESCRIPTION, &handle));
  if (verbose > 2)
    printf("handle: 0x%x\n", (int)handle);
  atexit (serial_close);

  ProgramMode (1);
  Reset (1);
  /* >3 mSec reset pulse */
  usleep(3*1000);

  Reset (0);

  Fail (FT_SetBaudRate (handle, 9600));
  Fail (FT_SetDataCharacteristics (handle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE));
  FT_SetFlowControl (handle, FT_FLOW_NONE, 0, 0);

  /* 3 mSec delay to let board "wake up" after reset */
  usleep(3*1000);
}
	void main(void)
	{
		void Delay(void);                       // Delay function
		setvbuf(stdout,NULL,_IONBF,0);     		// Used to flush the IO buffers otherwise-
		setvbuf(stderr,NULL,_IONBF,0);     		//-eclipse terminal will behave strangely


		FT_HANDLE ft_handle;               		// Declaring the handle to the chip
		FT_STATUS ft_status;               		// Variable for storing status of the operation

		DWORD     BaudRate;                		// Variable to hold the baud rate
		char      TxByte;                       // Variable to hold the byte to be tx'ed
		DWORD     NoOfBytesWritten = 0;         // No of Bytes written to the port

		UCHAR     Mask;                         // for selecting which pins are input/output
		UCHAR     Mode;                         // Selects the mode of operation for the chip

		int i = 1;

		//-------------------------------  Opening the Connection to the chip -----------------------------------//

		ft_status = FT_Open(0,&ft_handle); 		// Opening a connection to the connected FT232RL chip

		if(ft_status == FT_OK)             		// Error checking for FT_Open()
			printf("Connection to the chip opened successfully\n");
		else
			printf("error in opening connection,Chip not connected or loose cable\n");

		//--------------------------------------------------------------------------------------------------------//




		//-------------------------------  Setting the baud rate of the chip -------------------------------------//

		BaudRate = 9600;                   		// Set BaudRate = 9600
		FT_SetBaudRate(ft_handle,BaudRate);		// Setting the baudrate for the chip for 9600bps

		if(ft_status == FT_OK)             		//Error checking for FT_SetBaudRate()
			printf("Baud rate set to %d\n",BaudRate);
		else
			printf("Error in setting baud rate\n");

		//--------------------------------------------------------------------------------------------------------//



		//--------------------------- Setting Data bits,Stop bits,Parity Bits ------------------------------------//

				ft_status = FT_SetDataCharacteristics( ft_handle, 		// Handle of the chip(FT232)
											           FT_BITS_8,       // No of Data bits = 8
											           FT_STOP_BITS_1,  // No of Stop Bits = 1
						                               FT_PARITY_NONE	// Parity = NONE
						                              );
				if(ft_status == FT_OK)
					printf("Format-> 8 DataBits,No Parity,1 Stop Bit (8N1)\n");
				else
					printf("Error in setting Data Format \n");


				//---------------- Setting Flow Control bits ------------------------------//

				ft_status = FT_SetFlowControl( ft_handle,		// Handle of the chip(FT232)
						                       FT_FLOW_NONE,    // No Flow control
						                       NULL,            // XON  = Null since no Flow control
						                       NULL             // XOFF = Null since no Flow control
						                      );

				if(ft_status == FT_OK)
				    printf("Flow Control = None \n");
				else
					printf("Error in setting Flow Control \n");






		//------------------------ Putting the Chip in CBUS bit Bang Mode ---------------------------------------//

		Mode = 0x20;                                     // Select Chip mode as CBUS Bit Bang

		//--------------------------------------------------------------------------------------------------------------------------------//
		//  Calculating the Mask Value in CBUS Bit Bang Mode                                                                              //
		//													                                                                              //
		//  +------------------------------------------------------+                                                                      //
		//  |<------------------- Mask(8bit) --------------------->|  Mask is an 8 bit Variable                                           //
		//  +-----------------------+------+-----------------------+                                                                      //
		//  |    Direction(4bits)   |      |   Data (4bits)        |  Upper Nibble controls the Direction,LowerNibble controls data bits  //
		//  +-----------------------+------+-----------------------+                                                                      //
		//  |  7  |  6  |  5  |  4  |      |  3  |  2  |  1  |  0  |                                                                      //
		//  +-----+-----+-----+-----+------+-----+-----+-----+-----+                                                                      //
		//  |CBUS3|CBUS2|CBUS1|CBUS0|      |CBUS3|CBUS2|CBUS1|CBUS0|  CBUS1 Connected to ~RE, CBUS2 Connected to DE                       //
		//  +-----+-----+-----+-----+------+-----+-----+-----+-----+                                                                      //
		//  |     |     |  __ |     |      |     |     | __  |     |                         __                                           //
		//  |  x  | DE  |  RE |  x  |      |  x  | DE  | RE  |  x  |  Data For TX,{ CBUS1 -> RE = High } and { CBUS2 -> DE = HIGH }       //
		//  +-----+-----+-----+-----+------+-----+-----+-----+-----+                                                                      //
		//  |  0  |  1  |  1  |  0  |      |  0  |  1  |  1  |  0  |  Direction For TX,{ CBUS1->RE = Output } and { CBUS2->DE = Output }  //
		//  +-----------------------+------+-----------------------+                                                                      //
		//  |                         0x66                         |                                                                      //
		//  +------------------------------------------------------+                                                                      //
		//                                                                                                                                //
        //--------------------------------------------------------------------------------------------------------------------------------//
 
 		Mask =  0x66;  //To activate the RE and DE signals for MAX485,
					   // ~RE -> High 
					   //  DE -> High
					   
		ft_status = FT_SetBitMode(ft_handle,Mask,Mode);  // Opening  Bit Bang Mode to put the chip in Transmit Mode

		if(ft_status == FT_OK)
		   	printf("Opening CBUS Bit Bang Mode successful\n");
		else
		   	printf("ERROR in Opening CBUS Bit Bang Mode\n");
		//--------------------------------------------------------------------------------------------------------//
	
		while(1)
		{
			//-------------------------------  Writing a byte to serial port -----------------------------------------//

			TxByte = 'A';
			ft_status = FT_Write( ft_handle,         // Handle to the chip
								  &TxByte,           // Variable Containing the byte to be Txed
							      sizeof(TxByte),    // sizeof(TxByte) = char
							      &NoOfBytesWritten  // No of Bytes written to the port
							     );

		    if(ft_status == FT_OK)             		 // Error checking for FT_Writee()
		       printf("%c written to the serial port at %d bps - [%d]\n",TxByte,BaudRate,i);
		    else
			   printf("Error in writing to port\n");
			 
			 i++;

		     //--------------------------------------------------------------------------------------------------------//
			 Delay();
		}


		FT_Close(ft_handle);                      // Closing the handle to the chip
		getch();

	}
예제 #16
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
}
예제 #17
0
int nifalcon_load_firmware(falcon_device* dev, const char* firmware_filename)
{
	unsigned long bytes_written;
	unsigned char check_msg_1[3] = {0x0a, 0x43, 0x0d};
	unsigned char check_msg_2[1] = "A";
	unsigned char send_buf[128], receive_buf[128];
	FILE* firmware_file;
	
	if(!dev->is_open) nifalcon_error_return(NIFALCON_DEVICE_NOT_FOUND_ERROR, "tried load firmware to an unopened device");

	if((dev->falcon_status_code = FT_ResetDevice(dev->falcon)) != FT_OK) return -dev->falcon_status_code;

	//Set to:
	// 9600 baud
	// 8n1
	// No Flow Control
	// RTS Low
	// DTR High	
	if((dev->falcon_status_code = FT_SetBaudRate(dev->falcon, 9600)) != FT_OK) return -dev->falcon_status_code;
	if((dev->falcon_status_code = FT_SetDataCharacteristics(dev->falcon, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE)) != FT_OK) return -dev->falcon_status_code;
	if((dev->falcon_status_code = FT_SetFlowControl(dev->falcon, FT_FLOW_NONE, 0, 0)) != FT_OK) return -dev->falcon_status_code;
	if((dev->falcon_status_code = FT_ClrRts(dev->falcon)) != FT_OK) return -dev->falcon_status_code;
	if((dev->falcon_status_code = FT_ClrDtr(dev->falcon)) != FT_OK) return -dev->falcon_status_code;
	if((dev->falcon_status_code = FT_SetDtr(dev->falcon)) != FT_OK) return -dev->falcon_status_code;

	//Send 3 bytes: 0x0a 0x43 0x0d
	if((dev->falcon_status_code = nifalcon_write(dev, check_msg_1, 3)) < 3) return -dev->falcon_status_code;
	
	//Expect 5 bytes back
	if((dev->falcon_status_code = nifalcon_read(dev, receive_buf, 5, 1000)) < 5) return -dev->falcon_status_code;	

	//Set to:
	// DTR Low
	// 140000 baud (0x15 clock ticks per signal)
	if((dev->falcon_status_code = FT_ClrDtr(dev->falcon)) != FT_OK) return -dev->falcon_status_code;
	if((dev->falcon_status_code = FT_SetBaudRate(dev->falcon, 140000)) != FT_OK) return -dev->falcon_status_code;

	//Send "A" character
	if((dev->falcon_status_code = nifalcon_write(dev, check_msg_2, 1)) < 0) return -dev->falcon_status_code;

	//Expect back 2 bytes:
	// 0x13 0x41 
	if((dev->falcon_status_code = nifalcon_read(dev, receive_buf, 2, 1000)) < 0) return -dev->falcon_status_code;	

	firmware_file = fopen(firmware_filename, "rb");

	if(!firmware_file)
	{
		nifalcon_error_return(NIFALCON_FIRMWARE_NOT_FOUND_ERROR, "cannot find falcon firmware file");
	}
	while(!feof(firmware_file))
	{
		int firmware_bytes_read;
		int i;
		firmware_bytes_read = fread(send_buf, 1, 128, firmware_file);
		if((dev->falcon_status_code = nifalcon_write(dev, send_buf, firmware_bytes_read)) < 0) return dev->falcon_status_code;
		if((dev->falcon_status_code = nifalcon_read(dev, receive_buf, firmware_bytes_read, 1000)) < 0) return dev->falcon_status_code;
			
		if(firmware_bytes_read < 128) break;
	}
	fclose(firmware_file);

	if((dev->falcon_status_code = FT_SetBaudRate(dev->falcon, 1456312)) != FT_OK) return -dev->falcon_status_code;
	return FT_OK;
}
예제 #18
0
bool FTDIDMXDevice::open()
{
	// Change QString to char* (not const char* note)

	char *serial;
	QByteArray a = m_path.toLatin1();

	serial = (char*)malloc(sizeof(char) * (a.count() + 1));
	memcpy(serial, a.constData(), a.count());
	serial[a.count()] = 0;

#ifndef WIN32
	// Windows users cannot dynamiccaly set VID/PID of harward
	if (FT_SetVIDPID(m_vid, m_pid) == FT_OK && 
	    FT_OpenEx(serial, FT_OPEN_BY_SERIAL_NUMBER, &m_handle) == FT_OK)
	{
#else
	if (FT_OpenEx(serial, FT_OPEN_BY_SERIAL_NUMBER, &m_handle) == FT_OK)
	{
#endif
		free(serial);
		if (!FT_SUCCESS(FT_ResetDevice(m_handle)))
		{
			qWarning() << "Unable to reset FTDI device" << m_path;
			return false;
		}

		// Set the baud rate 12 will give us 250Kbits
		if (!FT_SUCCESS(FT_SetDivisor(m_handle, 12)))
		{
			qWarning() << "Unable to set divisor on FTDI device"
				   << m_path;
			return false;
		}

		// Set the data characteristics
		if (!FT_SUCCESS(FT_SetDataCharacteristics(m_handle,
							  FT_BITS_8,
							  FT_STOP_BITS_2,
							  FT_PARITY_NONE)))
		{
			qWarning() << "Unable to set data characteristics on"
				   << "FTDI device" << m_path;
			return false;
		}

		// Set flow control
	 	if (!FT_SUCCESS(FT_SetFlowControl(m_handle, FT_FLOW_NONE, 0, 0)))
	 	{
			qWarning() << "Unable to set flow control on"
				   << "FTDI device" << m_path;
			return false;
		}

		// set RS485 for sendin
		FT_ClrRts(m_handle);

		// Clear TX RX buffers
		FT_Purge(m_handle,FT_PURGE_TX | FT_PURGE_RX);

		m_threadRunning = true;
		start(QThread::TimeCriticalPriority);

		return true;
	}
	else
	{
		qWarning() << "Unable to open FTDIDMX"
			   << m_output << ":" << serial;
		free(serial);
		return false;
	}
}

bool FTDIDMXDevice::close()
{
	// Kill thread
	m_threadRunning = false;
	wait(500);

	FT_Close(m_handle);
	return true;
}
예제 #19
0
파일: main.c 프로젝트: scott5490/AIS600
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;
}
static void FTClassicPort_setDataCharacteristics(FTClassicPort *self,UCHAR WordLength,UCHAR StopBits,UCHAR Parity){
	self->status = FT_SetDataCharacteristics(self->handle, WordLength,
		StopBits, Parity);
}
예제 #21
0
int main(int argc, char *argv[])
{
    int             retCode = -1; // Assume failure
    int             f = 0;
    DWORD           driverVersion = 0;
    FT_STATUS       ftStatus = FT_OK;
    FT_HANDLE       ftHandle = NULL;
    int             portNum = 0; // First device found
    size_t          bufferSize = 64 * 1024;
    DWORD           bytesToWrite;
    DWORD           bytesWritten = 0;
    DWORD           bytesReceived = 0;
    DWORD           bytesRead = 0;
    struct timeval  startTime;
    int             journeyDuration;
    unsigned char  *writeBuffer = NULL;
    unsigned char  *readBuffer = NULL;
    int             queueChecks = 0;
    ULONG           rates[] = {300, 600, 1200, 2400, 4800, 9600,
                               19200, 38400, 57600, 115200, 
                               230400, 460800, 576000, 921600,
                               1500000, 2000000, 3000000};
                    // TODO: detect high-speed device and use 8240000

    UNUSED_PARAMETER(argc);
    UNUSED_PARAMETER(argv);
    
    // Make printfs immediate (no buffer)
    setvbuf(stdout, NULL, _IONBF, 0);

    writeBuffer = (unsigned char *)malloc((size_t)bufferSize);
    if (writeBuffer == NULL)
        goto exit;

    // Fill write buffer with consecutive values
    for (f = 0; f < (int)bufferSize; f++) 
    {
        writeBuffer[f] = (unsigned char)f + 64;
    }
    
    printf("Opening FTDI device %d.\n", portNum);
    
    ftStatus = FT_Open(portNum, &ftHandle);
    if (ftStatus != FT_OK) 
    {
        printf("FT_Open(%d) failed, with error %d.\n", portNum, (int)ftStatus);
        printf("On Linux, lsmod can 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_GetDriverVersion(ftHandle, &driverVersion);
	if (ftStatus != FT_OK)
    {
		printf("Failure.  FT_GetDriverVersion returned %d.\n",
               (int)ftStatus);
        goto exit;
    }

    printf("Using D2XX version %08x\n", driverVersion);

	ftStatus = FT_ResetDevice(ftHandle);
    if (ftStatus != FT_OK) 
    {
        printf("Failure.  FT_ResetDevice 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;
    }

    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;
    }
    
    for (f = 0; f < (int)ARRAY_SIZE(rates); f++)
    {
        ftStatus = FT_SetBaudRate(ftHandle, rates[f]);
        if (ftStatus != FT_OK) 
        {
            printf("Failure.  FT_SetBaudRate(%d) returned %d.\n", 
                   (int)rates[f],
                   (int)ftStatus);
            goto exit;
        }
        
        // Assert Request-To-Send to prepare receiver
        ftStatus = FT_SetRts(ftHandle);
        if (ftStatus != FT_OK) 
        {
            printf("Failure.  FT_SetRts returned %d.\n", (int)ftStatus);
            goto exit;
        }

        if (rates[f] < 57600)
        {
            // Keep test duration reasonable by transferring fewer 
            // bytes at low baud rates.
            bytesToWrite = rates[f] / 4;
        }
        else
        {
            bytesToWrite = bufferSize;
        }

        printf("\nBaud rate %d.  Writing %d bytes to loopback device...\n", 
               (int)rates[f],
               (int)bytesToWrite);

        ftStatus = FT_Write(ftHandle, 
                            writeBuffer,
                            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;
        }

        printf("%d bytes written.\n", (int)bytesWritten);

        // Keep checking queue until D2XX has received all the bytes we wrote.
        // Estimate total time to write and read, so we can time-out.
        // Each byte has 8 data bits plus a stop bit and perhaps a 1-bit gap.
        journeyDuration = bytesWritten * (8 + 1 + 1) / (int)rates[f];
        journeyDuration += 1;  // Round up
        journeyDuration *= 2;  // It's a return journey
        printf("Estimate %d seconds remain.\n", journeyDuration);
        
        gettimeofday(&startTime, NULL);
        
        for (bytesReceived = 0, queueChecks = 0; 
             bytesReceived < bytesWritten; 
             queueChecks++)
        {
            // Periodically check for time-out 
            if (queueChecks % 32 == 0)
            {
                struct timeval now;
                struct timeval elapsed;
                
                gettimeofday(&now, NULL);
                timersub(&now, &startTime, &elapsed);

                if (elapsed.tv_sec > (long int)journeyDuration)
                {
                    // We've waited too long.  Give up.
                    printf("\nTimed out after %ld seconds\n", elapsed.tv_sec);
                    break;
                }
                
                // Display number of bytes D2XX has received
                printf("%s%d", 
                       queueChecks == 0 ? "Number of bytes in D2XX receive-queue: " : ", ",
                       (int)bytesReceived);
            }

            ftStatus = FT_GetQueueStatus(ftHandle, &bytesReceived);
            if (ftStatus != FT_OK)
            {
                printf("\nFailure.  FT_GetQueueStatus returned %d.\n",
                       (int)ftStatus);
                goto exit;
            }
        }

        printf("\nGot %d (of %d) bytes.\n", (int)bytesReceived, (int)bytesWritten);

        // Even if D2XX has the wrong number of bytes, create our
        // own buffer so we can read and display them.
        free(readBuffer); // Free previous iteration's buffer.
		readBuffer = (unsigned char *)calloc(bytesReceived, sizeof(unsigned char));
        if (readBuffer == NULL)
        {
            printf("Failed to allocate %d bytes.\n", bytesReceived);
            goto exit;
        }

        // Then copy D2XX's buffer to ours.
        ftStatus = FT_Read(ftHandle, readBuffer, bytesReceived, &bytesRead);
        if (ftStatus != FT_OK)
        {
            printf("Failure.  FT_Read returned %d.\n", (int)ftStatus);
            goto exit;
        }

        if (bytesRead != bytesReceived)
        {
            printf("Failure.  FT_Read only read %d (of %d) bytes.\n",
                   (int)bytesRead,
                   (int)bytesReceived);
            goto exit;
        }
        
        if (0 != memcmp(writeBuffer, readBuffer, bytesRead))
        {
            printf("Failure.  Read-buffer does not match write-buffer.\n");
            printf("Write buffer:\n");
            dumpBuffer(writeBuffer, bytesReceived);
            printf("Read buffer:\n");
            dumpBuffer(readBuffer, bytesReceived);
            goto exit;
        }

        // Fail if D2XX's queue lacked (or had surplus) bytes.
        if (bytesReceived != bytesWritten)
        {
            printf("Failure.  D2XX received %d bytes but we expected %d.\n",
                   (int)bytesReceived,
                   (int)bytesWritten);
            dumpBuffer(readBuffer, bytesReceived);
            goto exit;
        }

        // Check that queue hasn't gathered any additional unexpected bytes
        bytesReceived = 4242; // deliberately junk
        ftStatus = FT_GetQueueStatus(ftHandle, &bytesReceived);
        if (ftStatus != FT_OK)
        {
            printf("Failure.  FT_GetQueueStatus returned %d.\n",
                   (int)ftStatus);
            goto exit;
        }

        if (bytesReceived != 0)
        {
            printf("Failure.  %d bytes in input queue -- expected none.\n",
                   (int)bytesReceived);
            goto exit;
        }
    }

    // Success
    printf("\nTest PASSED.\n");
    retCode = 0;

exit:
    free(readBuffer);
    free(writeBuffer);

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

    return retCode;
}
	void main(void)
	{
		FT_HANDLE ft_handle;               		// Declaring the handle to the chip
		FT_STATUS ft_status;               		// Variable for storing status of the operation
		DWORD     BaudRate;                		// Variable to hold the baud rate
		char      TxByte;                       // Variable to hold the byte to be tx'ed
		DWORD     NoOfBytesWritten = 0;         // No of Bytes written to the port



		//-------------------------------  Opening the Connection to the chip -----------------------------------//

		ft_status = FT_Open(0,&ft_handle); 		// Opening a connection to the connected FT232RL chip

		if(ft_status == FT_OK)             		// Error checking for FT_Open()
			printf("\n\n\tConnection to the chip opened successfully\n");
		else
			printf("\terror in opening connection,Chip not connected or loose cable\n");

		//--------------------------------------------------------------------------------------------------------//


		
		//-------------------------------  Setting the baud rate of the chip -------------------------------------//

		BaudRate = 9600;                   		// Set BaudRate = 9600
		FT_SetBaudRate(ft_handle,BaudRate);		// Setting the baudrate for the chip for 9600bps

		if(ft_status == FT_OK)             		//Error checking for FT_SetBaudRate()
			printf("\tBaud rate set to %d\n",BaudRate);
		else
			printf("\tError in setting baud rate\n");

		
		
		//--------------------------- Setting Data bits,Stop bits,Parity Bits ------------------------------------//

		ft_status = FT_SetDataCharacteristics( ft_handle, 		// Handle of the chip(FT232)
											   FT_BITS_8,       // No of Data bits = 8
											   FT_STOP_BITS_1,  // No of Stop Bits = 1
						                       FT_PARITY_NONE	// Parity = NONE
						                      );
		if(ft_status == FT_OK)
			printf("\tFormat-> 8 DataBits,No Parity,1 Stop Bit (8N1)\n");
		else
			printf("\tError in setting Data Format \n");


		//--------------------------------- Setting Flow Control bits -------------------------------------------//

		ft_status = FT_SetFlowControl( ft_handle,		// Handle of the chip(FT232)
				                       FT_FLOW_NONE,    // No Flow control
				                       NULL,            // XON  = Null since no Flow control
				                       NULL             // XOFF = Null since no Flow control
				                      );

		if(ft_status == FT_OK)
			printf("\tFlow Control = None \n");
		else
			printf("\tError in setting Flow Control \n");


		//-------------------------------  Writing a byte to serial port -----------------------------------------//

		TxByte = 'A';
		ft_status = FT_Write( ft_handle,         // Handle to the chip
							  &TxByte,           // Variable Containing the byte to be Txed
							  sizeof(TxByte),    // sizeof(TxByte) = char
							  &NoOfBytesWritten  // No of Bytes written to the port
							 );

		if(ft_status == FT_OK)             		 // Error checking for FT_Writee()
		    printf("\t'%c' written to the serial port at %d bps\n",TxByte,BaudRate);
		else
			printf("\tError in writing to port\n");

		//--------------------------------------------------------------------------------------------------------//


		FT_Close(ft_handle);                      // Closing the handle to the chip
		
		getch();
	}
예제 #23
0
파일: fld_ctrl.c 프로젝트: avasilje/btcar
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;
}