0

Cプログラミング言語とGCCコンパイラを使用して、ArduinoマイクロコントローラからMac OS Xを実行しているPCにシリアルポート経由でデータを読み取りたいです。

私のデータのフォーマットは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 1023B

A 1023 1023 1023 1023 1023 B

A 3 023 1023 1023 B

A 1023 1023 1023 1023 1023 B

10233 023 1023 1023B

1023 1023 1023 1023 1023 ば

助言がありますか?

4

1 に答える 1

2

各読み取り呼び出しから返される内容を調べます。

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

アプリケーションによって異なります。それよりもさらに簡単かもしれません。

于 2012-11-26T02:25:48.503 に答える