I am reading the Sensor data (broadcasted on RS232) with read() function. The data rate is 264 Bytes / Sec.
I am using the following code to read the data (I just needed to read 60 Bytes).
int BytesToRead = 60;
unsigned char* iBuffer = new unsigned char[BytesToRead];
int ret = read(COM, iBuffer, BytesToRead);
cout<<ret<<endl;
if (ret == 0) {
cout<<"Error Reading COM Port"<<endl;
exit(EXIT_FAILURE); // Error Handling
}
delete[] iBufer;
And this program is returning random bytes (~30).
I am a beginner for C++ programming. Sorry, If I am doing some stupid mistake.
Thanks.
My COM function:
int Connect(const char *DeviceName){
long BAUD = B115200;
long DATABITS = CS8; // CS8 = 8n1 Config.(8 bits, No parity, 1 Stop Bit)
long VMIN_CC = 1; // 1 input byte is enough to return from read()
long VTIME_CC = 0; // Inter-character timer
long STOPBITS = 0; // Defined with CS8
long PARITYON = 0; // NONE (Ref.: IH2 Azzura Hand User Guide)
long PARITY = 0; // NONE (Ref.: IH2 Azzura Hand User Guide)
struct termios config; // Configuration of the termios structure
fd_set rdset; // File discription set
//Basic serial interface configuration
//iflag = Input flag || oflag = Output flag || lflag = No-line processing flag
//c_cflag = Caracter processing flag || c_cc = Special character flag
memset(&config,0,sizeof(config));
config.c_iflag = 0; // Turning OFF Input processing
config.c_oflag = 0; // Turning OFF Output processing
config.c_lflag = 0;
config.c_cflag = DATABITS |CREAD|CLOCAL;// Enable the receiver and set local mode
config.c_cc[VMIN] = VMIN_CC;
config.c_cc[VTIME] = VTIME_CC;
//Opening the Port for communication
int com = open(DeviceName, O_RDWR | O_NOCTTY);
//Error Handling
if (com < 0) {
cout<<"ERROR!! Opening Port \n"<<"Sys:"<<strerror(errno)<<endl;
exit(EXIT_FAILURE);
} else {cout<<"Serial Communication (Opening Port): "<<strerror(errno)<<endl;}
//Setting the BaudRate for Communcation
cfsetispeed(&config, BAUD);
cfsetospeed(&config, BAUD);
//Applying Configuration / Attributes
int Attr = tcsetattr(com, TCSANOW, &config);
//Error Handling
if(Attr < 0){
cout<<"ERROR!! Setting Attributes \n"<<"Sys:"<< strerror(errno)<<endl;
exit(EXIT_FAILURE);
} else {cout<<"Serial Communication (Setting Attributes): "<<strerror(errno)<<endl;}
return(com);
}
COMobject. Like stijn points out, the third param to the read(...) should be a size_t (unsigned integer type), and not an int. When you say "random bytes" do you mean you get 30 meaningful bytes, and 30 bad ones? Or do you only get 30 bytes all of garbage?BytesToReadasize_twould be better style, but making it anintis not an error. The argument is implicitly converted to the correct type, and as long as the number of bytes doesn't exceedINT_MAX(which is at least 32767), usingintwon't cause any actual problems.