1 /***************************************************************************
5 copyright : (C) 2003-2008 by Intra2net AG
6 email : opensource@intra2net.com
7 ***************************************************************************/
9 /***************************************************************************
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU Lesser General Public License *
13 * version 2.1 as published by the Free Software Foundation; *
15 ***************************************************************************/
18 \mainpage libftdi API documentation
20 Library to talk to FTDI chips. You find the latest versions of libftdi at
21 http://www.intra2net.com/de/produkte/opensource/ftdi/
23 The library is easy to use. Have a look at this short example:
26 More examples can be found in the "examples" directory.
28 /** \addtogroup libftdi */
37 /* stuff needed for async write */
38 #ifdef LIBFTDI_LINUX_ASYNC_MODE
39 #include <sys/ioctl.h>
41 #include <sys/select.h>
42 #include <sys/types.h>
44 #include <linux/usbdevice_fs.h>
47 #define ftdi_error_return(code, str) do { \
48 ftdi->error_str = str; \
54 Initializes a ftdi_context.
56 \param ftdi pointer to ftdi_context
59 \retval -1: couldn't allocate read buffer
61 \remark This should be called before all functions
63 int ftdi_init(struct ftdi_context *ftdi)
68 ftdi->usb_read_timeout = 5000;
69 ftdi->usb_write_timeout = 5000;
71 ftdi->type = TYPE_BM; /* chip type */
73 ftdi->bitbang_enabled = 0;
75 ftdi->readbuffer = NULL;
76 ftdi->readbuffer_offset = 0;
77 ftdi->readbuffer_remaining = 0;
78 ftdi->writebuffer_chunksize = 4096;
84 ftdi->bitbang_mode = 1; /* 1: Normal bitbang mode, 2: SPI bitbang mode */
86 ftdi->error_str = NULL;
88 #ifdef LIBFTDI_LINUX_ASYNC_MODE
89 ftdi->async_usb_buffer_size=10;
90 if ((ftdi->async_usb_buffer=malloc(sizeof(struct usbdevfs_urb)*ftdi->async_usb_buffer_size)) == NULL)
91 ftdi_error_return(-1, "out of memory for async usb buffer");
93 /* initialize async usb buffer with unused-marker */
94 for (i=0; i < ftdi->async_usb_buffer_size; i++)
95 ((struct usbdevfs_urb*)ftdi->async_usb_buffer)[i].usercontext = FTDI_URB_USERCONTEXT_COOKIE;
97 ftdi->async_usb_buffer_size=0;
98 ftdi->async_usb_buffer = NULL;
101 ftdi->eeprom_size = FTDI_DEFAULT_EEPROM_SIZE;
103 /* All fine. Now allocate the readbuffer */
104 return ftdi_read_data_set_chunksize(ftdi, 4096);
108 Open selected channels on a chip, otherwise use first channel.
110 \param ftdi pointer to ftdi_context
111 \param interface Interface to use for FT2232C chips.
114 \retval -1: unknown interface
116 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
121 /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
125 ftdi->index = INTERFACE_B;
130 ftdi_error_return(-1, "Unknown interface");
136 Deinitializes a ftdi_context.
138 \param ftdi pointer to ftdi_context
140 void ftdi_deinit(struct ftdi_context *ftdi)
142 if (ftdi->async_usb_buffer != NULL) {
143 free(ftdi->async_usb_buffer);
144 ftdi->async_usb_buffer = NULL;
147 if (ftdi->readbuffer != NULL) {
148 free(ftdi->readbuffer);
149 ftdi->readbuffer = NULL;
154 Use an already open libusb device.
156 \param ftdi pointer to ftdi_context
157 \param usb libusb usb_dev_handle to use
159 void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
166 Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
167 needs to be deallocated by ftdi_list_free() after use.
169 \param ftdi pointer to ftdi_context
170 \param devlist Pointer where to store list of found devices
171 \param vendor Vendor ID to search for
172 \param product Product ID to search for
174 \retval >0: number of devices found
175 \retval -1: usb_find_busses() failed
176 \retval -2: usb_find_devices() failed
177 \retval -3: out of memory
179 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
181 struct ftdi_device_list **curdev;
183 struct usb_device *dev;
187 if (usb_find_busses() < 0)
188 ftdi_error_return(-1, "usb_find_busses() failed");
189 if (usb_find_devices() < 0)
190 ftdi_error_return(-2, "usb_find_devices() failed");
194 for (bus = usb_busses; bus; bus = bus->next) {
195 for (dev = bus->devices; dev; dev = dev->next) {
196 if (dev->descriptor.idVendor == vendor
197 && dev->descriptor.idProduct == product)
199 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
201 ftdi_error_return(-3, "out of memory");
203 (*curdev)->next = NULL;
204 (*curdev)->dev = dev;
206 curdev = &(*curdev)->next;
216 Frees a usb device list.
218 \param devlist USB device list created by ftdi_usb_find_all()
220 void ftdi_list_free(struct ftdi_device_list **devlist)
222 struct ftdi_device_list *curdev, *next;
224 for (curdev = *devlist; curdev != NULL;) {
234 Return device ID strings from the usb device.
236 The parameters manufacturer, description and serial may be NULL
237 or pointer to buffers to store the fetched strings.
239 \note Use this function only in combination with ftdi_usb_find_all()
240 as it closes the internal "usb_dev" after use.
242 \param ftdi pointer to ftdi_context
243 \param dev libusb usb_dev to use
244 \param manufacturer Store manufacturer string here if not NULL
245 \param mnf_len Buffer size of manufacturer string
246 \param description Store product description string here if not NULL
247 \param desc_len Buffer size of product description string
248 \param serial Store serial string here if not NULL
249 \param serial_len Buffer size of serial string
252 \retval -1: wrong arguments
253 \retval -4: unable to open device
254 \retval -7: get product manufacturer failed
255 \retval -8: get product description failed
256 \retval -9: get serial number failed
257 \retval -10: unable to close device
259 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct usb_device * dev,
260 char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
262 if ((ftdi==NULL) || (dev==NULL))
265 if (!(ftdi->usb_dev = usb_open(dev)))
266 ftdi_error_return(-4, usb_strerror());
268 if (manufacturer != NULL) {
269 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iManufacturer, manufacturer, mnf_len) <= 0) {
270 usb_close (ftdi->usb_dev);
271 ftdi_error_return(-7, usb_strerror());
275 if (description != NULL) {
276 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, description, desc_len) <= 0) {
277 usb_close (ftdi->usb_dev);
278 ftdi_error_return(-8, usb_strerror());
282 if (serial != NULL) {
283 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, serial, serial_len) <= 0) {
284 usb_close (ftdi->usb_dev);
285 ftdi_error_return(-9, usb_strerror());
289 if (usb_close (ftdi->usb_dev) != 0)
290 ftdi_error_return(-10, usb_strerror());
296 Opens a ftdi device given by a usb_device.
298 \param ftdi pointer to ftdi_context
299 \param dev libusb usb_dev to use
302 \retval -4: unable to open device
303 \retval -5: unable to claim device
304 \retval -6: reset failed
305 \retval -7: set baudrate failed
307 int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
309 int detach_errno = 0;
310 if (!(ftdi->usb_dev = usb_open(dev)))
311 ftdi_error_return(-4, "usb_open() failed");
313 #ifdef LIBUSB_HAS_GET_DRIVER_NP
314 // Try to detach ftdi_sio kernel module
315 // Returns ENODATA if driver is not loaded
316 if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
317 detach_errno = errno;
320 if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0) {
321 usb_close (ftdi->usb_dev);
322 if (detach_errno == EPERM) {
323 ftdi_error_return(-8, "inappropriate permissions on device!");
325 ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
329 if (ftdi_usb_reset (ftdi) != 0) {
330 usb_close (ftdi->usb_dev);
331 ftdi_error_return(-6, "ftdi_usb_reset failed");
334 if (ftdi_set_baudrate (ftdi, 9600) != 0) {
335 usb_close (ftdi->usb_dev);
336 ftdi_error_return(-7, "set baudrate failed");
339 // Try to guess chip type
340 // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
341 if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
342 && dev->descriptor.iSerialNumber == 0))
343 ftdi->type = TYPE_BM;
344 else if (dev->descriptor.bcdDevice == 0x200)
345 ftdi->type = TYPE_AM;
346 else if (dev->descriptor.bcdDevice == 0x500) {
347 ftdi->type = TYPE_2232C;
349 ftdi->index = INTERFACE_A;
350 } else if (dev->descriptor.bcdDevice == 0x600)
353 ftdi_error_return(0, "all fine");
357 Opens the first device with a given vendor and product ids.
359 \param ftdi pointer to ftdi_context
360 \param vendor Vendor ID
361 \param product Product ID
363 \retval same as ftdi_usb_open_desc()
365 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
367 return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
371 Opens the first device with a given, vendor id, product id,
372 description and serial.
374 \param ftdi pointer to ftdi_context
375 \param vendor Vendor ID
376 \param product Product ID
377 \param description Description to search for. Use NULL if not needed.
378 \param serial Serial to search for. Use NULL if not needed.
381 \retval -1: usb_find_busses() failed
382 \retval -2: usb_find_devices() failed
383 \retval -3: usb device not found
384 \retval -4: unable to open device
385 \retval -5: unable to claim device
386 \retval -6: reset failed
387 \retval -7: set baudrate failed
388 \retval -8: get product description failed
389 \retval -9: get serial number failed
390 \retval -10: unable to close device
392 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
393 const char* description, const char* serial)
396 struct usb_device *dev;
401 if (usb_find_busses() < 0)
402 ftdi_error_return(-1, "usb_find_busses() failed");
403 if (usb_find_devices() < 0)
404 ftdi_error_return(-2, "usb_find_devices() failed");
406 for (bus = usb_busses; bus; bus = bus->next) {
407 for (dev = bus->devices; dev; dev = dev->next) {
408 if (dev->descriptor.idVendor == vendor
409 && dev->descriptor.idProduct == product) {
410 if (!(ftdi->usb_dev = usb_open(dev)))
411 ftdi_error_return(-4, "usb_open() failed");
413 if (description != NULL) {
414 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0) {
415 usb_close (ftdi->usb_dev);
416 ftdi_error_return(-8, "unable to fetch product description");
418 if (strncmp(string, description, sizeof(string)) != 0) {
419 if (usb_close (ftdi->usb_dev) != 0)
420 ftdi_error_return(-10, "unable to close device");
424 if (serial != NULL) {
425 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0) {
426 usb_close (ftdi->usb_dev);
427 ftdi_error_return(-9, "unable to fetch serial number");
429 if (strncmp(string, serial, sizeof(string)) != 0) {
430 if (usb_close (ftdi->usb_dev) != 0)
431 ftdi_error_return(-10, "unable to close device");
436 if (usb_close (ftdi->usb_dev) != 0)
437 ftdi_error_return(-10, "unable to close device");
439 return ftdi_usb_open_dev(ftdi, dev);
445 ftdi_error_return(-3, "device not found");
449 Resets the ftdi device.
451 \param ftdi pointer to ftdi_context
454 \retval -1: FTDI reset failed
456 int ftdi_usb_reset(struct ftdi_context *ftdi)
458 if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
459 ftdi_error_return(-1,"FTDI reset failed");
461 // Invalidate data in the readbuffer
462 ftdi->readbuffer_offset = 0;
463 ftdi->readbuffer_remaining = 0;
469 Clears the buffers on the chip.
471 \param ftdi pointer to ftdi_context
474 \retval -1: write buffer purge failed
475 \retval -2: read buffer purge failed
477 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
479 if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 1, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
480 ftdi_error_return(-1, "FTDI purge of RX buffer failed");
482 // Invalidate data in the readbuffer
483 ftdi->readbuffer_offset = 0;
484 ftdi->readbuffer_remaining = 0;
486 if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 2, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
487 ftdi_error_return(-2, "FTDI purge of TX buffer failed");
493 Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
495 \param ftdi pointer to ftdi_context
498 \retval -1: usb_release failed
499 \retval -2: usb_close failed
501 int ftdi_usb_close(struct ftdi_context *ftdi)
505 #ifdef LIBFTDI_LINUX_ASYNC_MODE
506 /* try to release some kernel resources */
507 ftdi_async_complete(ftdi,1);
510 if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
513 if (usb_close (ftdi->usb_dev) != 0)
520 ftdi_convert_baudrate returns nearest supported baud rate to that requested.
521 Function is only used internally
524 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
525 unsigned short *value, unsigned short *index)
527 static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
528 static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
529 static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
530 int divisor, best_divisor, best_baud, best_baud_diff;
531 unsigned long encoded_divisor;
539 divisor = 24000000 / baudrate;
541 if (ftdi->type == TYPE_AM) {
542 // Round down to supported fraction (AM only)
543 divisor -= am_adjust_dn[divisor & 7];
546 // Try this divisor and the one above it (because division rounds down)
550 for (i = 0; i < 2; i++) {
551 int try_divisor = divisor + i;
555 // Round up to supported divisor value
556 if (try_divisor <= 8) {
557 // Round up to minimum supported divisor
559 } else if (ftdi->type != TYPE_AM && try_divisor < 12) {
560 // BM doesn't support divisors 9 through 11 inclusive
562 } else if (divisor < 16) {
563 // AM doesn't support divisors 9 through 15 inclusive
566 if (ftdi->type == TYPE_AM) {
567 // Round up to supported fraction (AM only)
568 try_divisor += am_adjust_up[try_divisor & 7];
569 if (try_divisor > 0x1FFF8) {
570 // Round down to maximum supported divisor value (for AM)
571 try_divisor = 0x1FFF8;
574 if (try_divisor > 0x1FFFF) {
575 // Round down to maximum supported divisor value (for BM)
576 try_divisor = 0x1FFFF;
580 // Get estimated baud rate (to nearest integer)
581 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
582 // Get absolute difference from requested baud rate
583 if (baud_estimate < baudrate) {
584 baud_diff = baudrate - baud_estimate;
586 baud_diff = baud_estimate - baudrate;
588 if (i == 0 || baud_diff < best_baud_diff) {
589 // Closest to requested baud rate so far
590 best_divisor = try_divisor;
591 best_baud = baud_estimate;
592 best_baud_diff = baud_diff;
593 if (baud_diff == 0) {
594 // Spot on! No point trying
599 // Encode the best divisor value
600 encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
601 // Deal with special cases for encoded value
602 if (encoded_divisor == 1) {
603 encoded_divisor = 0; // 3000000 baud
604 } else if (encoded_divisor == 0x4001) {
605 encoded_divisor = 1; // 2000000 baud (BM only)
607 // Split into "value" and "index" values
608 *value = (unsigned short)(encoded_divisor & 0xFFFF);
609 if(ftdi->type == TYPE_2232C) {
610 *index = (unsigned short)(encoded_divisor >> 8);
612 *index |= ftdi->index;
615 *index = (unsigned short)(encoded_divisor >> 16);
617 // Return the nearest baud rate
622 Sets the chip baud rate
624 \param ftdi pointer to ftdi_context
625 \param baudrate baud rate to set
628 \retval -1: invalid baudrate
629 \retval -2: setting baudrate failed
631 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
633 unsigned short value, index;
636 if (ftdi->bitbang_enabled) {
637 baudrate = baudrate*4;
640 actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
641 if (actual_baudrate <= 0)
642 ftdi_error_return (-1, "Silly baudrate <= 0.");
644 // Check within tolerance (about 5%)
645 if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
646 || ((actual_baudrate < baudrate)
647 ? (actual_baudrate * 21 < baudrate * 20)
648 : (baudrate * 21 < actual_baudrate * 20)))
649 ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
651 if (usb_control_msg(ftdi->usb_dev, 0x40, 3, value, index, NULL, 0, ftdi->usb_write_timeout) != 0)
652 ftdi_error_return (-2, "Setting new baudrate failed");
654 ftdi->baudrate = baudrate;
659 Set (RS232) line characteristics by Alain Abbas
661 \param ftdi pointer to ftdi_context
662 \param bits Number of bits
663 \param sbit Number of stop bits
664 \param parity Parity mode
667 \retval -1: Setting line property failed
669 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
670 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
672 unsigned short value = bits;
676 value |= (0x00 << 8);
679 value |= (0x01 << 8);
682 value |= (0x02 << 8);
685 value |= (0x03 << 8);
688 value |= (0x04 << 8);
694 value |= (0x00 << 11);
697 value |= (0x01 << 11);
700 value |= (0x02 << 11);
704 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x04, value, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
705 ftdi_error_return (-1, "Setting new line property failed");
711 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
713 \param ftdi pointer to ftdi_context
714 \param buf Buffer with the data
715 \param size Size of the buffer
717 \retval <0: error code from usb_bulk_write()
718 \retval >0: number of bytes written
720 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
724 int total_written = 0;
726 while (offset < size) {
727 int write_size = ftdi->writebuffer_chunksize;
729 if (offset+write_size > size)
730 write_size = size-offset;
732 ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
734 ftdi_error_return(ret, "usb bulk write failed");
736 total_written += ret;
737 offset += write_size;
740 return total_written;
743 #ifdef LIBFTDI_LINUX_ASYNC_MODE
744 /* this is strongly dependent on libusb using the same struct layout. If libusb
745 changes in some later version this may break horribly (this is for libusb 0.1.12) */
746 struct usb_dev_handle {
748 // some other stuff coming here we don't need
752 Check for pending async urbs
755 static int _usb_get_async_urbs_pending(struct ftdi_context *ftdi)
757 struct usbdevfs_urb *urb;
761 for (i=0; i < ftdi->async_usb_buffer_size; i++) {
762 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
763 if (urb->usercontext != FTDI_URB_USERCONTEXT_COOKIE)
771 Wait until one or more async URBs are completed by the kernel and mark their
772 positions in the async-buffer as unused
774 \param ftdi pointer to ftdi_context
775 \param wait_for_more if != 0 wait for more than one write to complete
776 \param timeout_msec max milliseconds to wait
780 static void _usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
783 struct usbdevfs_urb *urb=NULL;
789 FD_SET(ftdi->usb_dev->fd, &writefds);
791 /* init timeout only once, select writes time left after call */
792 tv.tv_sec = timeout_msec / 1000;
793 tv.tv_usec = (timeout_msec % 1000) * 1000;
796 while (_usb_get_async_urbs_pending(ftdi)
797 && (ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_REAPURBNDELAY, &urb)) == -1
800 if (keep_going && !wait_for_more) {
801 /* don't wait if repeating only for keep_going */
806 /* wait for timeout msec or something written ready */
807 select(ftdi->usb_dev->fd+1, NULL, &writefds, NULL, &tv);
810 if (ret == 0 && urb != NULL) {
811 /* got a free urb, mark it */
812 urb->usercontext = FTDI_URB_USERCONTEXT_COOKIE;
814 /* try to get more urbs that are ready now, but don't wait anymore */
818 /* no more urbs waiting */
821 } while (keep_going);
825 Wait until one or more async URBs are completed by the kernel and mark their
826 positions in the async-buffer as unused.
828 \param ftdi pointer to ftdi_context
829 \param wait_for_more if != 0 wait for more than one write to complete (until write timeout)
831 void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
833 _usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
837 Stupid libusb does not offer async writes nor does it allow
838 access to its fd - so we need some hacks here.
841 static int _usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
843 struct usbdevfs_urb *urb;
844 int bytesdone = 0, requested;
849 /* find a free urb buffer we can use */
851 for (cleanup_count=0; urb==NULL && cleanup_count <= 1; cleanup_count++)
853 if (i==ftdi->async_usb_buffer_size) {
854 /* wait until some buffers are free */
855 _usb_async_cleanup(ftdi,0,ftdi->usb_write_timeout);
858 for (i=0; i < ftdi->async_usb_buffer_size; i++) {
859 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
860 if (urb->usercontext == FTDI_URB_USERCONTEXT_COOKIE)
861 break; /* found a free urb position */
866 /* no free urb position found */
870 requested = size - bytesdone;
871 if (requested > 4096)
874 memset(urb,0,sizeof(urb));
876 urb->type = USBDEVFS_URB_TYPE_BULK;
879 urb->buffer = bytes + bytesdone;
880 urb->buffer_length = requested;
882 urb->actual_length = 0;
883 urb->number_of_packets = 0;
884 urb->usercontext = 0;
887 ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_SUBMITURB, urb);
888 } while (ret < 0 && errno == EINTR);
890 return ret; /* the caller can read errno to get more info */
892 bytesdone += requested;
893 } while (bytesdone < size);
898 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip.
899 Does not wait for completion of the transfer nor does it make sure that
900 the transfer was successful.
902 This function could be extended to use signals and callbacks to inform the
903 caller of completion or error - but this is not done yet, volunteers welcome.
905 Works around libusb and directly accesses functions only available on Linux.
907 \param ftdi pointer to ftdi_context
908 \param buf Buffer with the data
909 \param size Size of the buffer
911 \retval <0: error code from usb_bulk_write()
912 \retval >0: number of bytes written
914 int ftdi_write_data_async(struct ftdi_context *ftdi, unsigned char *buf, int size)
918 int total_written = 0;
920 while (offset < size) {
921 int write_size = ftdi->writebuffer_chunksize;
923 if (offset+write_size > size)
924 write_size = size-offset;
926 ret = _usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
928 ftdi_error_return(ret, "usb bulk write async failed");
930 total_written += ret;
931 offset += write_size;
934 return total_written;
936 #endif // LIBFTDI_LINUX_ASYNC_MODE
939 Configure write buffer chunk size.
942 \param ftdi pointer to ftdi_context
943 \param chunksize Chunk size
947 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
949 ftdi->writebuffer_chunksize = chunksize;
954 Get write buffer chunk size.
956 \param ftdi pointer to ftdi_context
957 \param chunksize Pointer to store chunk size in
961 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
963 *chunksize = ftdi->writebuffer_chunksize;
968 Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
970 Automatically strips the two modem status bytes transfered during every read.
972 \param ftdi pointer to ftdi_context
973 \param buf Buffer to store data in
974 \param size Size of the buffer
976 \retval <0: error code from usb_bulk_read()
977 \retval 0: no data was available
978 \retval >0: number of bytes read
980 \remark This function is not useful in bitbang mode.
981 Use ftdi_read_pins() to get the current state of the pins.
983 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
985 int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
987 // everything we want is still in the readbuffer?
988 if (size <= ftdi->readbuffer_remaining) {
989 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
992 ftdi->readbuffer_remaining -= size;
993 ftdi->readbuffer_offset += size;
995 /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
999 // something still in the readbuffer, but not enough to satisfy 'size'?
1000 if (ftdi->readbuffer_remaining != 0) {
1001 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1004 offset += ftdi->readbuffer_remaining;
1006 // do the actual USB read
1007 while (offset < size && ret > 0) {
1008 ftdi->readbuffer_remaining = 0;
1009 ftdi->readbuffer_offset = 0;
1010 /* returns how much received */
1011 ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
1013 ftdi_error_return(ret, "usb bulk read failed");
1016 // skip FTDI status bytes.
1017 // Maybe stored in the future to enable modem use
1018 num_of_chunks = ret / 64;
1019 chunk_remains = ret % 64;
1020 //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1022 ftdi->readbuffer_offset += 2;
1026 for (i = 1; i < num_of_chunks; i++)
1027 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
1028 ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
1030 if (chunk_remains > 2) {
1031 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
1032 ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
1034 ret -= 2*num_of_chunks;
1036 ret -= 2*(num_of_chunks-1)+chunk_remains;
1038 } else if (ret <= 2) {
1039 // no more data to read?
1043 // data still fits in buf?
1044 if (offset+ret <= size) {
1045 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
1046 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1049 /* Did we read exactly the right amount of bytes? */
1051 //printf("read_data exact rem %d offset %d\n",
1052 //ftdi->readbuffer_remaining, offset);
1055 // only copy part of the data or size <= readbuffer_chunksize
1056 int part_size = size-offset;
1057 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1059 ftdi->readbuffer_offset += part_size;
1060 ftdi->readbuffer_remaining = ret-part_size;
1061 offset += part_size;
1063 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
1064 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
1075 Configure read buffer chunk size.
1078 Automatically reallocates the buffer.
1080 \param ftdi pointer to ftdi_context
1081 \param chunksize Chunk size
1085 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1087 unsigned char *new_buf;
1089 // Invalidate all remaining data
1090 ftdi->readbuffer_offset = 0;
1091 ftdi->readbuffer_remaining = 0;
1093 if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1094 ftdi_error_return(-1, "out of memory for readbuffer");
1096 ftdi->readbuffer = new_buf;
1097 ftdi->readbuffer_chunksize = chunksize;
1103 Get read buffer chunk size.
1105 \param ftdi pointer to ftdi_context
1106 \param chunksize Pointer to store chunk size in
1110 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1112 *chunksize = ftdi->readbuffer_chunksize;
1118 Enable bitbang mode.
1120 For advanced bitbang modes of the FT2232C chip use ftdi_set_bitmode().
1122 \param ftdi pointer to ftdi_context
1123 \param bitmask Bitmask to configure lines.
1124 HIGH/ON value configures a line as output.
1127 \retval -1: can't enable bitbang mode
1129 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1131 unsigned short usb_val;
1133 usb_val = bitmask; // low byte: bitmask
1134 /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1135 usb_val |= (ftdi->bitbang_mode << 8);
1137 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1138 ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1140 ftdi->bitbang_enabled = 1;
1145 Disable bitbang mode.
1147 \param ftdi pointer to ftdi_context
1150 \retval -1: can't disable bitbang mode
1152 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1154 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1155 ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1157 ftdi->bitbang_enabled = 0;
1162 Enable advanced bitbang mode for FT2232C chips.
1164 \param ftdi pointer to ftdi_context
1165 \param bitmask Bitmask to configure lines.
1166 HIGH/ON value configures a line as output.
1167 \param mode Bitbang mode: 1 for normal mode, 2 for SPI mode
1170 \retval -1: can't enable bitbang mode
1172 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1174 unsigned short usb_val;
1176 usb_val = bitmask; // low byte: bitmask
1177 usb_val |= (mode << 8);
1178 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1179 ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1181 ftdi->bitbang_mode = mode;
1182 ftdi->bitbang_enabled = (mode == BITMODE_BITBANG || mode == BITMODE_SYNCBB)?1:0;
1187 Directly read pin state. Useful for bitbang mode.
1189 \param ftdi pointer to ftdi_context
1190 \param pins Pointer to store pins into
1193 \retval -1: read pins failed
1195 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1197 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0C, 0, ftdi->index, (char *)pins, 1, ftdi->usb_read_timeout) != 1)
1198 ftdi_error_return(-1, "read pins failed");
1206 The FTDI chip keeps data in the internal buffer for a specific
1207 amount of time if the buffer is not full yet to decrease
1208 load on the usb bus.
1210 \param ftdi pointer to ftdi_context
1211 \param latency Value between 1 and 255
1214 \retval -1: latency out of range
1215 \retval -2: unable to set latency timer
1217 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1219 unsigned short usb_val;
1222 ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
1225 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x09, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1226 ftdi_error_return(-2, "unable to set latency timer");
1234 \param ftdi pointer to ftdi_context
1235 \param latency Pointer to store latency value in
1238 \retval -1: unable to get latency timer
1240 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1242 unsigned short usb_val;
1243 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0A, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
1244 ftdi_error_return(-1, "reading latency timer failed");
1246 *latency = (unsigned char)usb_val;
1253 \param ftdi pointer to ftdi_context
1254 \param eeprom Pointer to ftdi_eeprom
1258 void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
1260 ftdi->eeprom_size=size;
1265 Init eeprom with default values.
1267 \param eeprom Pointer to ftdi_eeprom
1269 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
1271 eeprom->vendor_id = 0x0403;
1272 eeprom->product_id = 0x6001;
1274 eeprom->self_powered = 1;
1275 eeprom->remote_wakeup = 1;
1276 eeprom->BM_type_chip = 1;
1278 eeprom->in_is_isochronous = 0;
1279 eeprom->out_is_isochronous = 0;
1280 eeprom->suspend_pull_downs = 0;
1282 eeprom->use_serial = 0;
1283 eeprom->change_usb_version = 0;
1284 eeprom->usb_version = 0x0200;
1285 eeprom->max_power = 0;
1287 eeprom->manufacturer = NULL;
1288 eeprom->product = NULL;
1289 eeprom->serial = NULL;
1291 eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
1295 Build binary output from ftdi_eeprom structure.
1296 Output is suitable for ftdi_write_eeprom().
1298 \param eeprom Pointer to ftdi_eeprom
1299 \param output Buffer of 128 bytes to store eeprom image to
1301 \retval >0: used eeprom size
1302 \retval -1: eeprom size (128 bytes) exceeded by custom strings
1304 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
1307 unsigned short checksum, value;
1308 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
1311 if (eeprom->manufacturer != NULL)
1312 manufacturer_size = strlen(eeprom->manufacturer);
1313 if (eeprom->product != NULL)
1314 product_size = strlen(eeprom->product);
1315 if (eeprom->serial != NULL)
1316 serial_size = strlen(eeprom->serial);
1318 size_check = eeprom->size;
1319 size_check -= 28; // 28 are always in use (fixed)
1321 // Top half of a 256byte eeprom is used just for strings and checksum
1322 // it seems that the FTDI chip will not read these strings from the lower half
1323 // Each string starts with two bytes; offset and type (0x03 for string)
1324 // the checksum needs two bytes, so without the string data that 8 bytes from the top half
1325 if(eeprom->size>=256)size_check = 120;
1326 size_check -= manufacturer_size*2;
1327 size_check -= product_size*2;
1328 size_check -= serial_size*2;
1330 // eeprom size exceeded?
1335 memset (output, 0, eeprom->size);
1337 // Addr 00: Stay 00 00
1338 // Addr 02: Vendor ID
1339 output[0x02] = eeprom->vendor_id;
1340 output[0x03] = eeprom->vendor_id >> 8;
1342 // Addr 04: Product ID
1343 output[0x04] = eeprom->product_id;
1344 output[0x05] = eeprom->product_id >> 8;
1346 // Addr 06: Device release number (0400h for BM features)
1347 output[0x06] = 0x00;
1349 if (eeprom->BM_type_chip == 1)
1350 output[0x07] = 0x04;
1352 output[0x07] = 0x02;
1354 // Addr 08: Config descriptor
1355 // Bit 1: remote wakeup if 1
1356 // Bit 0: self powered if 1
1359 if (eeprom->self_powered == 1)
1361 if (eeprom->remote_wakeup == 1)
1365 // Addr 09: Max power consumption: max power = value * 2 mA
1366 output[0x09] = eeprom->max_power;
1369 // Addr 0A: Chip configuration
1370 // Bit 7: 0 - reserved
1371 // Bit 6: 0 - reserved
1372 // Bit 5: 0 - reserved
1373 // Bit 4: 1 - Change USB version
1374 // Bit 3: 1 - Use the serial number string
1375 // Bit 2: 1 - Enable suspend pull downs for lower power
1376 // Bit 1: 1 - Out EndPoint is Isochronous
1377 // Bit 0: 1 - In EndPoint is Isochronous
1380 if (eeprom->in_is_isochronous == 1)
1382 if (eeprom->out_is_isochronous == 1)
1384 if (eeprom->suspend_pull_downs == 1)
1386 if (eeprom->use_serial == 1)
1388 if (eeprom->change_usb_version == 1)
1392 // Addr 0B: reserved
1393 output[0x0B] = 0x00;
1395 // Addr 0C: USB version low byte when 0x0A bit 4 is set
1396 // Addr 0D: USB version high byte when 0x0A bit 4 is set
1397 if (eeprom->change_usb_version == 1) {
1398 output[0x0C] = eeprom->usb_version;
1399 output[0x0D] = eeprom->usb_version >> 8;
1403 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
1404 // Addr 0F: Length of manufacturer string
1405 output[0x0F] = manufacturer_size*2 + 2;
1407 // Addr 10: Offset of the product string + 0x80, calculated later
1408 // Addr 11: Length of product string
1409 output[0x11] = product_size*2 + 2;
1411 // Addr 12: Offset of the serial string + 0x80, calculated later
1412 // Addr 13: Length of serial string
1413 output[0x13] = serial_size*2 + 2;
1417 if(eeprom->size>=256) i = 0x80;
1420 // Output manufacturer
1421 output[0x0E] = i | 0x80; // calculate offset
1422 output[i++] = manufacturer_size*2 + 2;
1423 output[i++] = 0x03; // type: string
1424 for (j = 0; j < manufacturer_size; j++) {
1425 output[i] = eeprom->manufacturer[j], i++;
1426 output[i] = 0x00, i++;
1429 // Output product name
1430 output[0x10] = i | 0x80; // calculate offset
1431 output[i] = product_size*2 + 2, i++;
1432 output[i] = 0x03, i++;
1433 for (j = 0; j < product_size; j++) {
1434 output[i] = eeprom->product[j], i++;
1435 output[i] = 0x00, i++;
1439 output[0x12] = i | 0x80; // calculate offset
1440 output[i] = serial_size*2 + 2, i++;
1441 output[i] = 0x03, i++;
1442 for (j = 0; j < serial_size; j++) {
1443 output[i] = eeprom->serial[j], i++;
1444 output[i] = 0x00, i++;
1447 // calculate checksum
1450 for (i = 0; i < eeprom->size/2-1; i++) {
1451 value = output[i*2];
1452 value += output[(i*2)+1] << 8;
1454 checksum = value^checksum;
1455 checksum = (checksum << 1) | (checksum >> 15);
1458 output[eeprom->size-2] = checksum;
1459 output[eeprom->size-1] = checksum >> 8;
1467 \param ftdi pointer to ftdi_context
1468 \param eeprom Pointer to store eeprom into
1471 \retval -1: read failed
1473 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
1477 for (i = 0; i < ftdi->eeprom_size/2; i++) {
1478 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
1479 ftdi_error_return(-1, "reading eeprom failed");
1486 ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
1487 Function is only used internally
1490 static unsigned char ftdi_read_chipid_shift(unsigned char value)
1492 return ((value & 1) << 1) |
1493 ((value & 2) << 5) |
1494 ((value & 4) >> 2) |
1495 ((value & 8) << 4) |
1496 ((value & 16) >> 1) |
1497 ((value & 32) >> 1) |
1498 ((value & 64) >> 4) |
1499 ((value & 128) >> 2);
1503 Read the FTDIChip-ID from R-type devices
1505 \param ftdi pointer to ftdi_context
1506 \param chipid Pointer to store FTDIChip-ID
1509 \retval -1: read failed
1511 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
1513 unsigned int a = 0, b = 0;
1515 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, 0x43, (char *)&a, 2, ftdi->usb_read_timeout) == 2)
1517 a = a << 8 | a >> 8;
1518 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, 0x44, (char *)&b, 2, ftdi->usb_read_timeout) == 2)
1520 b = b << 8 | b >> 8;
1522 a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
1523 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
1524 *chipid = a ^ 0xa5f0f7d1;
1529 ftdi_error_return(-1, "read of FTDIChip-ID failed");
1533 Guesses size of eeprom by reading eeprom and comparing halves - will not work with blank eeprom
1534 Call this function then do a write then call again to see if size changes, if so write again.
1536 \param ftdi pointer to ftdi_context
1537 \param eeprom Pointer to store eeprom into
1538 \param maxsize the size of the buffer to read into
1540 \retval size of eeprom
1542 int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
1544 int i=0,j,minsize=32;
1548 for (j = 0; i < maxsize/2 && j<size; j++) {
1549 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
1550 ftdi_error_return(-1, "reading eeprom failed");
1554 }while(size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
1562 \param ftdi pointer to ftdi_context
1563 \param eeprom Pointer to read eeprom from
1566 \retval -1: read failed
1568 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
1570 unsigned short usb_val;
1573 for (i = 0; i < ftdi->eeprom_size/2; i++) {
1574 usb_val = eeprom[i*2];
1575 usb_val += eeprom[(i*2)+1] << 8;
1576 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x91, usb_val, i, NULL, 0, ftdi->usb_write_timeout) != 0)
1577 ftdi_error_return(-1, "unable to write eeprom");
1586 \param ftdi pointer to ftdi_context
1589 \retval -1: erase failed
1591 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
1593 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x92, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
1594 ftdi_error_return(-1, "unable to erase eeprom");
1600 Get string representation for last error code
1602 \param ftdi pointer to ftdi_context
1604 \retval Pointer to error string
1606 char *ftdi_get_error_string (struct ftdi_context *ftdi)
1608 return ftdi->error_str;
1612 Flow control code by Lorenz Moesenlechner (lorenz@hcilab.org)
1613 and Matthias Kranz (matthias@hcilab.org)
1616 Set flowcontrol for ftdi chip
1618 \param ftdi pointer to ftdi_context
1619 \param flowctrl flow control to use. should be
1620 SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
1623 \retval -1: set flow control failed
1625 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1627 if (usb_control_msg(ftdi->usb_dev, SIO_SET_FLOW_CTRL_REQUEST_TYPE,
1628 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->interface),
1629 NULL, 0, ftdi->usb_write_timeout) != 0)
1630 ftdi_error_return(-1, "set flow control failed");
1638 \param ftdi pointer to ftdi_context
1639 \param state state to set line to (1 or 0)
1642 \retval -1: set dtr failed
1644 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
1646 unsigned short usb_val;
1649 usb_val = SIO_SET_DTR_HIGH;
1651 usb_val = SIO_SET_DTR_LOW;
1653 if (usb_control_msg(ftdi->usb_dev, SIO_SET_MODEM_CTRL_REQUEST_TYPE,
1654 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->interface,
1655 NULL, 0, ftdi->usb_write_timeout) != 0)
1656 ftdi_error_return(-1, "set dtr failed");
1664 \param ftdi pointer to ftdi_context
1665 \param state state to set line to (1 or 0)
1668 \retval -1 set rts failed
1670 int ftdi_setrts(struct ftdi_context *ftdi, int state)
1672 unsigned short usb_val;
1675 usb_val = SIO_SET_RTS_HIGH;
1677 usb_val = SIO_SET_RTS_LOW;
1679 if (usb_control_msg(ftdi->usb_dev, SIO_SET_MODEM_CTRL_REQUEST_TYPE,
1680 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->interface,
1681 NULL, 0, ftdi->usb_write_timeout) != 0)
1682 ftdi_error_return(-1, "set of rts failed");
1687 /* @} end of doxygen libftdi group */