| 1 | /* serial_read.c |
| 2 | |
| 3 | Read data via serial I/O |
| 4 | |
| 5 | This program is distributed under the GPL, version 2 |
| 6 | */ |
| 7 | |
| 8 | #include <stdio.h> |
| 9 | #include <stdlib.h> |
| 10 | #include <unistd.h> |
| 11 | #include <getopt.h> |
| 12 | #include <ftdi.h> |
| 13 | |
| 14 | int main(int argc, char **argv) |
| 15 | { |
| 16 | struct ftdi_context ftdic; |
| 17 | unsigned char buf[1024]; |
| 18 | int f, i; |
| 19 | int vid = 0x0403; |
| 20 | int pid = 0x6001; |
| 21 | int baudrate = 115200; |
| 22 | int interface = INTERFACE_ANY; |
| 23 | |
| 24 | while ((i = getopt(argc, argv, "i:v:p:b:")) != -1) |
| 25 | { |
| 26 | switch (i) |
| 27 | { |
| 28 | case 'i': // 0=ANY, 1=A, 2=B, 3=C, 4=D |
| 29 | interface = strtoul(optarg, NULL, 0); |
| 30 | break; |
| 31 | case 'v': |
| 32 | vid = strtoul(optarg, NULL, 0); |
| 33 | break; |
| 34 | case 'p': |
| 35 | pid = strtoul(optarg, NULL, 0); |
| 36 | break; |
| 37 | case 'b': |
| 38 | baudrate = strtoul(optarg, NULL, 0); |
| 39 | break; |
| 40 | default: |
| 41 | fprintf(stderr, "usage: %s [-i interface] [-v vid] [-p pid] [-b baudrate]\n", *argv); |
| 42 | exit(-1); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | // Init |
| 47 | if (ftdi_init(&ftdic) < 0) |
| 48 | { |
| 49 | fprintf(stderr, "ftdi_init failed\n"); |
| 50 | return EXIT_FAILURE; |
| 51 | } |
| 52 | |
| 53 | // Select first interface |
| 54 | ftdi_set_interface(&ftdic, interface); |
| 55 | |
| 56 | // Open device |
| 57 | f = ftdi_usb_open(&ftdic, vid, pid); |
| 58 | if (f < 0) |
| 59 | { |
| 60 | fprintf(stderr, "unable to open ftdi device: %d (%s)\n", f, ftdi_get_error_string(&ftdic)); |
| 61 | exit(-1); |
| 62 | } |
| 63 | |
| 64 | // Set baudrate |
| 65 | f = ftdi_set_baudrate(&ftdic, 115200); |
| 66 | if (f < 0) |
| 67 | { |
| 68 | fprintf(stderr, "unable to set baudrate: %d (%s)\n", f, ftdi_get_error_string(&ftdic)); |
| 69 | exit(-1); |
| 70 | } |
| 71 | |
| 72 | // Read data forever |
| 73 | while ((f = ftdi_read_data(&ftdic, buf, sizeof(buf))) >= 0) { |
| 74 | fprintf(stderr, "read %d bytes\n", f); |
| 75 | fwrite(buf, f, 1, stdout); |
| 76 | fflush(stderr); |
| 77 | fflush(stdout); |
| 78 | } |
| 79 | |
| 80 | ftdi_usb_close(&ftdic); |
| 81 | ftdi_deinit(&ftdic); |
| 82 | |
| 83 | return 0; |
| 84 | } |