I have problem with reading data from serial port on linux.I configure port using termios library and receive data from microcontroller which work perfectly (I checked that using hterm program) .When i send "e" character to microcontroller it should send me sequence of characters in hex "77 31 31 32 33 34 a " "77 32 35 36 37 a" and "77 33 38 39 a" only once but it send me it multiple times. Part of code which write data to microcontroller works well. method responsible for reading
whole code
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "Terminal.h"
int Terminal::configPort(int fd, int sp){
struct termios tty;
tcgetattr(fd, &tty);
cfsetospeed(&tty, (speed_t)speed);
cfsetispeed(&tty, (speed_t)speed);
tty.c_cflag |= (CLOCAL | CREAD);
tty.c_cflag &= ~PARENB;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tty.c_oflag &= ~OPOST;
tty.c_cc[VMIN] = 0;
tty.c_cc[VTIME] = 240;
tcsetattr(fd, TCSANOW, &tty);}
int Terminal::openPort(char* p){
int f;
f = open(p, O_RDWR | O_NOCTTY | O_NDELAY);
if (f == -1) {
printf("Error opening %s: %s\n",p, strerror(errno));
} else {
fcntl(f, F_SETFL, 0);}
return(f);
}
Terminal::Terminal(char* p ,int s){
port=p;
speed=s;
}
void Terminal::readData(){
unsigned char buf[80];
int rdlen;
rdlen = read(fd, buf, sizeof(buf) - 1);
if (rdlen > 0) {
unsigned char *p;
for ( p = buf; rdlen > 0; ++p, --rdlen )
{ printf(" %x", *p);}
printf("\n");}
else if (rdlen < 0) {
printf("Error from read: %d: %s\n", rdlen, strerror(errno));
} else {
printf("Timeout from read\n");
}
}
Terminal::~Terminal(){
close(fd);
}
#pragma once
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <stdlib.h>
class Terminal{
char* port;
int speed;
public:
int fd;
int configPort(int,int);
int openPort(char*);
void readData();
Terminal(char* ,int);
~Terminal();
};
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "Terminal.h"
int main(){
char *portname = "/dev/ttyACM0";
int written;
Terminal w(portname,B115200);
w.fd=w.openPort(portname);
w.configPort(w.fd,B115200);
char message[] = "e";
int messageSize = strlen(message);
written = write(w.fd, message, messageSize);
printf("\nTotal bytes written: %d\n", written);
sleep(3);
w.readData();
}
expected output:
77 31 31 32 33 34 a 77 32 35 36 37 a 77 33 38 39 a
Real output: longer than expected
36 37 a 77 33 38 39 a 77 31 31 32 33 34 a 77 32 35 36 37 a 77 33 38 39 a 77 31 31 32 33 34
or shorter
77 31 31 32 33
Thanks in advance for any help.