c - 用串口编程C读取多个传感器

标签 c input serial-port

我想使用 C 编程语言和 GCC 编译器通过串行端口将数据从 Arduino 微 Controller 读取到运行 Mac OS X 的电脑。

我的数据格式是A xxxx xxxx xxxx xxxx xxxx xxxx B,其中A是数据的开头,B是数据的结尾,传感器之间有4个空格( “”)。 xxxx数据在0-1023之间变化。

我正在尝试这段代码:

#include<stdio.h>   /* Standard input/output definitions */
#include<stdlib.h>
#include<string.h>  /* String function definitions */
#include<unistd.h>  /* UNIX standard function definitions */
#include<fcntl.h>   /* File control definitions */
#include<errno.h>   /* Error number definitions */
#include<termios.h> /* POSIX terminal control definitions */
#include<string.h> 
#include<unistd.h>

char *buf;
int fd; /* File descriptor for the port */
int i,n;
char *sensor1, *sensor2, *sensor3, *sensor4, *sensor5, *sensor6,*header, *footer;

int open_port(void)
{
    fd = open("/dev/tty.usbmodem1d11", O_RDWR | O_NOCTTY | O_NDELAY);      

if (fd == -1)     {
    perror("cannot open");
}
else 
    fcntl(fd, F_SETFL, 0);
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD);
tcsetattr(fd, TCSANOW, &options);
options.c_cflag &= ~CSIZE; 
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
//    options.c_cflag |= (IXON | IXOFF | IXANY); // xon & xoff on
return (fd);
}

int main(int argc, char**argv) {
    buf=malloc(4095);
    open_port();
    free(buf);
    while(1){ 
        read(fd,buf,90);          
         printf("%s\n",buf);  
    }
    close(fd);
}

但是结果不一致,我的意思是数据的长度不一样:

A 1023 1023 1023 1023 1023 B

一个

10233 023 1023 1023 B

A 1023 1023 1023 1023 1023 B

一个 3 023 1023 1023 B

A 1023 1023 1023 1023 1023 B

一个

10233 023 1023 1023 B

A 1023 1023 1023 1023 1023 巴

有什么建议吗?

最佳答案

检查从每个 read 调用中返回的内容:

int nbytes;

while(1) { 
    nbytes = read(fd,buf,90);
    if( nbytes > 0 ) {
        buf[nbytes] = 0;
        printf( "Read %2d bytes: '%s'\n", nbytes, buf );
    }
}

您需要将结果收集到缓冲区中,并根据设备的格式规范对其进行解析。您不能假设每个 read 调用都会为您提供完整的记录。

为了收集结果,您需要跟踪您已经阅读过的内容 - 像这样......

int nbytes, nparsed;
int npos = 0;

while(1) { 
    nbytes = read(fd, &buf[npos], 90-npos);
    if( nbytes > 0 )
    {
        npos += nbytes;

        // Parse a line.  If successful, move remainder of line to
        // start of buffer and continue...
        nparsed = parse_line(buf, npos);
        if( nparsed > 0 ) {
            memmove( buf, &buf[npos], npos-nparsed );
            npos -= nparsed;
        }
    }
}

取决于您的应用程序。它可能比这更简单。

关于c - 用串口编程C读取多个传感器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13557587/

相关文章:

c++ - 从串口读取 C++

c++ - 为什么类的大小取决于成员声明的顺序?如何?

c - 如何从文件中读取字符串并将其标记为数组?

c - C中的二维字符数组操作

magento - magento 产品属性的自定义 "Catalog Input Type for Store Owner"

url - HTML 和 Google 的查询问题

计算传感器数据流的平均值

c++ - 如何处理输入流中留下的无关字符? (cin 跳过)

c# - 为什么我尝试打开串口时得到 "CreateFile Failed: 161"?

c# - 使用 Async await 方法从串口异步读取