sách gpt4 ai đã đi

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

In lại 作者:行者123 更新时间:2023-11-30 14:22:43 hai mươi bốn 4
mua khóa gpt4 Nike

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

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

我正在尝试这段代码:

#include /* Standard input/output definitions */
#include
#include /* String function definitions */
#include /* UNIX standard function definitions */
#include /* File control definitions */
#include /* Error number definitions */
#include /* POSIX terminal control definitions */
#include
#include

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");
}
khác
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 巴

Có gợi ý nào không?

1 Câu trả lời

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

int nbytes;

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

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

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

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/

hai mươi bốn 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com