1 /***************************************************************************
5 copyright : (C) 2003 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 /* All fine. Now allocate the readbuffer */
95 return ftdi_read_data_set_chunksize(ftdi, 4096);
99 Open selected channels on a chip, otherwise use first channel.
101 \param ftdi pointer to ftdi_context
102 \param interface Interface to use for FT2232C chips.
105 \retval -1: unknown interface
107 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
112 /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
116 ftdi->index = INTERFACE_B;
121 ftdi_error_return(-1, "Unknown interface");
127 Deinitializes a ftdi_context.
129 \param ftdi pointer to ftdi_context
131 void ftdi_deinit(struct ftdi_context *ftdi)
133 if (ftdi->async_usb_buffer != NULL) {
134 free(ftdi->async_usb_buffer);
135 ftdi->async_usb_buffer = NULL;
138 if (ftdi->readbuffer != NULL) {
139 free(ftdi->readbuffer);
140 ftdi->readbuffer = NULL;
145 Use an already open libusb device.
147 \param ftdi pointer to ftdi_context
148 \param usb libusb usb_dev_handle to use
150 void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
157 Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
158 needs to be deallocated by ftdi_list_free() after use.
160 \param ftdi pointer to ftdi_context
161 \param devlist Pointer where to store list of found devices
162 \param vendor Vendor ID to search for
163 \param product Product ID to search for
165 \retval >0: number of devices found
166 \retval -1: usb_find_busses() failed
167 \retval -2: usb_find_devices() failed
168 \retval -3: out of memory
170 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
172 struct ftdi_device_list **curdev;
174 struct usb_device *dev;
178 if (usb_find_busses() < 0)
179 ftdi_error_return(-1, "usb_find_busses() failed");
180 if (usb_find_devices() < 0)
181 ftdi_error_return(-2, "usb_find_devices() failed");
185 for (bus = usb_busses; bus; bus = bus->next) {
186 for (dev = bus->devices; dev; dev = dev->next) {
187 if (dev->descriptor.idVendor == vendor
188 && dev->descriptor.idProduct == product)
190 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
192 ftdi_error_return(-3, "out of memory");
194 (*curdev)->next = NULL;
195 (*curdev)->dev = dev;
197 curdev = &(*curdev)->next;
207 Frees a usb device list.
209 \param devlist USB device list created by ftdi_usb_find_all()
211 void ftdi_list_free(struct ftdi_device_list **devlist)
213 struct ftdi_device_list *curdev, *next;
215 for (curdev = *devlist; curdev != NULL;) {
225 Return device ID strings from the usb device.
227 The parameters manufacturer, description and serial may be NULL
228 or pointer to buffers to store the fetched strings.
230 \note Use this function only in combination with ftdi_usb_find_all()
231 as it closes the internal "usb_dev" after use.
233 \param ftdi pointer to ftdi_context
234 \param dev libusb usb_dev to use
235 \param manufacturer Store manufacturer string here if not NULL
236 \param mnf_len Buffer size of manufacturer string
237 \param description Store product description string here if not NULL
238 \param desc_len Buffer size of product description string
239 \param serial Store serial string here if not NULL
240 \param serial_len Buffer size of serial string
243 \retval -1: wrong arguments
244 \retval -4: unable to open device
245 \retval -7: get product manufacturer failed
246 \retval -8: get product description failed
247 \retval -9: get serial number failed
248 \retval -10: unable to close device
250 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct usb_device * dev,
251 char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
253 if ((ftdi==NULL) || (dev==NULL))
256 if (!(ftdi->usb_dev = usb_open(dev)))
257 ftdi_error_return(-4, usb_strerror());
259 if (manufacturer != NULL) {
260 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iManufacturer, manufacturer, mnf_len) <= 0) {
261 usb_close (ftdi->usb_dev);
262 ftdi_error_return(-7, usb_strerror());
266 if (description != NULL) {
267 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, description, desc_len) <= 0) {
268 usb_close (ftdi->usb_dev);
269 ftdi_error_return(-8, usb_strerror());
273 if (serial != NULL) {
274 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, serial, serial_len) <= 0) {
275 usb_close (ftdi->usb_dev);
276 ftdi_error_return(-9, usb_strerror());
280 if (usb_close (ftdi->usb_dev) != 0)
281 ftdi_error_return(-10, usb_strerror());
287 Opens a ftdi device given by a usb_device.
289 \param ftdi pointer to ftdi_context
290 \param dev libusb usb_dev to use
293 \retval -4: unable to open device
294 \retval -5: unable to claim device
295 \retval -6: reset failed
296 \retval -7: set baudrate failed
298 int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
300 int detach_errno = 0;
301 if (!(ftdi->usb_dev = usb_open(dev)))
302 ftdi_error_return(-4, "usb_open() failed");
304 #ifdef LIBUSB_HAS_GET_DRIVER_NP
305 // Try to detach ftdi_sio kernel module
306 // Returns ENODATA if driver is not loaded
307 if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
308 detach_errno = errno;
311 if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0) {
312 usb_close (ftdi->usb_dev);
313 if (detach_errno == EPERM) {
314 ftdi_error_return(-8, "inappropriate permissions on device!");
316 ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
320 if (ftdi_usb_reset (ftdi) != 0) {
321 usb_close (ftdi->usb_dev);
322 ftdi_error_return(-6, "ftdi_usb_reset failed");
325 if (ftdi_set_baudrate (ftdi, 9600) != 0) {
326 usb_close (ftdi->usb_dev);
327 ftdi_error_return(-7, "set baudrate failed");
330 // Try to guess chip type
331 // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
332 if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
333 && dev->descriptor.iSerialNumber == 0))
334 ftdi->type = TYPE_BM;
335 else if (dev->descriptor.bcdDevice == 0x200)
336 ftdi->type = TYPE_AM;
337 else if (dev->descriptor.bcdDevice == 0x500) {
338 ftdi->type = TYPE_2232C;
340 ftdi->index = INTERFACE_A;
341 } else if (dev->descriptor.bcdDevice == 0x600)
344 ftdi_error_return(0, "all fine");
348 Opens the first device with a given vendor and product ids.
350 \param ftdi pointer to ftdi_context
351 \param vendor Vendor ID
352 \param product Product ID
354 \retval same as ftdi_usb_open_desc()
356 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
358 return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
362 Opens the first device with a given, vendor id, product id,
363 description and serial.
365 \param ftdi pointer to ftdi_context
366 \param vendor Vendor ID
367 \param product Product ID
368 \param description Description to search for. Use NULL if not needed.
369 \param serial Serial to search for. Use NULL if not needed.
372 \retval -1: usb_find_busses() failed
373 \retval -2: usb_find_devices() failed
374 \retval -3: usb device not found
375 \retval -4: unable to open device
376 \retval -5: unable to claim device
377 \retval -6: reset failed
378 \retval -7: set baudrate failed
379 \retval -8: get product description failed
380 \retval -9: get serial number failed
381 \retval -10: unable to close device
383 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
384 const char* description, const char* serial)
387 struct usb_device *dev;
392 if (usb_find_busses() < 0)
393 ftdi_error_return(-1, "usb_find_busses() failed");
394 if (usb_find_devices() < 0)
395 ftdi_error_return(-2, "usb_find_devices() failed");
397 for (bus = usb_busses; bus; bus = bus->next) {
398 for (dev = bus->devices; dev; dev = dev->next) {
399 if (dev->descriptor.idVendor == vendor
400 && dev->descriptor.idProduct == product) {
401 if (!(ftdi->usb_dev = usb_open(dev)))
402 ftdi_error_return(-4, "usb_open() failed");
404 if (description != NULL) {
405 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0) {
406 usb_close (ftdi->usb_dev);
407 ftdi_error_return(-8, "unable to fetch product description");
409 if (strncmp(string, description, sizeof(string)) != 0) {
410 if (usb_close (ftdi->usb_dev) != 0)
411 ftdi_error_return(-10, "unable to close device");
415 if (serial != NULL) {
416 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0) {
417 usb_close (ftdi->usb_dev);
418 ftdi_error_return(-9, "unable to fetch serial number");
420 if (strncmp(string, serial, sizeof(string)) != 0) {
421 if (usb_close (ftdi->usb_dev) != 0)
422 ftdi_error_return(-10, "unable to close device");
427 if (usb_close (ftdi->usb_dev) != 0)
428 ftdi_error_return(-10, "unable to close device");
430 return ftdi_usb_open_dev(ftdi, dev);
436 ftdi_error_return(-3, "device not found");
440 Resets the ftdi device.
442 \param ftdi pointer to ftdi_context
445 \retval -1: FTDI reset failed
447 int ftdi_usb_reset(struct ftdi_context *ftdi)
449 if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
450 ftdi_error_return(-1,"FTDI reset failed");
452 // Invalidate data in the readbuffer
453 ftdi->readbuffer_offset = 0;
454 ftdi->readbuffer_remaining = 0;
460 Clears the buffers on the chip.
462 \param ftdi pointer to ftdi_context
465 \retval -1: write buffer purge failed
466 \retval -2: read buffer purge failed
468 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
470 if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 1, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
471 ftdi_error_return(-1, "FTDI purge of RX buffer failed");
473 // Invalidate data in the readbuffer
474 ftdi->readbuffer_offset = 0;
475 ftdi->readbuffer_remaining = 0;
477 if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 2, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
478 ftdi_error_return(-2, "FTDI purge of TX buffer failed");
484 Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
486 \param ftdi pointer to ftdi_context
489 \retval -1: usb_release failed
490 \retval -2: usb_close failed
492 int ftdi_usb_close(struct ftdi_context *ftdi)
496 /* try to release some kernel resources */
497 ftdi_async_complete(ftdi,1);
499 if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
502 if (usb_close (ftdi->usb_dev) != 0)
509 ftdi_convert_baudrate returns nearest supported baud rate to that requested.
510 Function is only used internally
513 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
514 unsigned short *value, unsigned short *index)
516 static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
517 static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
518 static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
519 int divisor, best_divisor, best_baud, best_baud_diff;
520 unsigned long encoded_divisor;
528 divisor = 24000000 / baudrate;
530 if (ftdi->type == TYPE_AM) {
531 // Round down to supported fraction (AM only)
532 divisor -= am_adjust_dn[divisor & 7];
535 // Try this divisor and the one above it (because division rounds down)
539 for (i = 0; i < 2; i++) {
540 int try_divisor = divisor + i;
544 // Round up to supported divisor value
545 if (try_divisor <= 8) {
546 // Round up to minimum supported divisor
548 } else if (ftdi->type != TYPE_AM && try_divisor < 12) {
549 // BM doesn't support divisors 9 through 11 inclusive
551 } else if (divisor < 16) {
552 // AM doesn't support divisors 9 through 15 inclusive
555 if (ftdi->type == TYPE_AM) {
556 // Round up to supported fraction (AM only)
557 try_divisor += am_adjust_up[try_divisor & 7];
558 if (try_divisor > 0x1FFF8) {
559 // Round down to maximum supported divisor value (for AM)
560 try_divisor = 0x1FFF8;
563 if (try_divisor > 0x1FFFF) {
564 // Round down to maximum supported divisor value (for BM)
565 try_divisor = 0x1FFFF;
569 // Get estimated baud rate (to nearest integer)
570 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
571 // Get absolute difference from requested baud rate
572 if (baud_estimate < baudrate) {
573 baud_diff = baudrate - baud_estimate;
575 baud_diff = baud_estimate - baudrate;
577 if (i == 0 || baud_diff < best_baud_diff) {
578 // Closest to requested baud rate so far
579 best_divisor = try_divisor;
580 best_baud = baud_estimate;
581 best_baud_diff = baud_diff;
582 if (baud_diff == 0) {
583 // Spot on! No point trying
588 // Encode the best divisor value
589 encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
590 // Deal with special cases for encoded value
591 if (encoded_divisor == 1) {
592 encoded_divisor = 0; // 3000000 baud
593 } else if (encoded_divisor == 0x4001) {
594 encoded_divisor = 1; // 2000000 baud (BM only)
596 // Split into "value" and "index" values
597 *value = (unsigned short)(encoded_divisor & 0xFFFF);
598 if(ftdi->type == TYPE_2232C) {
599 *index = (unsigned short)(encoded_divisor >> 8);
601 *index |= ftdi->index;
604 *index = (unsigned short)(encoded_divisor >> 16);
606 // Return the nearest baud rate
611 Sets the chip baud rate
613 \param ftdi pointer to ftdi_context
614 \param baudrate baud rate to set
617 \retval -1: invalid baudrate
618 \retval -2: setting baudrate failed
620 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
622 unsigned short value, index;
625 if (ftdi->bitbang_enabled) {
626 baudrate = baudrate*4;
629 actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
630 if (actual_baudrate <= 0)
631 ftdi_error_return (-1, "Silly baudrate <= 0.");
633 // Check within tolerance (about 5%)
634 if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
635 || ((actual_baudrate < baudrate)
636 ? (actual_baudrate * 21 < baudrate * 20)
637 : (baudrate * 21 < actual_baudrate * 20)))
638 ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
640 if (usb_control_msg(ftdi->usb_dev, 0x40, 3, value, index, NULL, 0, ftdi->usb_write_timeout) != 0)
641 ftdi_error_return (-2, "Setting new baudrate failed");
643 ftdi->baudrate = baudrate;
648 Set (RS232) line characteristics by Alain Abbas
650 \param ftdi pointer to ftdi_context
651 \param bits Number of bits
652 \param sbit Number of stop bits
653 \param parity Parity mode
656 \retval -1: Setting line property failed
658 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
659 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
661 unsigned short value = bits;
665 value |= (0x00 << 8);
668 value |= (0x01 << 8);
671 value |= (0x02 << 8);
674 value |= (0x03 << 8);
677 value |= (0x04 << 8);
683 value |= (0x00 << 11);
686 value |= (0x01 << 11);
689 value |= (0x02 << 11);
693 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x04, value, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
694 ftdi_error_return (-1, "Setting new line property failed");
700 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
702 \param ftdi pointer to ftdi_context
703 \param buf Buffer with the data
704 \param size Size of the buffer
706 \retval <0: error code from usb_bulk_write()
707 \retval >0: number of bytes written
709 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
713 int total_written = 0;
715 while (offset < size) {
716 int write_size = ftdi->writebuffer_chunksize;
718 if (offset+write_size > size)
719 write_size = size-offset;
721 ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
723 ftdi_error_return(ret, "usb bulk write failed");
725 total_written += ret;
726 offset += write_size;
729 return total_written;
732 /* this is strongly dependent on libusb using the same struct layout. If libusb
733 changes in some later version this may break horribly (this is for libusb 0.1.12) */
734 struct usb_dev_handle {
736 // some other stuff coming here we don't need
739 static int usb_get_async_urbs_pending(struct ftdi_context *ftdi)
741 struct usbdevfs_urb *urb;
745 for (i=0; i < ftdi->async_usb_buffer_size; i++) {
746 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
747 if (urb->usercontext != FTDI_URB_USERCONTEXT_COOKIE)
754 static void usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
757 struct usbdevfs_urb *urb=NULL;
763 FD_SET(ftdi->usb_dev->fd, &writefds);
765 /* init timeout only once, select writes time left after call */
766 tv.tv_sec = timeout_msec / 1000;
767 tv.tv_usec = (timeout_msec % 1000) * 1000;
770 while (usb_get_async_urbs_pending(ftdi)
771 && (ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_REAPURBNDELAY, &urb)) == -1
774 if (keep_going && !wait_for_more) {
775 /* don't wait if repeating only for keep_going */
780 /* wait for timeout msec or something written ready */
781 select(ftdi->usb_dev->fd+1, NULL, &writefds, NULL, &tv);
784 if (ret == 0 && urb != NULL) {
785 /* got a free urb, mark it */
786 urb->usercontext = FTDI_URB_USERCONTEXT_COOKIE;
788 /* try to get more urbs that are ready now, but don't wait anymore */
792 /* no more urbs waiting */
795 } while (keep_going);
799 Wait until at least one async write is complete
801 \param ftdi pointer to ftdi_context
802 \param wait_for_more if != 0 wait for more than one write to complete (until write timeout)
804 void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
806 usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
810 Stupid libusb does not offer async writes nor does it allow
811 access to its fd - so we need some hacks here.
813 static int usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
815 struct usbdevfs_urb *urb;
816 int bytesdone = 0, requested;
821 /* find a free urb buffer we can use */
823 for (cleanup_count=0; urb==NULL && cleanup_count <= 1; cleanup_count++)
825 if (i==ftdi->async_usb_buffer_size) {
826 /* wait until some buffers are free */
827 usb_async_cleanup(ftdi,0,ftdi->usb_write_timeout);
830 for (i=0; i < ftdi->async_usb_buffer_size; i++) {
831 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
832 if (urb->usercontext == FTDI_URB_USERCONTEXT_COOKIE)
833 break; /* found a free urb position */
838 /* no free urb position found */
842 requested = size - bytesdone;
843 if (requested > 4096)
846 memset(urb,0,sizeof(urb));
848 urb->type = USBDEVFS_URB_TYPE_BULK;
851 urb->buffer = bytes + bytesdone;
852 urb->buffer_length = requested;
854 urb->actual_length = 0;
855 urb->number_of_packets = 0;
856 urb->usercontext = 0;
859 ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_SUBMITURB, urb);
860 } while (ret < 0 && errno == EINTR);
862 return ret; /* the caller can read errno to get more info */
864 bytesdone += requested;
865 } while (bytesdone < size);
870 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip.
871 Does not wait for completion of the transfer nor does it make sure that
872 the transfer was successful.
874 This function could be extended to use signals and callbacks to inform the
875 caller of completion or error - but this is not done yet, volunteers welcome.
877 Works around libusb and directly accesses functions only available on Linux.
879 \param ftdi pointer to ftdi_context
880 \param buf Buffer with the data
881 \param size Size of the buffer
883 \retval <0: error code from usb_bulk_write()
884 \retval >0: number of bytes written
886 int ftdi_write_data_async(struct ftdi_context *ftdi, unsigned char *buf, int size)
890 int total_written = 0;
892 while (offset < size) {
893 int write_size = ftdi->writebuffer_chunksize;
895 if (offset+write_size > size)
896 write_size = size-offset;
898 ret = usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
900 ftdi_error_return(ret, "usb bulk write async failed");
902 total_written += ret;
903 offset += write_size;
906 return total_written;
911 Configure write buffer chunk size.
914 \param ftdi pointer to ftdi_context
915 \param chunksize Chunk size
919 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
921 ftdi->writebuffer_chunksize = chunksize;
926 Get write buffer chunk size.
928 \param ftdi pointer to ftdi_context
929 \param chunksize Pointer to store chunk size in
933 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
935 *chunksize = ftdi->writebuffer_chunksize;
940 Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
942 Automatically strips the two modem status bytes transfered during every read.
944 \param ftdi pointer to ftdi_context
945 \param buf Buffer to store data in
946 \param size Size of the buffer
948 \retval <0: error code from usb_bulk_read()
949 \retval 0: no data was available
950 \retval >0: number of bytes read
952 \remark This function is not useful in bitbang mode.
953 Use ftdi_read_pins() to get the current state of the pins.
955 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
957 int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
959 // everything we want is still in the readbuffer?
960 if (size <= ftdi->readbuffer_remaining) {
961 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
964 ftdi->readbuffer_remaining -= size;
965 ftdi->readbuffer_offset += size;
967 /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
971 // something still in the readbuffer, but not enough to satisfy 'size'?
972 if (ftdi->readbuffer_remaining != 0) {
973 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
976 offset += ftdi->readbuffer_remaining;
978 // do the actual USB read
979 while (offset < size && ret > 0) {
980 ftdi->readbuffer_remaining = 0;
981 ftdi->readbuffer_offset = 0;
982 /* returns how much received */
983 ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
985 ftdi_error_return(ret, "usb bulk read failed");
988 // skip FTDI status bytes.
989 // Maybe stored in the future to enable modem use
990 num_of_chunks = ret / 64;
991 chunk_remains = ret % 64;
992 //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
994 ftdi->readbuffer_offset += 2;
998 for (i = 1; i < num_of_chunks; i++)
999 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
1000 ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
1002 if (chunk_remains > 2) {
1003 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
1004 ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
1006 ret -= 2*num_of_chunks;
1008 ret -= 2*(num_of_chunks-1)+chunk_remains;
1010 } else if (ret <= 2) {
1011 // no more data to read?
1015 // data still fits in buf?
1016 if (offset+ret <= size) {
1017 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
1018 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1021 /* Did we read exactly the right amount of bytes? */
1023 //printf("read_data exact rem %d offset %d\n",
1024 //ftdi->readbuffer_remaining, offset);
1027 // only copy part of the data or size <= readbuffer_chunksize
1028 int part_size = size-offset;
1029 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1031 ftdi->readbuffer_offset += part_size;
1032 ftdi->readbuffer_remaining = ret-part_size;
1033 offset += part_size;
1035 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
1036 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
1047 Configure read buffer chunk size.
1050 Automatically reallocates the buffer.
1052 \param ftdi pointer to ftdi_context
1053 \param chunksize Chunk size
1057 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1059 unsigned char *new_buf;
1061 // Invalidate all remaining data
1062 ftdi->readbuffer_offset = 0;
1063 ftdi->readbuffer_remaining = 0;
1065 if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1066 ftdi_error_return(-1, "out of memory for readbuffer");
1068 ftdi->readbuffer = new_buf;
1069 ftdi->readbuffer_chunksize = chunksize;
1075 Get read buffer chunk size.
1077 \param ftdi pointer to ftdi_context
1078 \param chunksize Pointer to store chunk size in
1082 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1084 *chunksize = ftdi->readbuffer_chunksize;
1090 Enable bitbang mode.
1092 For advanced bitbang modes of the FT2232C chip use ftdi_set_bitmode().
1094 \param ftdi pointer to ftdi_context
1095 \param bitmask Bitmask to configure lines.
1096 HIGH/ON value configures a line as output.
1099 \retval -1: can't enable bitbang mode
1101 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1103 unsigned short usb_val;
1105 usb_val = bitmask; // low byte: bitmask
1106 /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1107 usb_val |= (ftdi->bitbang_mode << 8);
1109 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1110 ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1112 ftdi->bitbang_enabled = 1;
1117 Disable bitbang mode.
1119 \param ftdi pointer to ftdi_context
1122 \retval -1: can't disable bitbang mode
1124 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1126 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1127 ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1129 ftdi->bitbang_enabled = 0;
1134 Enable advanced bitbang mode for FT2232C chips.
1136 \param ftdi pointer to ftdi_context
1137 \param bitmask Bitmask to configure lines.
1138 HIGH/ON value configures a line as output.
1139 \param mode Bitbang mode: 1 for normal mode, 2 for SPI mode
1142 \retval -1: can't enable bitbang mode
1144 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1146 unsigned short usb_val;
1148 usb_val = bitmask; // low byte: bitmask
1149 usb_val |= (mode << 8);
1150 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1151 ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1153 ftdi->bitbang_mode = mode;
1154 ftdi->bitbang_enabled = (mode == BITMODE_BITBANG || mode == BITMODE_SYNCBB)?1:0;
1159 Directly read pin state. Useful for bitbang mode.
1161 \param ftdi pointer to ftdi_context
1162 \param pins Pointer to store pins into
1165 \retval -1: read pins failed
1167 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1169 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0C, 0, ftdi->index, (char *)pins, 1, ftdi->usb_read_timeout) != 1)
1170 ftdi_error_return(-1, "read pins failed");
1178 The FTDI chip keeps data in the internal buffer for a specific
1179 amount of time if the buffer is not full yet to decrease
1180 load on the usb bus.
1182 \param ftdi pointer to ftdi_context
1183 \param latency Value between 1 and 255
1186 \retval -1: latency out of range
1187 \retval -2: unable to set latency timer
1189 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1191 unsigned short usb_val;
1194 ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
1197 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x09, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1198 ftdi_error_return(-2, "unable to set latency timer");
1206 \param ftdi pointer to ftdi_context
1207 \param latency Pointer to store latency value in
1210 \retval -1: unable to get latency timer
1212 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1214 unsigned short usb_val;
1215 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0A, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
1216 ftdi_error_return(-1, "reading latency timer failed");
1218 *latency = (unsigned char)usb_val;
1223 Init eeprom with default values.
1225 \param eeprom Pointer to ftdi_eeprom
1227 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
1229 eeprom->vendor_id = 0x0403;
1230 eeprom->product_id = 0x6001;
1232 eeprom->self_powered = 1;
1233 eeprom->remote_wakeup = 1;
1234 eeprom->BM_type_chip = 1;
1236 eeprom->in_is_isochronous = 0;
1237 eeprom->out_is_isochronous = 0;
1238 eeprom->suspend_pull_downs = 0;
1240 eeprom->use_serial = 0;
1241 eeprom->change_usb_version = 0;
1242 eeprom->usb_version = 0x0200;
1243 eeprom->max_power = 0;
1245 eeprom->manufacturer = NULL;
1246 eeprom->product = NULL;
1247 eeprom->serial = NULL;
1251 Build binary output from ftdi_eeprom structure.
1252 Output is suitable for ftdi_write_eeprom().
1254 \param eeprom Pointer to ftdi_eeprom
1255 \param output Buffer of 128 bytes to store eeprom image to
1257 \retval >0: used eeprom size
1258 \retval -1: eeprom size (128 bytes) exceeded by custom strings
1260 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
1263 unsigned short checksum, value;
1264 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
1267 if (eeprom->manufacturer != NULL)
1268 manufacturer_size = strlen(eeprom->manufacturer);
1269 if (eeprom->product != NULL)
1270 product_size = strlen(eeprom->product);
1271 if (eeprom->serial != NULL)
1272 serial_size = strlen(eeprom->serial);
1274 size_check = 128; // eeprom is 128 bytes
1275 size_check -= 28; // 28 are always in use (fixed)
1276 size_check -= manufacturer_size*2;
1277 size_check -= product_size*2;
1278 size_check -= serial_size*2;
1280 // eeprom size exceeded?
1285 memset (output, 0, 128);
1287 // Addr 00: Stay 00 00
1288 // Addr 02: Vendor ID
1289 output[0x02] = eeprom->vendor_id;
1290 output[0x03] = eeprom->vendor_id >> 8;
1292 // Addr 04: Product ID
1293 output[0x04] = eeprom->product_id;
1294 output[0x05] = eeprom->product_id >> 8;
1296 // Addr 06: Device release number (0400h for BM features)
1297 output[0x06] = 0x00;
1299 if (eeprom->BM_type_chip == 1)
1300 output[0x07] = 0x04;
1302 output[0x07] = 0x02;
1304 // Addr 08: Config descriptor
1305 // Bit 1: remote wakeup if 1
1306 // Bit 0: self powered if 1
1309 if (eeprom->self_powered == 1)
1311 if (eeprom->remote_wakeup == 1)
1315 // Addr 09: Max power consumption: max power = value * 2 mA
1316 output[0x09] = eeprom->max_power;
1319 // Addr 0A: Chip configuration
1320 // Bit 7: 0 - reserved
1321 // Bit 6: 0 - reserved
1322 // Bit 5: 0 - reserved
1323 // Bit 4: 1 - Change USB version
1324 // Bit 3: 1 - Use the serial number string
1325 // Bit 2: 1 - Enable suspend pull downs for lower power
1326 // Bit 1: 1 - Out EndPoint is Isochronous
1327 // Bit 0: 1 - In EndPoint is Isochronous
1330 if (eeprom->in_is_isochronous == 1)
1332 if (eeprom->out_is_isochronous == 1)
1334 if (eeprom->suspend_pull_downs == 1)
1336 if (eeprom->use_serial == 1)
1338 if (eeprom->change_usb_version == 1)
1342 // Addr 0B: reserved
1343 output[0x0B] = 0x00;
1345 // Addr 0C: USB version low byte when 0x0A bit 4 is set
1346 // Addr 0D: USB version high byte when 0x0A bit 4 is set
1347 if (eeprom->change_usb_version == 1) {
1348 output[0x0C] = eeprom->usb_version;
1349 output[0x0D] = eeprom->usb_version >> 8;
1353 // Addr 0E: Offset of the manufacturer string + 0x80
1354 output[0x0E] = 0x14 + 0x80;
1356 // Addr 0F: Length of manufacturer string
1357 output[0x0F] = manufacturer_size*2 + 2;
1359 // Addr 10: Offset of the product string + 0x80, calculated later
1360 // Addr 11: Length of product string
1361 output[0x11] = product_size*2 + 2;
1363 // Addr 12: Offset of the serial string + 0x80, calculated later
1364 // Addr 13: Length of serial string
1365 output[0x13] = serial_size*2 + 2;
1368 output[0x14] = manufacturer_size*2 + 2;
1369 output[0x15] = 0x03; // type: string
1373 // Output manufacturer
1374 for (j = 0; j < manufacturer_size; j++) {
1375 output[i] = eeprom->manufacturer[j], i++;
1376 output[i] = 0x00, i++;
1379 // Output product name
1380 output[0x10] = i + 0x80; // calculate offset
1381 output[i] = product_size*2 + 2, i++;
1382 output[i] = 0x03, i++;
1383 for (j = 0; j < product_size; j++) {
1384 output[i] = eeprom->product[j], i++;
1385 output[i] = 0x00, i++;
1389 output[0x12] = i + 0x80; // calculate offset
1390 output[i] = serial_size*2 + 2, i++;
1391 output[i] = 0x03, i++;
1392 for (j = 0; j < serial_size; j++) {
1393 output[i] = eeprom->serial[j], i++;
1394 output[i] = 0x00, i++;
1397 // calculate checksum
1400 for (i = 0; i < 63; i++) {
1401 value = output[i*2];
1402 value += output[(i*2)+1] << 8;
1404 checksum = value^checksum;
1405 checksum = (checksum << 1) | (checksum >> 15);
1408 output[0x7E] = checksum;
1409 output[0x7F] = checksum >> 8;
1417 \param ftdi pointer to ftdi_context
1418 \param eeprom Pointer to store eeprom into
1421 \retval -1: read failed
1423 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
1427 for (i = 0; i < 64; i++) {
1428 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
1429 ftdi_error_return(-1, "reading eeprom failed");
1436 ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
1437 Function is only used internally
1440 static unsigned char ftdi_read_chipid_shift(unsigned char value)
1442 return ((value & 1) << 1) |
1443 ((value & 2) << 5) |
1444 ((value & 4) >> 2) |
1445 ((value & 8) << 4) |
1446 ((value & 16) >> 1) |
1447 ((value & 32) >> 1) |
1448 ((value & 64) >> 4) |
1449 ((value & 128) >> 2);
1453 Read the FTDIChip-ID from R-type devices
1455 \param ftdi pointer to ftdi_context
1456 \param chipid Pointer to store FTDIChip-ID
1459 \retval -1: read failed
1461 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
1463 unsigned int a = 0, b = 0;
1465 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, 0x43, (char *)&a, 2, ftdi->usb_read_timeout) == 2)
1467 a = a << 8 | a >> 8;
1468 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, 0x44, (char *)&b, 2, ftdi->usb_read_timeout) == 2)
1470 b = b << 8 | b >> 8;
1472 a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
1473 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
1474 *chipid = a ^ 0xa5f0f7d1;
1479 ftdi_error_return(-1, "read of FTDIChip-ID failed");
1485 \param ftdi pointer to ftdi_context
1486 \param eeprom Pointer to read eeprom from
1489 \retval -1: read failed
1491 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
1493 unsigned short usb_val;
1496 for (i = 0; i < 64; i++) {
1497 usb_val = eeprom[i*2];
1498 usb_val += eeprom[(i*2)+1] << 8;
1499 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x91, usb_val, i, NULL, 0, ftdi->usb_write_timeout) != 0)
1500 ftdi_error_return(-1, "unable to write eeprom");
1509 \param ftdi pointer to ftdi_context
1512 \retval -1: erase failed
1514 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
1516 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x92, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
1517 ftdi_error_return(-1, "unable to erase eeprom");
1523 Get string representation for last error code
1525 \param ftdi pointer to ftdi_context
1527 \retval Pointer to error string
1529 char *ftdi_get_error_string (struct ftdi_context *ftdi)
1531 return ftdi->error_str;
1535 Flow control code by Lorenz Moesenlechner (lorenz@hcilab.org)
1536 and Matthias Kranz (matthias@hcilab.org)
1539 Set flowcontrol for ftdi chip
1541 \param ftdi pointer to ftdi_context
1542 \param flowctrl flow control to use. should be
1543 SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
1546 \retval -1: set flow control failed
1548 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1550 if (usb_control_msg(ftdi->usb_dev, SIO_SET_FLOW_CTRL_REQUEST_TYPE,
1551 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->interface),
1552 NULL, 0, ftdi->usb_write_timeout) != 0)
1553 ftdi_error_return(-1, "set flow control failed");
1561 \param ftdi pointer to ftdi_context
1562 \param state state to set line to (1 or 0)
1565 \retval -1: set dtr failed
1567 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
1569 unsigned short usb_val;
1572 usb_val = SIO_SET_DTR_HIGH;
1574 usb_val = SIO_SET_DTR_LOW;
1576 if (usb_control_msg(ftdi->usb_dev, SIO_SET_MODEM_CTRL_REQUEST_TYPE,
1577 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->interface,
1578 NULL, 0, ftdi->usb_write_timeout) != 0)
1579 ftdi_error_return(-1, "set dtr failed");
1587 \param ftdi pointer to ftdi_context
1588 \param state state to set line to (1 or 0)
1591 \retval -1 set rts failed
1593 int ftdi_setrts(struct ftdi_context *ftdi, int state)
1595 unsigned short usb_val;
1598 usb_val = SIO_SET_RTS_HIGH;
1600 usb_val = SIO_SET_RTS_LOW;
1602 if (usb_control_msg(ftdi->usb_dev, SIO_SET_MODEM_CTRL_REQUEST_TYPE,
1603 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->interface,
1604 NULL, 0, ftdi->usb_write_timeout) != 0)
1605 ftdi_error_return(-1, "set of rts failed");
1610 /* @} end of doxygen libftdi group */