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 #include <sys/ioctl.h>
40 #include <sys/select.h>
41 #include <sys/types.h>
43 #include <linux/usbdevice_fs.h>
45 #define ftdi_error_return(code, str) do { \
46 ftdi->error_str = str; \
52 Initializes a ftdi_context.
54 \param ftdi pointer to ftdi_context
57 \retval -1: couldn't allocate read buffer
59 \remark This should be called before all functions
61 int ftdi_init(struct ftdi_context *ftdi)
66 ftdi->usb_read_timeout = 5000;
67 ftdi->usb_write_timeout = 5000;
69 ftdi->type = TYPE_BM; /* chip type */
71 ftdi->bitbang_enabled = 0;
73 ftdi->readbuffer = NULL;
74 ftdi->readbuffer_offset = 0;
75 ftdi->readbuffer_remaining = 0;
76 ftdi->writebuffer_chunksize = 4096;
82 ftdi->bitbang_mode = 1; /* 1: Normal bitbang mode, 2: SPI bitbang mode */
84 ftdi->error_str = NULL;
86 ftdi->async_usb_buffer_size=10;
87 if ((ftdi->async_usb_buffer=malloc(sizeof(struct usbdevfs_urb)*ftdi->async_usb_buffer_size)) == NULL)
88 ftdi_error_return(-1, "out of memory for async usb buffer");
90 /* initialize async usb buffer with unused-marker */
91 for (i=0; i < ftdi->async_usb_buffer_size; i++)
92 ((struct usbdevfs_urb*)ftdi->async_usb_buffer)[i].usercontext = FTDI_URB_USERCONTEXT_COOKIE;
94 ftdi->eeprom_size = FTDI_DEFAULT_EEPROM_SIZE;
96 /* All fine. Now allocate the readbuffer */
97 return ftdi_read_data_set_chunksize(ftdi, 4096);
101 Open selected channels on a chip, otherwise use first channel.
103 \param ftdi pointer to ftdi_context
104 \param interface Interface to use for FT2232C chips.
107 \retval -1: unknown interface
109 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
114 /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
118 ftdi->index = INTERFACE_B;
123 ftdi_error_return(-1, "Unknown interface");
129 Deinitializes a ftdi_context.
131 \param ftdi pointer to ftdi_context
133 void ftdi_deinit(struct ftdi_context *ftdi)
135 if (ftdi->async_usb_buffer != NULL) {
136 free(ftdi->async_usb_buffer);
137 ftdi->async_usb_buffer = NULL;
140 if (ftdi->readbuffer != NULL) {
141 free(ftdi->readbuffer);
142 ftdi->readbuffer = NULL;
147 Use an already open libusb device.
149 \param ftdi pointer to ftdi_context
150 \param usb libusb usb_dev_handle to use
152 void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
159 Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
160 needs to be deallocated by ftdi_list_free() after use.
162 \param ftdi pointer to ftdi_context
163 \param devlist Pointer where to store list of found devices
164 \param vendor Vendor ID to search for
165 \param product Product ID to search for
167 \retval >0: number of devices found
168 \retval -1: usb_find_busses() failed
169 \retval -2: usb_find_devices() failed
170 \retval -3: out of memory
172 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
174 struct ftdi_device_list **curdev;
176 struct usb_device *dev;
180 if (usb_find_busses() < 0)
181 ftdi_error_return(-1, "usb_find_busses() failed");
182 if (usb_find_devices() < 0)
183 ftdi_error_return(-2, "usb_find_devices() failed");
187 for (bus = usb_busses; bus; bus = bus->next) {
188 for (dev = bus->devices; dev; dev = dev->next) {
189 if (dev->descriptor.idVendor == vendor
190 && dev->descriptor.idProduct == product)
192 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
194 ftdi_error_return(-3, "out of memory");
196 (*curdev)->next = NULL;
197 (*curdev)->dev = dev;
199 curdev = &(*curdev)->next;
209 Frees a usb device list.
211 \param devlist USB device list created by ftdi_usb_find_all()
213 void ftdi_list_free(struct ftdi_device_list **devlist)
215 struct ftdi_device_list *curdev, *next;
217 for (curdev = *devlist; curdev != NULL;) {
227 Return device ID strings from the usb device.
229 The parameters manufacturer, description and serial may be NULL
230 or pointer to buffers to store the fetched strings.
232 \note Use this function only in combination with ftdi_usb_find_all()
233 as it closes the internal "usb_dev" after use.
235 \param ftdi pointer to ftdi_context
236 \param dev libusb usb_dev to use
237 \param manufacturer Store manufacturer string here if not NULL
238 \param mnf_len Buffer size of manufacturer string
239 \param description Store product description string here if not NULL
240 \param desc_len Buffer size of product description string
241 \param serial Store serial string here if not NULL
242 \param serial_len Buffer size of serial string
245 \retval -1: wrong arguments
246 \retval -4: unable to open device
247 \retval -7: get product manufacturer failed
248 \retval -8: get product description failed
249 \retval -9: get serial number failed
250 \retval -10: unable to close device
252 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct usb_device * dev,
253 char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
255 if ((ftdi==NULL) || (dev==NULL))
258 if (!(ftdi->usb_dev = usb_open(dev)))
259 ftdi_error_return(-4, usb_strerror());
261 if (manufacturer != NULL) {
262 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iManufacturer, manufacturer, mnf_len) <= 0) {
263 usb_close (ftdi->usb_dev);
264 ftdi_error_return(-7, usb_strerror());
268 if (description != NULL) {
269 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, description, desc_len) <= 0) {
270 usb_close (ftdi->usb_dev);
271 ftdi_error_return(-8, usb_strerror());
275 if (serial != NULL) {
276 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, serial, serial_len) <= 0) {
277 usb_close (ftdi->usb_dev);
278 ftdi_error_return(-9, usb_strerror());
282 if (usb_close (ftdi->usb_dev) != 0)
283 ftdi_error_return(-10, usb_strerror());
289 Opens a ftdi device given by a usb_device.
291 \param ftdi pointer to ftdi_context
292 \param dev libusb usb_dev to use
295 \retval -4: unable to open device
296 \retval -5: unable to claim device
297 \retval -6: reset failed
298 \retval -7: set baudrate failed
300 int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
302 int detach_errno = 0;
303 if (!(ftdi->usb_dev = usb_open(dev)))
304 ftdi_error_return(-4, "usb_open() failed");
306 #ifdef LIBUSB_HAS_GET_DRIVER_NP
307 // Try to detach ftdi_sio kernel module
308 // Returns ENODATA if driver is not loaded
309 if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
310 detach_errno = errno;
313 if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0) {
314 usb_close (ftdi->usb_dev);
315 if (detach_errno == EPERM) {
316 ftdi_error_return(-8, "inappropriate permissions on device!");
318 ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
322 if (ftdi_usb_reset (ftdi) != 0) {
323 usb_close (ftdi->usb_dev);
324 ftdi_error_return(-6, "ftdi_usb_reset failed");
327 if (ftdi_set_baudrate (ftdi, 9600) != 0) {
328 usb_close (ftdi->usb_dev);
329 ftdi_error_return(-7, "set baudrate failed");
332 // Try to guess chip type
333 // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
334 if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
335 && dev->descriptor.iSerialNumber == 0))
336 ftdi->type = TYPE_BM;
337 else if (dev->descriptor.bcdDevice == 0x200)
338 ftdi->type = TYPE_AM;
339 else if (dev->descriptor.bcdDevice == 0x500) {
340 ftdi->type = TYPE_2232C;
342 ftdi->index = INTERFACE_A;
343 } else if (dev->descriptor.bcdDevice == 0x600)
346 ftdi_error_return(0, "all fine");
350 Opens the first device with a given vendor and product ids.
352 \param ftdi pointer to ftdi_context
353 \param vendor Vendor ID
354 \param product Product ID
356 \retval same as ftdi_usb_open_desc()
358 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
360 return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
364 Opens the first device with a given, vendor id, product id,
365 description and serial.
367 \param ftdi pointer to ftdi_context
368 \param vendor Vendor ID
369 \param product Product ID
370 \param description Description to search for. Use NULL if not needed.
371 \param serial Serial to search for. Use NULL if not needed.
374 \retval -1: usb_find_busses() failed
375 \retval -2: usb_find_devices() failed
376 \retval -3: usb device not found
377 \retval -4: unable to open device
378 \retval -5: unable to claim device
379 \retval -6: reset failed
380 \retval -7: set baudrate failed
381 \retval -8: get product description failed
382 \retval -9: get serial number failed
383 \retval -10: unable to close device
385 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
386 const char* description, const char* serial)
389 struct usb_device *dev;
394 if (usb_find_busses() < 0)
395 ftdi_error_return(-1, "usb_find_busses() failed");
396 if (usb_find_devices() < 0)
397 ftdi_error_return(-2, "usb_find_devices() failed");
399 for (bus = usb_busses; bus; bus = bus->next) {
400 for (dev = bus->devices; dev; dev = dev->next) {
401 if (dev->descriptor.idVendor == vendor
402 && dev->descriptor.idProduct == product) {
403 if (!(ftdi->usb_dev = usb_open(dev)))
404 ftdi_error_return(-4, "usb_open() failed");
406 if (description != NULL) {
407 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0) {
408 usb_close (ftdi->usb_dev);
409 ftdi_error_return(-8, "unable to fetch product description");
411 if (strncmp(string, description, sizeof(string)) != 0) {
412 if (usb_close (ftdi->usb_dev) != 0)
413 ftdi_error_return(-10, "unable to close device");
417 if (serial != NULL) {
418 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0) {
419 usb_close (ftdi->usb_dev);
420 ftdi_error_return(-9, "unable to fetch serial number");
422 if (strncmp(string, serial, sizeof(string)) != 0) {
423 if (usb_close (ftdi->usb_dev) != 0)
424 ftdi_error_return(-10, "unable to close device");
429 if (usb_close (ftdi->usb_dev) != 0)
430 ftdi_error_return(-10, "unable to close device");
432 return ftdi_usb_open_dev(ftdi, dev);
438 ftdi_error_return(-3, "device not found");
442 Resets the ftdi device.
444 \param ftdi pointer to ftdi_context
447 \retval -1: FTDI reset failed
449 int ftdi_usb_reset(struct ftdi_context *ftdi)
451 if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
452 ftdi_error_return(-1,"FTDI reset failed");
454 // Invalidate data in the readbuffer
455 ftdi->readbuffer_offset = 0;
456 ftdi->readbuffer_remaining = 0;
462 Clears the buffers on the chip.
464 \param ftdi pointer to ftdi_context
467 \retval -1: write buffer purge failed
468 \retval -2: read buffer purge failed
470 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
472 if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 1, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
473 ftdi_error_return(-1, "FTDI purge of RX buffer failed");
475 // Invalidate data in the readbuffer
476 ftdi->readbuffer_offset = 0;
477 ftdi->readbuffer_remaining = 0;
479 if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 2, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
480 ftdi_error_return(-2, "FTDI purge of TX buffer failed");
486 Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
488 \param ftdi pointer to ftdi_context
491 \retval -1: usb_release failed
492 \retval -2: usb_close failed
494 int ftdi_usb_close(struct ftdi_context *ftdi)
498 /* try to release some kernel resources */
499 ftdi_async_complete(ftdi,1);
501 if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
504 if (usb_close (ftdi->usb_dev) != 0)
511 ftdi_convert_baudrate returns nearest supported baud rate to that requested.
512 Function is only used internally
515 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
516 unsigned short *value, unsigned short *index)
518 static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
519 static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
520 static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
521 int divisor, best_divisor, best_baud, best_baud_diff;
522 unsigned long encoded_divisor;
530 divisor = 24000000 / baudrate;
532 if (ftdi->type == TYPE_AM) {
533 // Round down to supported fraction (AM only)
534 divisor -= am_adjust_dn[divisor & 7];
537 // Try this divisor and the one above it (because division rounds down)
541 for (i = 0; i < 2; i++) {
542 int try_divisor = divisor + i;
546 // Round up to supported divisor value
547 if (try_divisor <= 8) {
548 // Round up to minimum supported divisor
550 } else if (ftdi->type != TYPE_AM && try_divisor < 12) {
551 // BM doesn't support divisors 9 through 11 inclusive
553 } else if (divisor < 16) {
554 // AM doesn't support divisors 9 through 15 inclusive
557 if (ftdi->type == TYPE_AM) {
558 // Round up to supported fraction (AM only)
559 try_divisor += am_adjust_up[try_divisor & 7];
560 if (try_divisor > 0x1FFF8) {
561 // Round down to maximum supported divisor value (for AM)
562 try_divisor = 0x1FFF8;
565 if (try_divisor > 0x1FFFF) {
566 // Round down to maximum supported divisor value (for BM)
567 try_divisor = 0x1FFFF;
571 // Get estimated baud rate (to nearest integer)
572 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
573 // Get absolute difference from requested baud rate
574 if (baud_estimate < baudrate) {
575 baud_diff = baudrate - baud_estimate;
577 baud_diff = baud_estimate - baudrate;
579 if (i == 0 || baud_diff < best_baud_diff) {
580 // Closest to requested baud rate so far
581 best_divisor = try_divisor;
582 best_baud = baud_estimate;
583 best_baud_diff = baud_diff;
584 if (baud_diff == 0) {
585 // Spot on! No point trying
590 // Encode the best divisor value
591 encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
592 // Deal with special cases for encoded value
593 if (encoded_divisor == 1) {
594 encoded_divisor = 0; // 3000000 baud
595 } else if (encoded_divisor == 0x4001) {
596 encoded_divisor = 1; // 2000000 baud (BM only)
598 // Split into "value" and "index" values
599 *value = (unsigned short)(encoded_divisor & 0xFFFF);
600 if(ftdi->type == TYPE_2232C) {
601 *index = (unsigned short)(encoded_divisor >> 8);
603 *index |= ftdi->index;
606 *index = (unsigned short)(encoded_divisor >> 16);
608 // Return the nearest baud rate
613 Sets the chip baud rate
615 \param ftdi pointer to ftdi_context
616 \param baudrate baud rate to set
619 \retval -1: invalid baudrate
620 \retval -2: setting baudrate failed
622 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
624 unsigned short value, index;
627 if (ftdi->bitbang_enabled) {
628 baudrate = baudrate*4;
631 actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
632 if (actual_baudrate <= 0)
633 ftdi_error_return (-1, "Silly baudrate <= 0.");
635 // Check within tolerance (about 5%)
636 if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
637 || ((actual_baudrate < baudrate)
638 ? (actual_baudrate * 21 < baudrate * 20)
639 : (baudrate * 21 < actual_baudrate * 20)))
640 ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
642 if (usb_control_msg(ftdi->usb_dev, 0x40, 3, value, index, NULL, 0, ftdi->usb_write_timeout) != 0)
643 ftdi_error_return (-2, "Setting new baudrate failed");
645 ftdi->baudrate = baudrate;
650 Set (RS232) line characteristics by Alain Abbas
652 \param ftdi pointer to ftdi_context
653 \param bits Number of bits
654 \param sbit Number of stop bits
655 \param parity Parity mode
658 \retval -1: Setting line property failed
660 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
661 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
663 unsigned short value = bits;
667 value |= (0x00 << 8);
670 value |= (0x01 << 8);
673 value |= (0x02 << 8);
676 value |= (0x03 << 8);
679 value |= (0x04 << 8);
685 value |= (0x00 << 11);
688 value |= (0x01 << 11);
691 value |= (0x02 << 11);
695 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x04, value, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
696 ftdi_error_return (-1, "Setting new line property failed");
702 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
704 \param ftdi pointer to ftdi_context
705 \param buf Buffer with the data
706 \param size Size of the buffer
708 \retval <0: error code from usb_bulk_write()
709 \retval >0: number of bytes written
711 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
715 int total_written = 0;
717 while (offset < size) {
718 int write_size = ftdi->writebuffer_chunksize;
720 if (offset+write_size > size)
721 write_size = size-offset;
723 ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
725 ftdi_error_return(ret, "usb bulk write failed");
727 total_written += ret;
728 offset += write_size;
731 return total_written;
734 /* this is strongly dependent on libusb using the same struct layout. If libusb
735 changes in some later version this may break horribly (this is for libusb 0.1.12) */
736 struct usb_dev_handle {
738 // some other stuff coming here we don't need
742 Check for pending async urbs
745 static int _usb_get_async_urbs_pending(struct ftdi_context *ftdi)
747 struct usbdevfs_urb *urb;
751 for (i=0; i < ftdi->async_usb_buffer_size; i++) {
752 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
753 if (urb->usercontext != FTDI_URB_USERCONTEXT_COOKIE)
761 Wait until one or more async URBs are completed by the kernel and mark their
762 positions in the async-buffer as unused
764 \param ftdi pointer to ftdi_context
765 \param wait_for_more if != 0 wait for more than one write to complete
766 \param timeout_msec max milliseconds to wait
770 static void _usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
773 struct usbdevfs_urb *urb=NULL;
779 FD_SET(ftdi->usb_dev->fd, &writefds);
781 /* init timeout only once, select writes time left after call */
782 tv.tv_sec = timeout_msec / 1000;
783 tv.tv_usec = (timeout_msec % 1000) * 1000;
786 while (_usb_get_async_urbs_pending(ftdi)
787 && (ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_REAPURBNDELAY, &urb)) == -1
790 if (keep_going && !wait_for_more) {
791 /* don't wait if repeating only for keep_going */
796 /* wait for timeout msec or something written ready */
797 select(ftdi->usb_dev->fd+1, NULL, &writefds, NULL, &tv);
800 if (ret == 0 && urb != NULL) {
801 /* got a free urb, mark it */
802 urb->usercontext = FTDI_URB_USERCONTEXT_COOKIE;
804 /* try to get more urbs that are ready now, but don't wait anymore */
808 /* no more urbs waiting */
811 } while (keep_going);
815 Wait until one or more async URBs are completed by the kernel and mark their
816 positions in the async-buffer as unused.
818 \param ftdi pointer to ftdi_context
819 \param wait_for_more if != 0 wait for more than one write to complete (until write timeout)
821 void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
823 _usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
827 Stupid libusb does not offer async writes nor does it allow
828 access to its fd - so we need some hacks here.
831 static int _usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
833 struct usbdevfs_urb *urb;
834 int bytesdone = 0, requested;
839 /* find a free urb buffer we can use */
841 for (cleanup_count=0; urb==NULL && cleanup_count <= 1; cleanup_count++)
843 if (i==ftdi->async_usb_buffer_size) {
844 /* wait until some buffers are free */
845 _usb_async_cleanup(ftdi,0,ftdi->usb_write_timeout);
848 for (i=0; i < ftdi->async_usb_buffer_size; i++) {
849 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
850 if (urb->usercontext == FTDI_URB_USERCONTEXT_COOKIE)
851 break; /* found a free urb position */
856 /* no free urb position found */
860 requested = size - bytesdone;
861 if (requested > 4096)
864 memset(urb,0,sizeof(urb));
866 urb->type = USBDEVFS_URB_TYPE_BULK;
869 urb->buffer = bytes + bytesdone;
870 urb->buffer_length = requested;
872 urb->actual_length = 0;
873 urb->number_of_packets = 0;
874 urb->usercontext = 0;
877 ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_SUBMITURB, urb);
878 } while (ret < 0 && errno == EINTR);
880 return ret; /* the caller can read errno to get more info */
882 bytesdone += requested;
883 } while (bytesdone < size);
888 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip.
889 Does not wait for completion of the transfer nor does it make sure that
890 the transfer was successful.
892 This function could be extended to use signals and callbacks to inform the
893 caller of completion or error - but this is not done yet, volunteers welcome.
895 Works around libusb and directly accesses functions only available on Linux.
897 \param ftdi pointer to ftdi_context
898 \param buf Buffer with the data
899 \param size Size of the buffer
901 \retval <0: error code from usb_bulk_write()
902 \retval >0: number of bytes written
904 int ftdi_write_data_async(struct ftdi_context *ftdi, unsigned char *buf, int size)
908 int total_written = 0;
910 while (offset < size) {
911 int write_size = ftdi->writebuffer_chunksize;
913 if (offset+write_size > size)
914 write_size = size-offset;
916 ret = _usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
918 ftdi_error_return(ret, "usb bulk write async failed");
920 total_written += ret;
921 offset += write_size;
924 return total_written;
929 Configure write buffer chunk size.
932 \param ftdi pointer to ftdi_context
933 \param chunksize Chunk size
937 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
939 ftdi->writebuffer_chunksize = chunksize;
944 Get write buffer chunk size.
946 \param ftdi pointer to ftdi_context
947 \param chunksize Pointer to store chunk size in
951 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
953 *chunksize = ftdi->writebuffer_chunksize;
958 Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
960 Automatically strips the two modem status bytes transfered during every read.
962 \param ftdi pointer to ftdi_context
963 \param buf Buffer to store data in
964 \param size Size of the buffer
966 \retval <0: error code from usb_bulk_read()
967 \retval 0: no data was available
968 \retval >0: number of bytes read
970 \remark This function is not useful in bitbang mode.
971 Use ftdi_read_pins() to get the current state of the pins.
973 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
975 int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
977 // everything we want is still in the readbuffer?
978 if (size <= ftdi->readbuffer_remaining) {
979 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
982 ftdi->readbuffer_remaining -= size;
983 ftdi->readbuffer_offset += size;
985 /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
989 // something still in the readbuffer, but not enough to satisfy 'size'?
990 if (ftdi->readbuffer_remaining != 0) {
991 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
994 offset += ftdi->readbuffer_remaining;
996 // do the actual USB read
997 while (offset < size && ret > 0) {
998 ftdi->readbuffer_remaining = 0;
999 ftdi->readbuffer_offset = 0;
1000 /* returns how much received */
1001 ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
1003 ftdi_error_return(ret, "usb bulk read failed");
1006 // skip FTDI status bytes.
1007 // Maybe stored in the future to enable modem use
1008 num_of_chunks = ret / 64;
1009 chunk_remains = ret % 64;
1010 //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1012 ftdi->readbuffer_offset += 2;
1016 for (i = 1; i < num_of_chunks; i++)
1017 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
1018 ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
1020 if (chunk_remains > 2) {
1021 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
1022 ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
1024 ret -= 2*num_of_chunks;
1026 ret -= 2*(num_of_chunks-1)+chunk_remains;
1028 } else if (ret <= 2) {
1029 // no more data to read?
1033 // data still fits in buf?
1034 if (offset+ret <= size) {
1035 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
1036 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1039 /* Did we read exactly the right amount of bytes? */
1041 //printf("read_data exact rem %d offset %d\n",
1042 //ftdi->readbuffer_remaining, offset);
1045 // only copy part of the data or size <= readbuffer_chunksize
1046 int part_size = size-offset;
1047 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1049 ftdi->readbuffer_offset += part_size;
1050 ftdi->readbuffer_remaining = ret-part_size;
1051 offset += part_size;
1053 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
1054 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
1065 Configure read buffer chunk size.
1068 Automatically reallocates the buffer.
1070 \param ftdi pointer to ftdi_context
1071 \param chunksize Chunk size
1075 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1077 unsigned char *new_buf;
1079 // Invalidate all remaining data
1080 ftdi->readbuffer_offset = 0;
1081 ftdi->readbuffer_remaining = 0;
1083 if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1084 ftdi_error_return(-1, "out of memory for readbuffer");
1086 ftdi->readbuffer = new_buf;
1087 ftdi->readbuffer_chunksize = chunksize;
1093 Get read buffer chunk size.
1095 \param ftdi pointer to ftdi_context
1096 \param chunksize Pointer to store chunk size in
1100 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1102 *chunksize = ftdi->readbuffer_chunksize;
1108 Enable bitbang mode.
1110 For advanced bitbang modes of the FT2232C chip use ftdi_set_bitmode().
1112 \param ftdi pointer to ftdi_context
1113 \param bitmask Bitmask to configure lines.
1114 HIGH/ON value configures a line as output.
1117 \retval -1: can't enable bitbang mode
1119 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1121 unsigned short usb_val;
1123 usb_val = bitmask; // low byte: bitmask
1124 /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1125 usb_val |= (ftdi->bitbang_mode << 8);
1127 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1128 ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1130 ftdi->bitbang_enabled = 1;
1135 Disable bitbang mode.
1137 \param ftdi pointer to ftdi_context
1140 \retval -1: can't disable bitbang mode
1142 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1144 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1145 ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1147 ftdi->bitbang_enabled = 0;
1152 Enable advanced bitbang mode for FT2232C chips.
1154 \param ftdi pointer to ftdi_context
1155 \param bitmask Bitmask to configure lines.
1156 HIGH/ON value configures a line as output.
1157 \param mode Bitbang mode: 1 for normal mode, 2 for SPI mode
1160 \retval -1: can't enable bitbang mode
1162 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1164 unsigned short usb_val;
1166 usb_val = bitmask; // low byte: bitmask
1167 usb_val |= (mode << 8);
1168 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1169 ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1171 ftdi->bitbang_mode = mode;
1172 ftdi->bitbang_enabled = (mode == BITMODE_BITBANG || mode == BITMODE_SYNCBB)?1:0;
1177 Directly read pin state. Useful for bitbang mode.
1179 \param ftdi pointer to ftdi_context
1180 \param pins Pointer to store pins into
1183 \retval -1: read pins failed
1185 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1187 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0C, 0, ftdi->index, (char *)pins, 1, ftdi->usb_read_timeout) != 1)
1188 ftdi_error_return(-1, "read pins failed");
1196 The FTDI chip keeps data in the internal buffer for a specific
1197 amount of time if the buffer is not full yet to decrease
1198 load on the usb bus.
1200 \param ftdi pointer to ftdi_context
1201 \param latency Value between 1 and 255
1204 \retval -1: latency out of range
1205 \retval -2: unable to set latency timer
1207 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1209 unsigned short usb_val;
1212 ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
1215 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x09, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1216 ftdi_error_return(-2, "unable to set latency timer");
1224 \param ftdi pointer to ftdi_context
1225 \param latency Pointer to store latency value in
1228 \retval -1: unable to get latency timer
1230 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1232 unsigned short usb_val;
1233 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0A, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
1234 ftdi_error_return(-1, "reading latency timer failed");
1236 *latency = (unsigned char)usb_val;
1243 \param ftdi pointer to ftdi_context
1244 \param eeprom Pointer to ftdi_eeprom
1248 void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
1250 ftdi->eeprom_size=size;
1255 Init eeprom with default values.
1257 \param eeprom Pointer to ftdi_eeprom
1259 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
1261 eeprom->vendor_id = 0x0403;
1262 eeprom->product_id = 0x6001;
1264 eeprom->self_powered = 1;
1265 eeprom->remote_wakeup = 1;
1266 eeprom->BM_type_chip = 1;
1268 eeprom->in_is_isochronous = 0;
1269 eeprom->out_is_isochronous = 0;
1270 eeprom->suspend_pull_downs = 0;
1272 eeprom->use_serial = 0;
1273 eeprom->change_usb_version = 0;
1274 eeprom->usb_version = 0x0200;
1275 eeprom->max_power = 0;
1277 eeprom->manufacturer = NULL;
1278 eeprom->product = NULL;
1279 eeprom->serial = NULL;
1281 eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
1285 Build binary output from ftdi_eeprom structure.
1286 Output is suitable for ftdi_write_eeprom().
1288 \param eeprom Pointer to ftdi_eeprom
1289 \param output Buffer of 128 bytes to store eeprom image to
1291 \retval >0: used eeprom size
1292 \retval -1: eeprom size (128 bytes) exceeded by custom strings
1294 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
1297 unsigned short checksum, value;
1298 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
1301 if (eeprom->manufacturer != NULL)
1302 manufacturer_size = strlen(eeprom->manufacturer);
1303 if (eeprom->product != NULL)
1304 product_size = strlen(eeprom->product);
1305 if (eeprom->serial != NULL)
1306 serial_size = strlen(eeprom->serial);
1308 size_check = eeprom->size;
1309 size_check -= 28; // 28 are always in use (fixed)
1311 // Top half of a 256byte eeprom is used just for strings and checksum
1312 // it seems that the FTDI chip will not read these strings from the lower half
1313 // Each string starts with two bytes; offset and type (0x03 for string)
1314 // the checksum needs two bytes, so without the string data that 8 bytes from the top half
1315 if(eeprom->size>=256)size_check = 120;
1316 size_check -= manufacturer_size*2;
1317 size_check -= product_size*2;
1318 size_check -= serial_size*2;
1320 // eeprom size exceeded?
1325 memset (output, 0, eeprom->size);
1327 // Addr 00: Stay 00 00
1328 // Addr 02: Vendor ID
1329 output[0x02] = eeprom->vendor_id;
1330 output[0x03] = eeprom->vendor_id >> 8;
1332 // Addr 04: Product ID
1333 output[0x04] = eeprom->product_id;
1334 output[0x05] = eeprom->product_id >> 8;
1336 // Addr 06: Device release number (0400h for BM features)
1337 output[0x06] = 0x00;
1339 if (eeprom->BM_type_chip == 1)
1340 output[0x07] = 0x04;
1342 output[0x07] = 0x02;
1344 // Addr 08: Config descriptor
1345 // Bit 1: remote wakeup if 1
1346 // Bit 0: self powered if 1
1349 if (eeprom->self_powered == 1)
1351 if (eeprom->remote_wakeup == 1)
1355 // Addr 09: Max power consumption: max power = value * 2 mA
1356 output[0x09] = eeprom->max_power;
1359 // Addr 0A: Chip configuration
1360 // Bit 7: 0 - reserved
1361 // Bit 6: 0 - reserved
1362 // Bit 5: 0 - reserved
1363 // Bit 4: 1 - Change USB version
1364 // Bit 3: 1 - Use the serial number string
1365 // Bit 2: 1 - Enable suspend pull downs for lower power
1366 // Bit 1: 1 - Out EndPoint is Isochronous
1367 // Bit 0: 1 - In EndPoint is Isochronous
1370 if (eeprom->in_is_isochronous == 1)
1372 if (eeprom->out_is_isochronous == 1)
1374 if (eeprom->suspend_pull_downs == 1)
1376 if (eeprom->use_serial == 1)
1378 if (eeprom->change_usb_version == 1)
1382 // Addr 0B: reserved
1383 output[0x0B] = 0x00;
1385 // Addr 0C: USB version low byte when 0x0A bit 4 is set
1386 // Addr 0D: USB version high byte when 0x0A bit 4 is set
1387 if (eeprom->change_usb_version == 1) {
1388 output[0x0C] = eeprom->usb_version;
1389 output[0x0D] = eeprom->usb_version >> 8;
1393 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
1394 // Addr 0F: Length of manufacturer string
1395 output[0x0F] = manufacturer_size*2 + 2;
1397 // Addr 10: Offset of the product string + 0x80, calculated later
1398 // Addr 11: Length of product string
1399 output[0x11] = product_size*2 + 2;
1401 // Addr 12: Offset of the serial string + 0x80, calculated later
1402 // Addr 13: Length of serial string
1403 output[0x13] = serial_size*2 + 2;
1407 if(eeprom->size>=256) i = 0x80;
1410 // Output manufacturer
1411 output[0x0E] = i | 0x80; // calculate offset
1412 output[i++] = manufacturer_size*2 + 2;
1413 output[i++] = 0x03; // type: string
1414 for (j = 0; j < manufacturer_size; j++) {
1415 output[i] = eeprom->manufacturer[j], i++;
1416 output[i] = 0x00, i++;
1419 // Output product name
1420 output[0x10] = i | 0x80; // calculate offset
1421 output[i] = product_size*2 + 2, i++;
1422 output[i] = 0x03, i++;
1423 for (j = 0; j < product_size; j++) {
1424 output[i] = eeprom->product[j], i++;
1425 output[i] = 0x00, i++;
1429 output[0x12] = i | 0x80; // calculate offset
1430 output[i] = serial_size*2 + 2, i++;
1431 output[i] = 0x03, i++;
1432 for (j = 0; j < serial_size; j++) {
1433 output[i] = eeprom->serial[j], i++;
1434 output[i] = 0x00, i++;
1437 // calculate checksum
1440 for (i = 0; i < eeprom->size/2-1; i++) {
1441 value = output[i*2];
1442 value += output[(i*2)+1] << 8;
1444 checksum = value^checksum;
1445 checksum = (checksum << 1) | (checksum >> 15);
1448 output[eeprom->size-2] = checksum;
1449 output[eeprom->size-1] = checksum >> 8;
1457 \param ftdi pointer to ftdi_context
1458 \param eeprom Pointer to store eeprom into
1461 \retval -1: read failed
1463 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
1467 for (i = 0; i < ftdi->eeprom_size/2; i++) {
1468 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
1469 ftdi_error_return(-1, "reading eeprom failed");
1476 ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
1477 Function is only used internally
1480 static unsigned char ftdi_read_chipid_shift(unsigned char value)
1482 return ((value & 1) << 1) |
1483 ((value & 2) << 5) |
1484 ((value & 4) >> 2) |
1485 ((value & 8) << 4) |
1486 ((value & 16) >> 1) |
1487 ((value & 32) >> 1) |
1488 ((value & 64) >> 4) |
1489 ((value & 128) >> 2);
1493 Read the FTDIChip-ID from R-type devices
1495 \param ftdi pointer to ftdi_context
1496 \param chipid Pointer to store FTDIChip-ID
1499 \retval -1: read failed
1501 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
1503 unsigned int a = 0, b = 0;
1505 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, 0x43, (char *)&a, 2, ftdi->usb_read_timeout) == 2)
1507 a = a << 8 | a >> 8;
1508 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, 0x44, (char *)&b, 2, ftdi->usb_read_timeout) == 2)
1510 b = b << 8 | b >> 8;
1512 a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
1513 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
1514 *chipid = a ^ 0xa5f0f7d1;
1519 ftdi_error_return(-1, "read of FTDIChip-ID failed");
1523 Guesses size of eeprom by reading eeprom and comparing halves - will not work with blank eeprom
1524 Call this function then do a write then call again to see if size changes, if so write again.
1526 \param ftdi pointer to ftdi_context
1527 \param eeprom Pointer to store eeprom into
1528 \param maxsize the size of the buffer to read into
1530 \retval size of eeprom
1532 int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
1534 int i=0,j,minsize=32;
1538 for (j = 0; i < maxsize/2 && j<size; j++) {
1539 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
1540 ftdi_error_return(-1, "reading eeprom failed");
1544 }while(size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
1552 \param ftdi pointer to ftdi_context
1553 \param eeprom Pointer to read eeprom from
1556 \retval -1: read failed
1558 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
1560 unsigned short usb_val;
1563 for (i = 0; i < ftdi->eeprom_size/2; i++) {
1564 usb_val = eeprom[i*2];
1565 usb_val += eeprom[(i*2)+1] << 8;
1566 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x91, usb_val, i, NULL, 0, ftdi->usb_write_timeout) != 0)
1567 ftdi_error_return(-1, "unable to write eeprom");
1576 \param ftdi pointer to ftdi_context
1579 \retval -1: erase failed
1581 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
1583 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x92, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
1584 ftdi_error_return(-1, "unable to erase eeprom");
1590 Get string representation for last error code
1592 \param ftdi pointer to ftdi_context
1594 \retval Pointer to error string
1596 char *ftdi_get_error_string (struct ftdi_context *ftdi)
1598 return ftdi->error_str;
1602 Flow control code by Lorenz Moesenlechner (lorenz@hcilab.org)
1603 and Matthias Kranz (matthias@hcilab.org)
1606 Set flowcontrol for ftdi chip
1608 \param ftdi pointer to ftdi_context
1609 \param flowctrl flow control to use. should be
1610 SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
1613 \retval -1: set flow control failed
1615 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1617 if (usb_control_msg(ftdi->usb_dev, SIO_SET_FLOW_CTRL_REQUEST_TYPE,
1618 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->interface),
1619 NULL, 0, ftdi->usb_write_timeout) != 0)
1620 ftdi_error_return(-1, "set flow control failed");
1628 \param ftdi pointer to ftdi_context
1629 \param state state to set line to (1 or 0)
1632 \retval -1: set dtr failed
1634 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
1636 unsigned short usb_val;
1639 usb_val = SIO_SET_DTR_HIGH;
1641 usb_val = SIO_SET_DTR_LOW;
1643 if (usb_control_msg(ftdi->usb_dev, SIO_SET_MODEM_CTRL_REQUEST_TYPE,
1644 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->interface,
1645 NULL, 0, ftdi->usb_write_timeout) != 0)
1646 ftdi_error_return(-1, "set dtr failed");
1654 \param ftdi pointer to ftdi_context
1655 \param state state to set line to (1 or 0)
1658 \retval -1 set rts failed
1660 int ftdi_setrts(struct ftdi_context *ftdi, int state)
1662 unsigned short usb_val;
1665 usb_val = SIO_SET_RTS_HIGH;
1667 usb_val = SIO_SET_RTS_LOW;
1669 if (usb_control_msg(ftdi->usb_dev, SIO_SET_MODEM_CTRL_REQUEST_TYPE,
1670 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->interface,
1671 NULL, 0, ftdi->usb_write_timeout) != 0)
1672 ftdi_error_return(-1, "set of rts failed");
1677 /* @} end of doxygen libftdi group */