I've really basic knowledge on C++ and I'm trying to read/write Serial Port by using Visual Studio. I'm trying to use Boost::Asio but I'm always getting similar errors. While I'm trying to run the code below I'm getting "Error: open: The parameter is incorrect".
To make sure serial port and my device is working correctly, I used another application. I'm able to read/write without no problem. After my test I closed my application to not to cause any problem.
UPDATE: By using Virtual Serial Port Emulator(VSPE) I created pair of ports(COM1 and COM2). I used COM1 in C++ and COM2 in RealTerm. By this I successfully read/write data with my code without any problem. But while I'm trying to access COM6, I still get same error. An FPGA connected to that port and I also tested FPGA with RealTerm which is able to read/write, means working as I expected. So, It's look like my problem is accessing to the COM6 port. Looking for your advice.
I'm open to any kind of suggestion.
#include <iostream>
#include "SimpleSerial.h"
using namespace std;
using namespace boost;
int main(int argc, char* argv[])
{
try {
SimpleSerial serial("COM6", 115200);
serial.writeString("Hello world\n");
cout << serial.readLine() << endl;
}
catch (boost::system::system_error & e)
{
cout << "Error: " << e.what() << endl;
return 1;
}
}
I found this SimpleSerial Class online and tried to make basic application.
class SimpleSerial
{
public:
/**
* Constructor.
* \param port device name, example "/dev/ttyUSB0" or "COM4"
* \param baud_rate communication speed, example 9600 or 115200
* \throws boost::system::system_error if cannot open the
* serial device
*/
SimpleSerial(std::string port, unsigned int baud_rate)
: io(), serial(io, port)
{
serial.set_option(boost::asio::serial_port_base::baud_rate(baud_rate));
}
/**
* Write a string to the serial device.
* \param s string to write
* \throws boost::system::system_error on failure
*/
void writeString(std::string s)
{
boost::asio::write(serial, boost::asio::buffer(s.c_str(), s.size()));
}
/**
* Blocks until a line is received from the serial device.
* Eventual '\n' or '\r\n' characters at the end of the string are removed.
* \return a string containing the received line
* \throws boost::system::system_error on failure
*/
std::string readLine()
{
//Reading data char by char, code is optimized for simplicity, not speed
using namespace boost;
char c;
std::string result;
for (;;)
{
asio::read(serial, asio::buffer(&c, 1));
switch (c)
{
case '\r':
break;
case '\n':
return result;
default:
result += c;
}
}
}
private:
boost::asio::io_service io;
boost::asio::serial_port serial;
};