// 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; }
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; }
/** * TODO: Необходимо отрефакторить код */ bool FtdiDevices::reset() { FT_STATUS ftStatus; ftStatus = FT_ResetDevice(m_ftHandleA); if (!FT_SUCCESS(ftStatus)) { return false; } return true; }
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); }
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; }
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; }
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; }
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 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; }
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; }
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; }
int main(int argc, char *argv[]) { static const struct option long_opts[] = { {"prompt", no_argument, NULL, 'p'}, {"verbose", no_argument, NULL, 'v'}, {"help", no_argument, NULL, 'h'}, {NULL, no_argument, NULL, 0} }; opterr = 0; int c; int option_index = 0; while ((c = getopt_long(argc, argv, "vph", long_opts, &option_index)) != -1) switch (c) { case 'v': verbose++; break; case 'p': dont_prompt++; break; case 'h': print_usage(); return EXIT_SUCCESS; case '?': fprintf(stderr, "Unknown option `-%c'.\n", optopt); return EXIT_FAILURE; default: abort(); } DWORD num_devs; DWORD VID, PID; int iport = 0; /* See how many devices are plugged in, fail if greater than 1 */ if (verbose) printf("Creating device info list\n"); ft_status = FT_CreateDeviceInfoList(&num_devs); if (ft_status != FT_OK){ fprintf(stderr,"ERROR : Failed to create device info list, ft_status = %d\n",ft_status); return EXIT_FAILURE; } if (verbose) printf("Making sure only one FTDI device is plugged in\n"); /* Check that there aren't more than 1 device plugged in */ if (num_devs > 1){ fprintf(stderr,"ERROR : More than one FTDI device plugged in\n"); return EXIT_FAILURE; } /* Get VID/PID from FTDI device */ if (verbose) printf("Getting VID/PID from device\n"); ft_status = FT_GetVIDPID(&VID,&PID); if (ft_status != FT_OK){ fprintf(stderr,"ERROR : Failed to get VID and PID from FTDI device, ft_status = %d\n",ft_status); return EXIT_FAILURE; } if (verbose) printf(" VID = %04x, PID = %04x\n",VID,PID); /* Set the VID/PID found */ if (verbose) printf("Setting VID/PID\n"); ft_status = FT_SetVIDPID(VID,PID); if (ft_status != FT_OK){ fprintf(stderr,"ERROR : Failed to set VID and PID, ft_status = %d\n",ft_status); return EXIT_FAILURE; } /* Get info about the device and print to user */ //FT_GetDeviceInfoDetail seems to not work very reliably //DWORD lpdw_flags; //DWORD lpdw_type; //DWORD lpdw_id; //char pc_serial_number[16]; //char pc_description[64]; //ft_status = FT_GetDeviceInfoDetail(0,&lpdw_flags,&lpdw_type,&lpdw_id,NULL,pc_serial_number,pc_description,&ft_handle); //if (ft_status != FT_OK){ // fprintf(stderr,"ERROR : Failed to get device info, ft_status = %d\n",ft_status); // return EXIT_FAILURE; //} //if (verbose || !dont_prompt){ // printf("Device Information : \n"); // printf(" Description : %s\n", pc_description); // printf(" Serial Number : %s\n", pc_serial_number); // printf(" Flags : 0x%x\n", lpdw_flags); // printf(" Type : 0x%x\n", lpdw_type); // printf(" ID : 0x%x\n", lpdw_id); //} /* Ask user if this is the correct device */ if (!dont_prompt) { char correct_device; printf("Is this the correct device? (y/n) : "); scanf("%c",&correct_device); while ((correct_device != 'y') && (correct_device != 'n')) { printf("\rPlease enter y or n"); scanf("%c",&correct_device); } if (correct_device == 'n'){ printf("Exiting, since this is not the device we want to program\n"); return EXIT_SUCCESS; } } /* Open the device */ if (verbose) printf("Attempting to open device using read VID/PID..."); ft_status = FT_Open(iport, &ft_handle); /* If that didn't work, try some other likely VID/PID combos */ /* Try 0403:6014 */ if (ft_status != FT_OK){ if (verbose) printf("FAILED\nTrying VID=0x0403, PID=0x6014..."); ft_status = FT_SetVIDPID(0x0403,0x6014); if (ft_status != FT_OK){ fprintf(stderr,"ERROR : Failed to set VID and PID, ft_status = %d\n",ft_status); return EXIT_FAILURE; } ft_status = FT_Open(iport, &ft_handle); } /* Try 0403:8398 */ if (ft_status != FT_OK){ if (verbose) printf("FAILED\nTrying VID=0x0403, PID=0x8398..."); ft_status = FT_SetVIDPID(0x0403,0x8398); if (ft_status != FT_OK){ fprintf(stderr,"ERROR : Failed to set VID and PID, ft_status = %d\n",ft_status); return EXIT_FAILURE; } ft_status = FT_Open(iport, &ft_handle); } /* Exit program if we still haven't opened the device */ if (ft_status != FT_OK){ if (verbose) printf("FAILED\n"); fprintf(stderr,"ERROR : Failed to open device : ft_status = %d\nHave you tried (sudo rmmod ftdi_sio)?\n",ft_status); return EXIT_FAILURE; } if (verbose) printf("SUCCESS\n"); /* Erase the EEPROM */ ft_status = FT_EraseEE(ft_handle); if(ft_status != FT_OK) { fprintf(stderr, "ERROR: Device EEPROM could not be erased : ft_status = %d\n", ft_status); return EXIT_FAILURE; } if (verbose) printf("Erased device's EEPROM\n"); /* Assign appropriate values to eeprom data */ eeprom_data.Signature1 = 0x00000000; eeprom_data.Signature2 = 0xffffffff; eeprom_data.Version = 5; /* 5=FT232H */ eeprom_data.VendorId = USB_CUSTOM_VID; eeprom_data.ProductId = USB_CUSTOM_PID; eeprom_data.Manufacturer = "FTDI"; eeprom_data.ManufacturerId = "FT"; eeprom_data.Description = "Piksi Passthrough"; eeprom_data.IsFifoH = 1; /* needed for FIFO samples passthrough */ /* Program device EEPROM */ ft_status = FT_EE_Program(ft_handle, &eeprom_data); if (ft_status != FT_OK) { fprintf(stderr,"ERROR : Failed to program device EEPROM : ft_status = %d\n",ft_status); return EXIT_FAILURE; } if (verbose) printf("Programmed device's EEPROM\n"); /* Reset the device */ ft_status = FT_ResetDevice(ft_handle); if (ft_status != FT_OK) { fprintf(stderr, "ERROR: Device could not be reset : ft_status = %d\n", ft_status); return EXIT_FAILURE; } if (verbose) printf("Reset device\n"); /* Close the device */ if (verbose) printf("Closing device\n"); FT_Close(ft_handle); if(ft_status != FT_OK) { fprintf(stderr,"ERROR : Failed to close device : ft_status = %d\n",ft_status); return EXIT_FAILURE; } printf("Re-configuring for FIFO mode successful, please unplug and replug your device now\n"); return EXIT_SUCCESS; }
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; }
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; }
void image_transfer(FILE *fp, ftdi_context_t *c, u8 dump, u8 type, u32 addr, u32 size) { u32 ram_addr = addr; int bytes_left = size; int bytes_done = 0; int bytes_do; int trunc_flag = 0; int i; int chunk = 0; struct timespec time_start; struct timespec time_stop; double time_duration; time_t time_diff_seconds; long time_diff_nanoseconds; dev_cmd_resp_t r; // make sure handle is valid if(!c->handle) die(err[DEV_ERR_NULL_HANDLE], __FUNCTION__); // decide a better, more optimized chunk size if(size > 16 * 1024 * 1024) chunk = 32; else if( size > 2 * 1024 * 1024) chunk = 16; else chunk = 4; // convert to megabytes chunk *= 128 * 1024; if(c->verbose) _printf(info[INFO_CHUNK], CHUNK_SIZE); if(c->verbose) _printf(info[INFO_OPT_CHUNK], chunk); // get initial time count // QueryPerformanceFrequency(&time_freq); // QueryPerformanceCounter(&time_start); clock_gettime(CLOCK_MONOTONIC, &time_start); while(1){ if(bytes_left >= chunk) bytes_do = chunk; else bytes_do = bytes_left; if(bytes_do % 512 != 0) { trunc_flag = 1; bytes_do -= (bytes_do % 512); } if(bytes_do <= 0) break; for(i = 0; i < 2; i++){ if(i == 1) { printf("\n"); _printf("Retrying\n"); FT_ResetPort(c->handle); FT_ResetDevice(c->handle); _printf("Retrying FT_ResetDevice() success\n"); // set synchronous FIFO mode //FT_SetBitMode(c->handle, 0xff, 0x40); _printf("Retrying FT_SetBitMode() success\n"); FT_Purge(c->handle, FT_PURGE_RX | FT_PURGE_TX); _printf("Retrying FT_Purge() success\n"); } device_sendcmd(c, &r, dump ? DEV_CMD_DUMPRAM : DEV_CMD_LOADRAM, 2, 0, 1, ram_addr, (bytes_do & 0xffffff) | type << 24); if(dump){ c->status = FT_Read(c->handle, buffer, bytes_do, &c->bytes_written); fwrite(buffer, bytes_do, 1, fp); }else{ fread(buffer, bytes_do, 1, fp); c->status = FT_Write(c->handle, buffer, bytes_do, &c->bytes_written); } if(c->bytes_written) break; } // check for a timeout if(c->bytes_written == 0) die(err[DEV_ERR_TIMED_OUT], __FUNCTION__); // dump success response c->status = FT_Read(c->handle, buffer, 4, &c->bytes_read); bytes_left -= bytes_do; bytes_done += bytes_do; ram_addr += bytes_do; // progress bar prog_draw(bytes_done, size); c->status = FT_GetStatus(c->handle, &c->bytes_read, &c->bytes_written, &c->event_status); } // stop the timer // QueryPerformanceCounter(&time_stop); clock_gettime(CLOCK_MONOTONIC, &time_stop); // get the difference of the timer time_diff_seconds = time_stop.tv_sec - time_start.tv_sec; time_diff_nanoseconds = time_stop.tv_nsec - time_start.tv_nsec; time_duration = (double)time_diff_seconds + (double)(time_diff_nanoseconds/1000000000.0f); // erase progress bar prog_erase(); if(c->verbose && trunc_flag) _printf(info[INFO_TRUNCATED]); if(c->verbose) _printf(info[INFO_COMPLETED_TIME], time_duration, (float)size/1048576.0f/(float)time_duration); }
static void FTClassicPort_resetDevice(FTClassicPort *self){ self->status = FT_ResetDevice(self->handle); }
int main(int argc, char *argv[]) { static const struct option long_opts[] = { {"verbose", no_argument, NULL, 'v'}, {"help", no_argument, NULL, 'h'}, {"id", required_argument, NULL, 'i'}, {NULL, no_argument, NULL, 0} }; opterr = 0; int c; int option_index = 0; while ((c = getopt_long(argc, argv, "vhi:", long_opts, &option_index)) != -1) switch (c) { case 'v': verbose++; break; case 'h': print_usage(); return EXIT_SUCCESS; case 'i': { pid = parse_pid(optarg); if (!pid) { fprintf(stderr, "Invalid ID argument.\n"); return EXIT_FAILURE; } break; } case '?': if (optopt == 'i') fprintf(stderr, "ID argument requires an argument.\n"); else fprintf(stderr, "Unknown option `-%c'.\n", optopt); return EXIT_FAILURE; default: abort(); } int iport = 0; /* Try to open device using input PID, or our custom PID if no input. */ if (verbose) printf("Trying to open with VID=0x%04x, PID=0x%04x...",USB_CUSTOM_VID,pid); ft_status = FT_SetVIDPID(USB_CUSTOM_VID, pid); if (ft_status != FT_OK){ fprintf(stderr,"ERROR : Failed to set VID and PID, ft_status = %d\n",ft_status); return EXIT_FAILURE; } ft_status = FT_Open(iport, &ft_handle); /* Exit program if we haven't opened the device. */ if (ft_status != FT_OK){ if (verbose) printf("FAILED\n"); fprintf(stderr,"ERROR : Failed to open device : ft_status = %d\n",ft_status); return EXIT_FAILURE; } if (verbose) printf("SUCCESS\n"); /* Erase the EEPROM to set the device to UART mode. */ if (verbose) printf("Erasing device EEPROM\n"); ft_status = FT_EraseEE(ft_handle); if(ft_status != FT_OK) { fprintf(stderr, "ERROR: Device EEPROM could not be erased : ft_status = %d\n", ft_status); return EXIT_FAILURE; } /* Reset the device. */ if (verbose) printf("Resetting device\n"); ft_status = FT_ResetDevice(ft_handle); if(ft_status != FT_OK) { fprintf(stderr, "ERROR: Device could not be reset : ft_status = %d\n", ft_status); return EXIT_FAILURE; } /* Close the device. */ if (verbose) printf("Closing device\n"); FT_Close(ft_handle); if(ft_status != FT_OK) { fprintf(stderr,"ERROR : Failed to close device : ft_status = %d\n",ft_status); return EXIT_FAILURE; } if (verbose) printf("Re-configuring for UART mode successful, please unplug and replug your device now\n"); return EXIT_SUCCESS; }
bool CApoxObj::open( const char *szFileName, unsigned long flags ) { const char *p; unsigned long busspeed = 125; m_emergencyInfo = 0; char szDrvParams[ MAX_PATH ]; m_initFlag = flags; m_RxMsgState = USB_IDLE; // save parameter string and conbert to upper case strncpy( szDrvParams, szFileName, MAX_PATH ); _strupr( szDrvParams ); // Initiate statistics m_stat.cntReceiveData = 0; m_stat.cntReceiveFrames = 0; m_stat.cntTransmitData = 0; m_stat.cntTransmitFrames = 0; m_stat.cntBusOff = 0; m_stat.cntBusWarnings = 0; m_stat.cntOverruns = 0; // if open we have noting to do if ( m_bRun ) return true; // serial p = strtok( szDrvParams, ";" ); if ( NULL != p ) { strcpy( m_SerialNumber, p ); } // Bus-Speed p = strtok( NULL, ";" ); if ( NULL != p ) { if ( ( NULL != strstr( p, "0x" ) ) || ( NULL != strstr( p, "0X" ) ) ) { sscanf( p + 2, "%x", &busspeed ); } else { busspeed = atol( p ); } } // Handle busspeed uint8_t nSpeed = CAN_BAUD_1000; switch ( busspeed ) { case 125: nSpeed = CAN_BAUD_125; break; case 250: nSpeed = CAN_BAUD_250; break; case 500: nSpeed = CAN_BAUD_500; break; case 1000: nSpeed = CAN_BAUD_1000; break; default: nSpeed = CAN_BAUD_125; break; } FT_STATUS ftStatus; ftStatus = FT_OpenEx( (void *)m_SerialNumber, FT_OPEN_BY_SERIAL_NUMBER, &m_ftHandle ); if ( !FT_SUCCESS( ftStatus ) ) return false; ftStatus = FT_ResetDevice( m_ftHandle ); ftStatus = FT_Purge( m_ftHandle, FT_PURGE_RX | FT_PURGE_TX ); ftStatus = FT_SetTimeouts(m_ftHandle, 378, 128); ftStatus = FT_SetUSBParameters ( m_ftHandle, 2048, 2048 ); ftStatus = FT_SetLatencyTimer( m_ftHandle, 3 ); // Run run run ..... m_bRun = true; #ifdef WIN32 // Start write thread DWORD threadId; if ( NULL == ( m_hTreadTransmit = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE) workThreadTransmit, this, 0, &threadId ) ) ) { // Failure close(); return false; } // Start read thread if ( NULL == ( m_hTreadReceive = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE) workThreadReceive, this, 0, &threadId ) ) ) { // Failure close(); return false; } // Release the mutex UNLOCK_MUTEX( m_apoxMutex ); UNLOCK_MUTEX( m_receiveMutex ); UNLOCK_MUTEX( m_transmitMutex ); UNLOCK_MUTEX( m_responseMutex ); #else // LINUX pthread_attr_t thread_attr; pthread_attr_init( &thread_attr ); // Create the log write thread. if ( pthread_create( &m_threadId, &thread_attr, workThreadTransmit, this ) ) { syslog( LOG_CRIT, "canallogger: Unable to create apoxdrv write thread."); rv = false; fclose( m_flog ); } // Create the log write thread. if ( pthread_create( &m_threadId, &thread_attr, workThreadReceive, this ) ) { syslog( LOG_CRIT, "canallogger: Unable to create apoxdrv receive thread."); rv = false; fclose( m_flog ); } // We are open m_bOpen = true; // Release the mutex pthread_mutex_unlock( &m_apoxMutex ); #endif // Switch to main mode if in boot mode if ( RUNMODE_BOOT == getAdapterRunMode() ) { setAdapterRunMode( RUNMODE_MAIN ); } // Set baudrate setBaudrate( nSpeed ); // Set initial filter/mask switch( m_initFlag & 0x03 ) { case 0: case 3: m_filtermask.rx_buff1_ext = 0; m_filtermask.rx_buff2_ext = 1; break; case 1: m_filtermask.rx_buff1_ext = 0; m_filtermask.rx_buff2_ext = 0; break; case 2: m_filtermask.rx_buff1_ext = 1; m_filtermask.rx_buff2_ext = 1; break; } m_filtermask.RXM0 = 0; m_filtermask.RXM1 = 0; m_filtermask.RXF0 = 0; m_filtermask.RXF1 = 0; m_filtermask.RXF2 = 0; m_filtermask.RXF3 = 0; m_filtermask.RXF4 = 0; m_filtermask.RXF5 = 0; setAdapterFilterMask( &m_filtermask ); // Set transmission mode short trmode = ( (short)( m_initFlag & 0x0c ) >> 2 ); if ( 0 == trmode ) trmode = TRMODE_NORMAL; setTransmissionMode( trmode ); return true; }