accessing serial COM port using c++

Jul 18, 2011 at 11:48am
hello,
can i access a serial COM port to send and receive data.....
are there any built in classes or functions...
Last edited on Jul 18, 2011 at 12:37pm
Jul 18, 2011 at 2:32pm
can i access a serial COM port to send and receive data.....
Sure you can.

are there any built in classes or functions...
Depends for what OS do you want to develop. .Net or ASIO/Boost provides support for that.

Jul 18, 2011 at 5:08pm
for windows7...
Jul 19, 2011 at 2:42am
but using it in command line might be enough...
i need to send and receive pieces of strings and characters...
i dunno anything about
.Net or ASIO/Boost

i only know c,c++, and some simple python
Last edited on Jul 19, 2011 at 5:51am
Jul 19, 2011 at 10:58am
Well, accessing the serial port is not quite trivial. Maybe it's the best to use the (win-) API directly:

To open the port use CreateFile like so:
1
2
3
HANDLE h = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
...
CloseHandle(h );


To change the settings of the serial port you need the 'DCB' like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
DCB dcb;
memset(&dcb, 0, sizeof(dcb));
dcb.DCBlength = sizeof(DCB);

dcb.fBinary = true;
dcb.BaudRate = CBR_9600;
dcb.ByteSize = 8;
dcb.StopBits = ONESTOPBIT;
dcb.Parity   = NOPARITY;
dcb.fParity  = false;

dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fTXContinueOnXoff = true;
dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
dcb.XoffChar = 0x13;
dcb.XonChar = 0x11;
dcb.XoffLim = 10;
dcb.XonLim = 10;

if(SetCommState(h, &dcb) != FALSE)
  ...


The 'DCB' structure is extensive. You need to figure out all the elements
Topic archived. No new replies allowed.