Reading Serial Data From C (OSX /dev/tty)

后端 未结 4 1147
南方客
南方客 2021-01-22 21:46

I am trying to read data from a bluetooth barcode scanner (KDC300) using C. Here is the code I have so far, and the program successfully establishes a bluetooth connection to th

相关标签:
4条回答
  • 2021-01-22 21:46

    Here is the best info I've found.

    The C program on there using termios worked just by adding

    #include<string.h>
    

    And changing the baudrate to match my needs.

    0 讨论(0)
  • 2021-01-22 21:48

    In your code

    printf("%s", strcat("Unable to open /dev/tty.", argv[1]));
    

    Why did you do that? It would be easier to do it this way:

    printf("%s: Unable to open /dev/tty.KDC1", argv[0]); 
    

    Why the parameter referencing to the command line?

    res = read(fd,buf,255)
    

    Why did you have buf declaration commented out above?

    0 讨论(0)
  • 2021-01-22 21:51

    @tommieb75, the strcat statement was from the first "go" at the program, I took a variable from argv[1] and appended it to the /dev/tty.* so you could select which device you wanted to monitor.

    I am not sure why I had commented out buf, probably stems from looking at the code too much / trying different approaches and forgetting where I was (not much of a C programmer, which is how I can get lost in 30 LOC).

    @caf, Good catch on the extra semi-colon after the while loop, unfortunately, even after correcting it, the program doesn't behave correctly.

    I am researching the problem further. I can verify (with osx packetlogger) that the computer is getting the data, but the but the buffer never has any data placed in it.

    -Jud

    ---------------Edit--------------

    I solved the problem after a little trial and error. Adding the following code to setup the serial connection solved everything:

    struct termios theTermios;
    
    memset(&theTermios, 0, sizeof(struct termios));
    cfmakeraw(&theTermios);
    cfsetspeed(&theTermios, 115200);
    
    theTermios.c_cflag = CREAD | CLOCAL;     // turn on READ
    theTermios.c_cflag |= CS8;
    theTermios.c_cc[VMIN] = 0;
    theTermios.c_cc[VTIME] = 10;     // 1 sec timeout
    ioctl(fileDescriptor, TIOCSETA, &theTermios);
    

    Thanks to the other answers for getting me to this point.

    0 讨论(0)
  • 2021-01-22 22:06

    This line:

            while((res = read(fd,buf,255)) == 0);
    

    Does not do what you think it does. That's a while loop with an empty body.

    0 讨论(0)
提交回复
热议问题