fix mem leaks in examples ftdi_deinit -> ftdi_free
[libftdi] / examples / bitbang2.c
CommitLineData
ad397a4b
TJ
1/* ftdi_out.c
2 *
22d12cda
TJ
3 * Output a (stream of) byte(s) in bitbang mode to the
4 * ftdi245 chip that is (hopefully) attached.
ad397a4b 5 *
22d12cda
TJ
6 * We have a little board that has a FT245BM chip and
7 * the 8 outputs are connected to several different
8 * things that we can turn on and off with this program.
ad397a4b
TJ
9 *
10 * If you have an idea about hardware that can easily
11 * interface onto an FTDI chip, I'd like to collect
12 * ideas. If I find it worthwhile to make, I'll consider
13 * making it, I'll even send you a prototype (against
14 * cost-of-material) if you want.
22d12cda
TJ
15 *
16 * At "harddisk-recovery.nl" they have a little board that
17 * controls the power to two harddrives and two fans.
18 *
ad397a4b
TJ
19 * -- REW R.E.Wolff@BitWizard.nl
20 *
21 *
22 *
22d12cda 23 * This program was based on libftdi_example_bitbang2232.c
ad397a4b
TJ
24 * which doesn't carry an author or attribution header.
25 *
26 *
22d12cda 27 * This program is distributed under the GPL, version 2.
ad397a4b
TJ
28 * Millions copies of the GPL float around the internet.
29 */
30
31
32#include <stdio.h>
579b006f 33#include <stdlib.h>
ad397a4b 34#include <unistd.h>
7b5c5624
UB
35#ifdef __WIN32__
36#define usleep(x) Sleep((x+999)/1000)
37#endif
ad397a4b
TJ
38#include <ftdi.h>
39
40void ftdi_fatal (struct ftdi_context *ftdi, char *str)
41{
42 fprintf (stderr, "%s: %s\n",
43 str, ftdi_get_error_string (ftdi));
1383a2c4 44 ftdi_free(ftdi);
ad397a4b
TJ
45 exit (1);
46}
47
48int main(int argc, char **argv)
49{
cd2ead2f 50 struct ftdi_context *ftdi;
ad397a4b
TJ
51 int i, t;
52 unsigned char data;
53 int delay = 100000; /* 100 thousand microseconds: 1 tenth of a second */
54
22d12cda
TJ
55 while ((t = getopt (argc, argv, "d:")) != -1)
56 {
57 switch (t)
58 {
59 case 'd':
60 delay = atoi (optarg);
61 break;
ad397a4b
TJ
62 }
63 }
64
cd2ead2f 65 if ((ftdi = ftdi_new()) == 0)
6ac169ea 66 {
cd2ead2f 67 fprintf(stderr, "ftdi_bew failed\n");
6ac169ea
TJ
68 return EXIT_FAILURE;
69 }
ad397a4b 70
cd2ead2f
UB
71 if (ftdi_usb_open(ftdi, 0x0403, 0x6001) < 0)
72 ftdi_fatal (ftdi, "Can't open ftdi device");
ad397a4b 73
cd2ead2f
UB
74 if (ftdi_set_bitmode(ftdi, 0xFF, BITMODE_BITBANG) < 0)
75 ftdi_fatal (ftdi, "Can't enable bitbang");
ad397a4b 76
22d12cda
TJ
77 for (i=optind; i < argc ; i++)
78 {
ad397a4b
TJ
79 sscanf (argv[i], "%x", &t);
80 data = t;
cd2ead2f 81 if (ftdi_write_data(ftdi, &data, 1) < 0)
22d12cda 82 {
ad397a4b 83 fprintf(stderr,"write failed for 0x%x: %s\n",
cd2ead2f 84 data, ftdi_get_error_string(ftdi));
ad397a4b
TJ
85 }
86 usleep(delay);
87 }
88
cd2ead2f
UB
89 ftdi_usb_close(ftdi);
90 ftdi_free(ftdi);
ad397a4b
TJ
91 exit (0);
92}