Reputation: 97
I am working on a multi threading program to read and write to a serial port. If I test my application with Putty everything is fine. But when I test it with the created .exe-file, it doesn't work. (I start the program in VS2017 and then the .exe file)
E.g.: My input: "Test", the output in the other window: "Teeeeeeeeeeeessssssssssttttttt".
My code to send the data:
void SendDataToPort()
{
for (size_t i = 0; i <= strlen(line); i++) // loop through the array until
every letter has been sent
{
try
{
if (i == strlen(line)) // If ever letter has been sent
{ // end it with a new line
c = '\n'; // a new line
}
else
{
c = line[i];
}
WriteFile(serialHandle, &c, 1, &dwBytesWrite, NULL); // Send letter to serial port
}
catch (const exception&)
{
cout << "Error while writing.";
}
}
cout << endl << "Sent." << endl;
}
In the array "line" I have the input from the user.
My code to read the data:
int newLineCounter = 0;
unsigned char tmp;
while (!endCurrentRead)
{
ReadFile(hSerial, &tmp, 1, &bytesRead, NULL); // Get new letter
if (tmp != '\n')
{
newLineCounter = 0;
if (tmp >= 32 && tmp <= 126)
{
output += tmp; // Add current letter to the output
}
}
else
{
newLineCounter++;
if (newLineCounter < 2) // If there are more than 2 '\n' it doesn't write it down
{
output += tmp;
}
else if (newLineCounter == 2)
{
Print(output);
output = receiverName;
endCurrentRead = true;
}
}
}
After that I write the data down with the Print(output) function:
cout << output << endl;
How I create the Handle File:
serialHandle = CreateFile(LcomPort, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
Why is this happening and why is this only happening when I test it with the .exe-file and not with Putty?
Upvotes: 1
Views: 1793
Reputation: 97
Thanks to the help of @quetzalcoatl, I was able to solve the problem. I have to check if the bytesRead
are bigger then 0.
Solution:
int newLineCounter = 0;
DWORD dwCommModemStatus;
unsigned char tmp;
while (!endCurrentRead)
{
ReadFile(hSerial, &tmp, 1, &bytesRead, NULL); // Get new letter
if (bytesRead > 0)
{
if (tmp != '\n')
{
newLineCounter = 0;
if (tmp >= 32 && tmp <= 126)
{
output += tmp; // Add current letter to the output
}
}
else
{
output += tmp;
Print(output);
output = receiverName;
endCurrentRead = true;
}
}
}
Upvotes: 2