从C读取串行数据(OSX / dev / tty)

时间:2010-03-24 01:08:54

标签: c serial-port bluetooth screen

我正在尝试使用C从蓝牙条码扫描器(KDC300)读取数据。这是我到目前为止的代码,程序成功建立了与扫描仪的蓝牙连接,但是当扫描条形码时,没有输入屏幕上显示(最终将对数据进行更多操作,但我们必须先让它工作,对吧)。

以下是该计划:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <sys/ioctl.h>

int main (int argc, const char * argv[]) {

    // define vars
    int STOP = 0;
    //char buf[255];

    if(argv[1])
    {
        int fd = open("/dev/tty.KDC1", O_RDONLY);
        if(fd == -1)
        {
            printf("%s", strcat("Unable to open /dev/tty.", argv[1]));
        }

        int res;
        while(STOP == 0)
        {
            while((res = read(fd,buf,255)) == 0);
            {
                if(res > 0)
                {
                    buf[res]=0;
                    printf("%s:%d\n", buf, res);
                    if(buf[sizeof(buf)]=='\n') break;   
                }
            }
        }
    }

    return 0;
}

如果有人有任何想法,我到目前为止都不知所措。如果有任何帮助,我可以运行screen /dev/tty.KDC1并且扫描仪上扫描的任何条形码都出现在终端中,我对数据无能为力。

4 个答案:

答案 0 :(得分:7)

这一行:

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

不按照您的想法行事。这是一个空while循环。

答案 1 :(得分:1)

@ tommieb75,    strcat语句来自程序的第一个“go”,我从argv [1]中获取一个变量并将其附加到/dev/tty.*,这样你就可以选择要监视的设备。

我不确定为什么我已经评论buf,可能源于过多地查看代码/尝试不同的方法而忘记了我的位置(不是很多C程序员,这是我怎么能得到的失去了30 LOC。

@caf,在while循环之后很好地捕获额外的分号,不幸的是,即使在纠正之后,程序也没有正常运行。

我正在进一步研究这个问题。我可以验证(使用osx packetlogger)计算机正在获取数据,但缓冲区中没有任何数据。

-Jud

---------------编辑--------------

经过一番试验,我解决了这个问题。添加以下代码来设置串行连接解决了所有问题:

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);

感谢让我达到这一点的其他答案。

答案 2 :(得分:1)

Here是我发现的最佳信息。

使用termios的C程序只需添加

即可
#include<string.h>

更改波特率以符合我的需要。

答案 3 :(得分:0)

在您的代码中

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

你为什么这样做?这样做会更容易:

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

为什么参数引用命令行?

res = read(fd,buf,255)

为什么上面有buf声明?