Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

linux

I am trying to fetch data from the USB device (say pendrive) connected to the USB port of a system. Here, I am able to open the device file and read some random raw data. But I want to fetch data like minicom/teraterm.

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

#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 of the output:

���������鉀�������������������鍀���������������������������������������������������������������2
����������鉀�������������������鍀���������������������������������������������������������������2
like image 380
Appie Avatar asked Sep 26 '13 09:09

Appie


1 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 a rough working example here... http://file-hub.com/cmd:thread/142300

like image 192
Trudysfun Avatar answered Oct 10 '22 09:10

Trudysfun