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 ば
助言がありますか?