First support PL2303-HXD GPIO 2 & 3
[pub/pl2303-ft232-gpio.git] / ft232r.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 /* According to POSIX.1-2001 */
4 #include <sys/select.h>
5 #include <string.h>
6 #include <sys/time.h>
7 #include <sys/types.h>
8 #include <unistd.h>
9 #include <termios.h>
10 #include <fcntl.h>
11 #include <signal.h>
12 #include <libusb.h>
13 #include <getopt.h>
14
15
16 #define _GNU_SOURCE
17 #include <getopt.h>
18
19
20 #define I_VENDOR_NUM 0x0403
21 #define I_PRODUCT_NUM 0x6001
22 #define BITMODE_CBUS 0x20
23 #define BITMODE_RESET 0x00
24
25 #define FTDI_SIO_SET_BITMODE 11 /* Set the bitmode */
26 #define FTDI_SIO_READ_PINS 12 /* Read pins in bitmode */
27
28 #define FTDI_SIO_SET_BITMODE_REQUEST FTDI_SIO_SET_BITMODE
29 #define FTDI_SIO_SET_BITMODE_REQUEST_TYPE 0x40
30
31 #define FTDI_SIO_READ_PINS_REQUEST FTDI_SIO_READ_PINS
32 #define FTDI_SIO_READ_PINS_REQUEST_TYPE 0xC0
33
34 int get_device_vid()
35 {
36 return I_VENDOR_NUM;
37 }
38
39 int get_device_pid()
40 {
41 return I_PRODUCT_NUM;
42 }
43
44 /* Get current GPIO register from PL2303 */
45 unsigned char gpio_read_reg(libusb_device_handle *h)
46 {
47 unsigned char buf;
48 int bytes = libusb_control_transfer(
49 h, // handle obtained with usb_open()
50 FTDI_SIO_READ_PINS_REQUEST_TYPE, // bRequestType
51 FTDI_SIO_READ_PINS_REQUEST, // bRequest
52 0, // wValue
53 0, // wIndex
54 &buf, // pointer to destination buffer
55 1, // wLength
56 1000
57 );
58 handle_error(bytes);
59 return buf;
60 }
61
62 void gpio_write_reg(libusb_device_handle *h, unsigned short reg)
63 {
64 int bytes = libusb_control_transfer(
65 h, // handle obtained with usb_open()
66 FTDI_SIO_SET_BITMODE_REQUEST_TYPE, //bRequestType
67 FTDI_SIO_SET_BITMODE_REQUEST, // bRequest
68 reg, // wValue
69 0, // wIndex
70 0, // pointer to destination buffer
71 0, // wLength
72 1000
73 );
74 handle_error(bytes);
75
76 }
77
78 void gpio_out(libusb_device_handle *h, int gpio, int value)
79 {
80 unsigned char cbus_mask;
81
82 if ((gpio < 0) || (gpio > 3))
83 return;
84
85 cbus_mask = gpio_read_reg(h);
86 cbus_mask |= ((1 << gpio) << 4);
87 if (value)
88 cbus_mask |= (1 << gpio);
89 else
90 cbus_mask &= ~(1 << gpio);
91 gpio_write_reg(h, (BITMODE_CBUS << 8) | cbus_mask);
92 }
93
94 void gpio_in(libusb_device_handle *h, int gpio, int pullup)
95 {
96 unsigned char cbus_mask;
97
98 if ((gpio < 0) || (gpio > 3))
99 return;
100
101 cbus_mask = gpio_read_reg(h);
102 cbus_mask &= ~((1 << gpio) << 4);
103 gpio_write_reg(h, (BITMODE_CBUS << 8) | cbus_mask);
104 }
105
106 int gpio_read(libusb_device_handle *h, int gpio)
107 {
108 unsigned char r = gpio_read_reg(h);
109
110 if ((gpio < 0) || (gpio > 3))
111 return 0;
112 return (r & (1 << gpio)) ? 1 : 0;
113 }
114