C to read data from a USB device connected to the system

I am trying to retrieve data from a USB device (e.g. pendrive) connected to the systemโ€™s USB port. Here I can open the device file and read some random source data. But I want to get data like minicom / teraterm.

Please let me know what methods and libraries I can use to do this successfully and how to do it.

#include <stdio.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <termios.h> #include <signal.h> #include <sys/time.h> int main() { short portfd=-1; int n,f,len; char buf[256],*s; alarm(2); #if defined(O_NDELAY) && defined(F_SETFL) portfd = open("/dev/ttyUSB0", O_RDWR|O_NDELAY); if (portfd >= 0){ /* Cancel the O_NDELAY flag. */ printf("port openend\n"); n = fcntl(portfd, F_GETFL, 0); (void) fcntl(portfd, F_SETFL, n & ~O_NDELAY); } #else portfd = open("/dev/ttyUSB0", O_RDWR); #endif if (portfd >= 0) { if (len == 0) len = strlen(s); for(f = 0; f < len && f <100; f++) buf[f] = *s++ | 0x80; write(portfd, buf, f); printf("Do write\n"); while(portfd>=0){ printf("%s\n",buf); } } alarm(0); signal(SIGALRM, SIG_IGN); if (portfd < 0) { printf("cannot open %s. Sorry.\n", "/dev/ttyUSB0"); } } 

Log Out:

          ้‰€                   ้€                                                               2           ้‰€                   ้€                                                               2 
+4
source share
2 answers

you will need to set the correct port configuration ...

 struct termios oldtio,newtio; // open port... // save existing attributes tcgetattr(fd,&oldtio); // set attributes - these flags may change for your device #define BAUDRATE B9600 memset(&newtio, 0x00, sizeof(newtio)); newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD; newtio.c_iflag = IGNPAR | ICRNL; newtio.c_oflag = 0; tcflush(fd, TCIFLUSH); tcsetattr(fd,TCSANOW,&newtio); //reset attributes tcsetattr(fd,TCSANOW,&oldtio); 

I have an example working example here ... http://file-hub.com/cmd:thread/142300

+3
source

The garbage that you get in the console may be caused by an incorrect serial line speed configuration. I suggest you do the same as here to make sure your device is configured correctly.

[SOLVED] How to read data over / dev / ttyUSB0

+1
source

All Articles