I want to read serial from arduino. I use this code :
#include <stdio.h> /* Standard input/output definitions */
#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 <sys/ioctl.h>
int main(){
char data[1024];
char dev[] = "/dev/ttyACM1";
int fd = open(dev, O_RDWR | O_NOCTTY | O_NDELAY);
fcntl(fd, F_SETFL, FNDELAY);
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= CS8;
options.c_cflag |= CS8;
options.c_cflag &= ~CRTSCTS;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tcsetattr(fd, TCSANOW, &options);
ioctl(fd, TCFLSH, 2);
while(1){
read(fd, data, sizeof(data));
printf(data);
}
//write(fd, data, sizeof(data));
}
My arduino runs very simple sketch :
int x;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("DO YOU HEAR ME ??");
delay(1000);
}
and output of this combinatin is that :
??OU HEAR ME ??
DO YOU HEAR ME ??
DO YOU HEAR ME ??
A¹þ
??OU HEAR ME ??
DO YOU HEAR ME ??
DO YOU HEAR ME ??
A¹þ
??OU HEAR ME ??
DO YOU HEAR ME ??
DO YOU HEAR ME ??
My question is how to make order out of chaos. I found that this issue occurs when buffer ends and new one begins(bigger buffer less junk data) but I can't have a infinite buffer. Also there is a lot of junk when it reads for the first time.. Is there a way to sync it or something ?
(Also I am not native English sorry for any mistakes.)
read.read, it might return with an error value. However, your program will still print thedatabuffer. Also, on success, the return value ofreadwill be the number of bytes read, which you should use to make sure thatdatais null terminated.