WriteFile() and ReadFile() asynchronously not writing or reading - c++

I'm trying to send and receive strings across a serial port connection using the writefile and readfile functions. I have to do this asynchronously because the number of bytes to read will always be different and readfile will just hang or block until it gets those correct number of bytes. Now that I'm trying to do this asynchronously my writefile function won't send any data and my readfile function just appears to be skipped because the next line begins doing it's thing without any characters being read. Not sure if it's a problem with my Overlapped structure or my timeouts. But I'm stuck at this moment.
Timeouts
void Serial::OpenPortRead()
{
HANDLE sSerial = CreateFile(L"COM3",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,0);
//Timeout Settings
COMMTIMEOUTS CommTimeouts;
GetCommTimeouts(sSerial, &CommTimeouts);
CommTimeouts.ReadIntervalTimeout = 5000;
CommTimeouts.ReadTotalTimeoutMultiplier = 2;
CommTimeouts.ReadTotalTimeoutConstant = 10;
CommTimeouts.WriteTotalTimeoutMultiplier = 50;
CommTimeouts.WriteTotalTimeoutConstant = 500;
//Port Settings
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
dcbSerialParams.BaudRate=CBR_19200;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;
SetCommState(sSerial,&dcbSerialParams);//Apply Settings to Handle
}
Write file function
void Serial::WritePort(CString buffer)
{
DWORD bytes;//pointer to hold number of bytes written
USES_CONVERSION;
CW2A buf((LPCWSTR)buffer);//Convert unicode to ascii
OpenPortRead();
OVERLAPPED overlapped_structure;
memset(&overlapped_structure, 0, sizeof(overlapped_structure));
overlapped_structure.Offset = 0;
overlapped_structure.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
WriteFile(sSerial, buf,strlen(buf),&bytes,&overlapped_structure);//Send string
}
Read file function
int Serial::ReadPort(CString buf){
OpenPortRead();// Open Serial Communication for reading
const int buffer_size = 10;
char buffer[10];//buffer to hold recieved string
memset (buffer, 0, buffer_size * sizeof (char));
int n, num,iTemp,i=0;
OVERLAPPED overlapped_structure;
memset(&overlapped_structure, 0, sizeof(overlapped_structure));
overlapped_structure.Offset = 0;
overlapped_structure.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
DWORD bytesRead;//pointer to number bytes read
ReadFile(sSerial,&buffer,buffer_size,&bytesRead,&overlapped_structure);// begin read
//Used this function because return would be filled with extra raw data characters
buffer[n] = StringLength(buffer, &n);//find length of string returned
num = n;

MSDN contains detailed information about how to use overlapped I/O with serial port communications:
Serial Communications

Related

read() not returning Specified amount of Bytes

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);
}
I am assuming this is a Linux system....
Your BytesToRead variable is only a suggestion to read() in that read() will try to read up to BytesToRead. If read() returns less than your requested amount, then fewer bytes were available to be read.
From the linux manpage on read
... It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal...
It is possible that your sensor is not sending the data you expect, or you are not giving it enough time to transfer all of the data, or there is some other logic/hardware problem that is not apparent from your code example.
read() is not guaranteed to return the number of bytes requested:
From the read(2) Linux manpage:
On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. On error, -1 is returned, and errno is set appropriately. In this case it is left unspecified whether the file position (if any) changes.

C++ doesn't receive data with ReadFile/WriteFile when I'm trying to talk to a TTI device

I come to you because I have some problems when I trying to write a driver supporting the QL355P from TTI. I already wrote the driver in VB6, but now, I am trying to write it in C++. I use the ReadFile/WriteFile function to communicate with the interface. The problem is when I send the identification command (*IDN?) and the endchar (.), I have no response (I have Statut_timeout).
My code is:
DCB l_dcb;
BOOL l_Success;
COMMTIMEOUTS l_TimeOuts;
const char *command = "*IDN?.";
// open an access to serial port
m_ComPort = CreateFile(L"COM2",
GENERIC_READ | GENERIC_WRITE,
0, // comm devices must be opened w/exclusive-access
NULL, // no security attrs
OPEN_EXISTING, // comm devices must use OPEN_EXISTING
0, // not overlapped I/O
NULL // hTemplate must be NULL for comm devices
);
// get the current configuration
l_Success = GetCommState(m_ComPort, &l_dcb);
// fill in the DCB with configuation:
// baud=19200, 8 data bits, no parity, 1 stop bit
l_dcb.BaudRate = 19200;
l_dcb.ByteSize = 8;
l_dcb.Parity = NOPARITY;
l_dcb.StopBits = ONESTOPBIT;
// configure the port
l_Success = SetCommState(m_ComPort, &l_dcb);
// get the current time-outs configuration
l_Success = GetCommTimeouts(m_ComPort, &l_TimeOuts);
// change the time-outs
l_TimeOuts.ReadIntervalTimeout=50;
l_TimeOuts.ReadTotalTimeoutMultiplier=50;
l_TimeOuts.ReadTotalTimeoutConstant=1000;
// sets the time-outs configuration
l_Success = SetCommTimeouts(m_ComPort, &l_TimeOuts);
// first purge the input buffer
PurgeComm(m_ComPort,PURGE_RXCLEAR);
// send the command
DWORD l_NumBytesTransfered=0;
DWORD l_NumBytesToTransfer=strlen(command);
l_Success = WriteFile(m_ComPort,command,l_NumBytesToTransfer,&l_NumBytesTransfered,NULL);
//Try to read
char l_Char='*';
int i=0;
char l_Pointer[100];
while(l_Char !=0x0a && i<100)
{
l_Success = ReadFile(m_ComPort,&l_Char,1,&l_NumBytesTransfered,NULL);
l_Pointer[i] = l_Char;
i++;
}
CloseHandle(m_ComPort); //close the handle
ReadFile can return 0 in case of a timeout, or various possible errors. Your code snippet ignores that possibility and puts garbage into the input array even when ReadFile fails.

Unable to receive data from serial port

Currently I try to write a serial port communication in VC++ to transfer data from PC and robot via XBee transmitter. But after I wrote some commands to poll data from robot, I didn't receive anything from the robot (the output of filesize is 0 in the code.). Because my MATLAB interface works, so the problem should happen in the code not the hardware or communication. Would you please give me help?
01/03/2014 Updated: I have updated my codes. It still can not receive any data from my robot (the output of read is 0). When I use "cout<<&read" in the while loop, I obtain "0041F01C1". I also don't know how to define the size of buffer, because I don't know the size of data I will receive. In the codes, I just give it a random size like 103. Please help me.
// This is the main DLL file.
#include "StdAfx.h"
#include <iostream>
#define WIN32_LEAN_AND_MEAN //for GetCommState command
#include "Windows.h"
#include <WinBase.h>
using namespace std;
int main(){
char init[]="";
HANDLE serialHandle;
// Open serial port
serialHandle = CreateFile("\\\\.\\COM8", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
// Do some basic settings
DCB serialParams;
DWORD read, written;
serialParams.DCBlength = sizeof(serialParams);
if((GetCommState(serialHandle, &serialParams)==0))
{
printf("Get configuration port has a problem.");
return FALSE;
}
GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = CBR_57600;
serialParams.ByteSize = 8;
serialParams.StopBits = ONESTOPBIT;
serialParams.Parity = NOPARITY;
//set flow control="hardware"
serialParams.fOutX=false;
serialParams.fInX=false;
serialParams.fOutxCtsFlow=true;
serialParams.fOutxDsrFlow=true;
serialParams.fDsrSensitivity=true;
serialParams.fRtsControl=RTS_CONTROL_HANDSHAKE;
serialParams.fDtrControl=DTR_CONTROL_HANDSHAKE;
if (!SetCommState(serialHandle, &serialParams))
{
printf("Set configuration port has a problem.");
return FALSE;
}
GetCommState(serialHandle, &serialParams);
// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 30;
timeout.ReadTotalTimeoutConstant = 30;
timeout.ReadTotalTimeoutMultiplier = 30;
timeout.WriteTotalTimeoutConstant = 30;
timeout.WriteTotalTimeoutMultiplier = 30;
SetCommTimeouts(serialHandle, &timeout);
if (!SetCommTimeouts(serialHandle, &timeout))
{
printf("Set configuration port has a problem.");
return FALSE;
}
//write packet to poll data from robot
WriteFile(serialHandle,">*>p4",strlen(">*>p4"),&written,NULL);
//check whether the data can be received
char buffer[103];
do {
ReadFile (serialHandle,buffer,sizeof(buffer),&read,NULL);
cout << read;
} while (read!=0);
//buffer[read]="\0";
CloseHandle(serialHandle);
return 0;
}
GetFileSize is documented not to be valid when used with a serial port handle. Use the ReadFile function to receive serial port data.
You should use strlen instead of sizeof here:
WriteFile(serialHandle,init,strlen(init),&written,NULL)
You would be even better off creating a function like this:
function write_to_robot (const char * msg)
{
DWORD written;
BOOL ok = WriteFile(serialHandle, msg, strlen(msg), &written, NULL)
&& (written == strlen(msg));
if (!ok) printf ("Could not send message '%s' to robot\n", msg);
}
But that's only the appetizer. The main trouble is, as MDN says:
You cannot use the GetFileSize function with a handle of a nonseeking device such as a pipe or a communications device.
If you want to read from the port, you can simply use ReadFile until it returns zero bytes.
If you already know the max size of your robot's response, try reading that many characters.
Continue reading until the read reports an actual number of bytes read inferior to the size of the buffer. For instance:
#define MAX_ROBOT_ANSWER_LENGTH 1000 /* bytes */
const char * read_robot_response ()
{
static char buffer[MAX_ROBOT_ANSWER_LENGTH];
DWORD read;
if (!ReadFile (serialHandle, buffer, sizeof(buffer), &read, NULL))
{
printf ("something wrong with the com port handle");
exit (-1);
}
if (read == sizeof(buffer))
{
// the robot response is bigger than it should
printf ("this robot is overly talkative. Flushing input\n");
// read the rest of the input so that the next answer will not be
// polluted by leftovers of the previous one.
do {
ReadFile (serialHandle, buffer, sizeof(buffer), &read, NULL);
} while (read != 0);
// report error
return "error: robot response exceeds maximal length";
}
else
{
// add a terminator to string in case Mr Robot forgot to provide one
buffer[read] = '\0';
printf ("Mr Robot said '%s'\n", buffer);
return buffer;
}
}
This simplistic function returns a static variable, which will be overwritten each time you call read_robot_response.
Of course the proper way of doing things would be to use blocking I/Os instead of waiting one second and praying for the robot to answer in time, but that would require a lot more effort.
If you feel adventurous, you can use overlapped I/O, as this lenghty MDN article thoroughly explores.
EDIT: after looking at your code
// this reads at most 103 bytes of the answer, and does not display them
if (!ReadFile(serialHandle,buffer,sizeof(buffer),&read,NULL))
{
printf("Reading data to port has a problem.");
return FALSE;
}
// this could display the length of the remaining of the answer,
// provided it is more than 103 bytes long
do {
ReadFile (serialHandle,buffer,sizeof(buffer),&read,NULL);
cout << read;
}
while (read!=0);
You are displaying nothing but the length of the response beyond the first 103 characters received.
This should do the trick:
#define BUFFER_LEN 1000
DWORD read;
char buffer [BUFFER_LEN];
do {
if (!ReadFile(
serialHandle, // handle
buffer, // where to put your characters
sizeof(buffer) // max nr of chars to read
-1, // leave space for terminator character
&read, // get the number of bytes actually read
NULL)) // Yet another blody stupid Microsoft parameter
{
// die if something went wrong
printf("Reading data to port has a problem.");
return FALSE;
}
// add a terminator after last character read,
// so as to have a null terminated C string to display
buffer[read] = '\0';
// display what you actually read
cout << buffer;
}
while (read!=0);
I advised you to wrap the actual calls to serial port accesses inside simpler functions for a reason.
As I said before, Microsoft interfaces are a disaster. They are verbose, cumbersome and only moderately consistent. Using them directly leads to awkward and obfuscated code.
Here, for instance, you seem to have gotten confused between read and buffer
read holds the number of bytes actually read from the serial port
buffer holds the actual data.
buffer is what you will want to display to see what the robot answered you
Also, you should have a documentation for your robot stating which kind of answers you are supposed to expect. It would help to know how they are formatted, for instance whether they are null-terminated strings or not. That could dispense to add the string terminator.

C++(Serial Communicatio using the <windows.h>) - How can i find out before hand, how many characters will be read by the ReadFile() method

ReadFile( hSerial , buffer , 25, &dwBytesRead , 0);
Hey ppl
My question is how do i find out how many characters my ReadFile statement will return before calling the ReadFile?. The device i am communicating with, returns different data based on what was sent. Concerning the above ReadFile, in that instance i knew that the returned data would be 25 characters long, but what if i dont know the answer, how can i substitute 25 with a variable that will be enough for any amount of data received.
In my code you will see i have 2 Readfile statements, in both cases i knew the amount of data i would receive, to i sent a fixed number, what happens when i dont know that amount?
#include "stdafx.h"
#include "windows.h"
BOOL SetCommDefaults(HANDLE hSerial);
void StripCRLFandPrint(char *command);
char buffer[1000];
HANDLE hSerial;
DWORD dwBytesRead = 0;
DWORD dwBytesWritten = 0;
char trash;
int main(int argc, char* argv[])
{
hSerial = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0 , 0 , OPEN_EXISTING , 0 , 0);
if (hSerial == INVALID_HANDLE_VALUE) return GetLastError();
SetCommDefaults(hSerial);//Initializing the Device Control Block
COMMTIMEOUTS timeouts={0};
timeouts.ReadIntervalTimeout=50;
timeouts.ReadTotalTimeoutConstant=50;
timeouts.ReadTotalTimeoutMultiplier=10;
timeouts.WriteTotalTimeoutConstant=50;
timeouts.WriteTotalTimeoutMultiplier=10;
char szRxChar[3];//varialble holds characters that will be sent
szRxChar[0] = '?';
DWORD y =0, z =0;
char buf[327];// will hold the data received
memset(buf,0,327);//initializing the buf[]
memset(buffer,0,10000);
WriteFile( hSerial , &szRxChar , 1, &dwBytesWritten ,0);
ReadFile( hSerial , buf , sizeof(buf), &dwBytesRead , 0);
printf("Retrieving data...\n\n");
//Displaying the buffer
printf( "%s",buf);
printf("\nData Read: %i\n",dwBytesRead);
printf("Enter an option:");
scanf("%c%c",&szRxChar,&trash);//Reading the next command to be sent
while(szRxChar[0] != '1')//Press one to exit
{
memset(buffer,0,10000);
//StripCRLFandPrint(szRxChar);
WriteFile( hSerial , &szRxChar, 1, &dwBytesWritten ,0);
ReadFile( hSerial , buffer , 25, &dwBytesRead , 0);
printf("%s",buffer);
printf("\nData Read: %i\n",dwBytesRead);
printf("\n");
printf("Enter an Option:");
scanf("%c%c",&szRxChar,&trash);
}
CloseHandle(hSerial);// Closing the handle
return 0;
}
You can't know what you are asking for, because no software can make predictions regarding the behaviour of a remote end. For this reason, the reading should take place in a different thread. In the reading thread you can instruct ReadFile to read one byte at a time. You can choose to read more bytes at the same time, but then you are running the risk of having received a full message from the other part and still do not get a notification, because ReadFile is blocked waiting for more data.
It may be challenging to create the threading code yourself. I recommend that you search for a library that already handles this for you.
You won't ever know exactly what was sent, but instead of putting 25, use sizeof(buffer) instead.
Keep in mind that ReadFile() isn't perfect. I have experienced issues on slower hardware whereas ReadFile() does not always read in the complete message sent over the COM port. Therefore, it may be beneficial to read in byte-by-byte, albeit slower, to ensure you get the entire message:
int c;
DWORD dwBytesRead = 0;
if (!(pcState[readerPort] & PORT_OPEN)) {
RecvIndex = 0;
Sleep(1000);
return;
}
ReadFile(hComm[readerPort], buff, 1, &dwBytesRead, NULL); // array of handles used here
c = buff[0];
if (dwBytesRead == 0) { // possible end of transmission
if (RecvTimer++ > 3) {
RecvTimer = 0;
if (RecvIndex) { // have receive some data prior
keyBuf[RecvIndex] = 0;
RecvIndex = 0;
processBuffer(keyBuf);
memset(keyBuf, 0, sizeof(keyBuf));
}
}
} else {
RecvTimer = 0; //Restart timer
if (RecvIndex == 0) { // first character
memset(keyBuf, 0, sizeof(keyBuf));
keyBuf[0] = (unsigned char)c;
RecvIndex = 1;
} else { // get remaining characters
if (RecvIndex < sizeof(keyBuf))
keyBuf[RecvIndex++] = (unsigned char)c;
}
}
in the example above, keyBuf is a private class variable and the above code is part of a function that is called in a while loop.

Serial Port communication with Arduino and C++

I am having a problem with a Serial Port communication between Arduino Nano and C++, even though the problem is in C++ side. Basically I want to send integers (or long,...) from the Arduino to a C++ program to be processed.
First I did a test sending information from the Arduino to the computer using Matlab. The Arduino code is pretty simple:
int i = 0;
void setup() {
// start serial port at 9600 bps:
Serial.begin(9600);
establishContact();
}
void loop() {
Serial.println(i);
i=i+1;
delay(10);
}
void establishContact() {
while (Serial.available() <= 0) {
Serial.println('A', BYTE);
delay(10);
}
}
The Matlab side is also simple:
clc;
clear all;
numSec=2;
t=[];
v=[];
s1 = serial('COM3'); % define serial port
s1.BaudRate=9600; % define baud rate
set(s1, 'terminator', 'LF'); % define the terminator for println
fopen(s1);
try % use try catch to ensure fclose
% signal the arduino to start collection
w=fscanf(s1,'%s'); % must define the input % d or %s, etc.
if (w=='A')
display(['Collecting data']);
fprintf(s1,'%s\n','A'); % establishContact just wants
% something in the buffer
end
i=0;
t0=tic;
while (toc(t0)<=numSec)
i=i+1;
t(i)=toc(t0);
t(i)=t(i)-t(1);
v(i)=fscanf(s1,'%d');
end
fclose(s1);
plot(t,v,'*r')
catch me
fclose(s1);
end
My goal is, with C++, do the same that is done in Matlab using fscanf(s1, '%d').
Here is the current code that I am using (C++ code):
void main()
{
HANDLE hSerial;
hSerial = CreateFile(TEXT("COM3"),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,//FILE_FLAG_OVERLAPPED,
NULL);
if ( hSerial == INVALID_HANDLE_VALUE)
{
printf("Error initializing handler");
}
else
{
// Set the parameters of the handler to the serial port.
DCB dcb = {0};
dcb.DCBlength = sizeof(dcb);
if ( !GetCommState(hSerial, &dcb) )
{
printf("Error setting parameters");
}
FillMemory(&dcb, sizeof(dcb), 0);
dcb.BaudRate = CBR_9600;
dcb.ByteSize = 8;
dcb.StopBits = ONESTOPBIT;
dcb.Parity = NOPARITY;
if ( !SetCommState(hSerial, &dcb) )
{
// error setting serial port state.
}
// Tell the program not to wait for data to show up
COMMTIMEOUTS timeouts = {0};
timeouts.ReadIntervalTimeout = 0;//20;
timeouts.ReadTotalTimeoutConstant = 0;//20;
timeouts.ReadTotalTimeoutMultiplier = 0;//50;
timeouts.WriteTotalTimeoutConstant = 0;//100;
timeouts.WriteTotalTimeoutMultiplier = 0;//100;
if ( !SetCommTimeouts(hSerial, &timeouts) )
{
printf("Error setting the timeouts");
}
char szBuff[5] = "";
DWORD dwBytesRead = 0;
int i = 0;
char test[] = "B\n";
int maxSamples = 10;
DWORD dwCommStatus;
WriteFile(hSerial, test, 2, &dwBytesRead, NULL);
SetCommMask(hSerial,EV_RXCHAR);
while (i < maxSamples)
{
WaitCommEvent (hSerial, &dwCommStatus, 0);
if (dwCommStatus & EV_RXCHAR)
{
memset(szBuff,0,sizeof(szBuff));
ReadFile(hSerial, LPVOID(szBuff), 4, &dwBytesRead, NULL);
cout<<szBuff;
printf(" - %d - \n", atoi(szBuff));
}
i++;
}
scanf("%d", &i);
CloseHandle(hSerial);
}
}
The goal of my code would be something like num = ReadSerialCOM(hSerial, "%d");
My current C++ code reads the information from the buffer, but there is not an accepted end of line, which implies that my numbers (integers) are received cut.
Eg:
I send 8889 from the Arduino, which places it in the COM port. And the command ReadFile saves '88' into szBuff. At the next iteration '89\n' is saved into sZBuff. Basically I want to avoid to post-process sZBuff to concat '88' and '89\n'.
Anyone?
Thanks!
If I understand your question correctly, one way to avoid having to 'post-process' is to move the pointer passed to ReadFile to the end of the available data, so the ReadFile call is appending to the buffer, instead of overwriting.
Essentially, you would have two pointers. One to the buffer, the other to the end of the data in the buffer. So when your program starts, both pointers will be the same. Now, you read the first 2 bytes. You increment the end-of-data pointer by 2. You do another read, but instead of szBuff, you pass a pointer to the end of the previously read data. You read the next three bytes and you have the complete entry in szBuff.
If you need to wait until some delimiter to mark the end of an entry is received, you could just search the received data for it. If it's not there, you keep reading until you find it. If it is there, you can just return.
// Fill the buffer with 0
char szBuff[256] = {0};
// We have no data in the buffer, so the end of data points to the beginning
// of the buffer.
char* szEndOfData = szBuff;
while (i < maxSamples)
{
WaitCommEvent (hSerial, &dwCommStatus, 0);
if (dwCommStatus & EV_RXCHAR)
{
// Append up to 4 bytes from the serial port to the buffer
ReadFile(hSerial, LPVOID(szEndOfData), 4, &dwBytesRead, NULL);
// Increment the end of data pointer, so it points to the end of the
// data available in the buffer.
szEndOfData += dwBytesRead;
cout<<szBuff;
printf(" - %d - \n", atoi(szBuff));
}
i++;
}
// Output, assuming what you mentioned happens:
// - 88 -
// - 8889 -
If this approach is acceptable to you, it will require a bit more work. For example, you would have to ensure you don't overflow your buffer. When you remove data from the buffer, you'll have to move all of the data after the removed segment to the beginning, and fix the end of data pointer. Alternatively, you could use a circular buffer.
As Hans Passant and dauphic pointed, it doesn't seem to be a general solution for my question. I am writing, though, the code that I was trying to avoid, just in case somebody finds it useful or face the same problem that I had:
int i = 0;
DWORD dwBytesRead = 0;
DWORD dwCommStatus = 0;
char szBuff[2] = "";
int maxRead = 20;
int sizeNum = 1;
int *num = (int*)malloc(maxRead*sizeof(int));
char *currNum;
char *pastNum;
// Write something into the Serial Port to start receive
// information from the Arduino
WriteFile(hSerial, (LPCVOID)"A\0", 1, &dwBytesRead, NULL);
SetCommMask(hSerial, EV_RXCHAR);
// Start reading from the Serial Port
while ( i < maxRead )
{
WaitCommEvent (hSerial, &dwCommStatus, 0);
if (dwCommStatus & EV_RXCHAR) // if a char is received in the serial port
{
ReadFile(hSerial, LPVOID(szBuff), 1, &dwBytesRead, NULL);
if ( szBuff[0] > 47 && szBuff[0] < 58 )
{
sizeNum++;
if (sizeNum ==2)
{
currNum = (char*)malloc(sizeNum*sizeof(char));
strcpy(currNum, szBuff);
} else
{
if (pastNum != NULL)
free(pastNum);
pastNum = currNum;
currNum = (char*)malloc(sizeNum*sizeof(char));
strcpy(currNum, pastNum);
strcpy(currNum+(sizeNum-2)*sizeof(char), szBuff);
}
cout << szBuff<<endl;
} else if (szBuff[0] == '\n' && sizeNum > 1) // end of number
{
num[i] = atoi(currNum);
i++;
sizeNum = 1;
if (currNum!=NULL)
free(currNum);
}
}
}