473,883 Members | 1,591 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Handling input from a serial port using Visual C++

Sorry, don't know if this is the correct board for my question. I'm a novice so I guess I have a valid excuse

My question : I'm using Visual C++ and I need to collect data from a serial port. Specifically, I have a piece of equipment that outputs ASCII data to my computer through the serial port. Is there some way I can call the serial port from within Vis C++ and then save the data
I'd much rather do this than buy some sort of software, such as ProComm Plus or Hyper-terminal

Any and all help is appreciated - thank you.
Nov 17 '05 #1
4 16680
"Mike" <an*******@disc ussions.microso ft.com> wrote in message
news:9F******** *************** ***********@mic rosoft.com...
Sorry, don't know if this is the correct
board for my question.
Technically, the topic of this group is the C++ programming language as
implemented by Visual Studio. Practically, we get lots of questions on how
to use the language to do things.
I'm a novice so I guess I have a valid excuse.
:-) Unlike the USENET groups we don't sacrifice our trespassers. If I knew
of a more appropriate group I'd direct you.
My question : I'm using Visual C++ and I need
to collect data from a serial port. Specifically, I
have a piece of equipment that outputs ASCII data
to my computer through the serial port. Is there
some way I can call the serial port from within Vis
C++ and then save the data?


Yes, of course. Windows' mantra is "everything is a handle". So you open up
a COMM port and get a handle. Armed with a handle you call ReadFile() and
WriteFile() almost as though you were reading from a file. I say, "almost"
because COMM ports have some properties that files do not. For example, you
need to set parity bit attribute as well as a reasonable timeout policy.

What follows is a little HACK, completley devoid of anything resembling
correct error handling which opens up a port on which this box has a modem
(COM3), sends a Hayes command (ATI1 = identify) and receives the modem
response through the port.

I suggest you consult the MSDN for the names of functions which are
unfamiliar to you. It should get you started.

Regards,
Will

#include <windows.h>
#include <stdio.h>

int main(int argc, char **argv)
{
char szBuffer[80];
DCB dcb = {0};
DWORD dwRead, dwWritten;
HANDLE hComm;
OVERLAPPED ovlr = {0}, ovlw = {0};
COMMTIMEOUTS cto;

// Create events for overlapped operation

ovlr.hEvent = CreateEvent(NUL L, TRUE, FALSE, NULL);
ovlw.hEvent = CreateEvent(NUL L, TRUE, FALSE, NULL);

// Open the port

hComm = CreateFile("\\\ \.\\COM3", GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_ NORMAL | FILE_FLAG_OVERL APPED, NULL);

// Get the state of the device and modify it

dcb.DCBlength = sizeof(dcb);
GetCommState(hC omm, &dcb);
dcb.BaudRate = CBR_9600;
SetCommState(hC omm, &dcb);

// Set the timeout parameters nonsensically

cto.ReadInterva lTimeout = 1000;
cto.ReadTotalTi meoutConstant = 1000;
cto.ReadTotalTi meoutMultiplier = 1000;
cto.WriteTotalT imeoutConstant = 1000;
cto.WriteTotalT imeoutMultiplie r = 1000;

SetCommTimeouts (hComm, &cto);

// Send a command and receieve a response. Note that
// we post the receive in advance of sending the
// command in order not to miss anything

printf("\r\nSen ding: ATI1\r\n");

ReadFile (hComm, szBuffer, sizeof(szBuffer ), &dwRead, &ovlr);
WriteFile(hComm , "ATI1\r", strlen("ATI1\r" ), &dwWritten, &ovlw);

// Wait for the receive to complete and display the response

if ( GetOverlappedRe sult(hComm, &ovlr, &dwRead, TRUE) )
{
szBuffer[dwRead] = 0;
printf("Receive d: %s\r\n", szBuffer);
}

// Close the device

CloseHandle(hCo mm);

return 0;
}
Nov 17 '05 #2
"Mike" <an*******@disc ussions.microso ft.com> wrote in message
news:15******** *************** ***********@mic rosoft.com...
Thank you for the help.
You are welcome.
With the Read function - if I plan on continuously
reading form the serial port as my program
performs other functions, I have to use asynch
reading?
That depends on your protocol. When can "the other side" send? If it can do
that at any time then it would be wise to have one or more reads pending all
the time. In my little hack the other side is a modem and it only sends it
response to Hayes AT commands. So, I posted the read just before I issued
the write.
However, with the Write function I can simply
perform that at the end of my program using the
synch setup? (I've been looking through the MSDN,
but the examples haven't completely cleared this up for me)


There is always more than a little to know about async I/O (at least on
platforms that are modern enough to support it <g>). As much as it hurts you
may want to go back to the MSDN.

There you will find that there are extended variants of the read and write
functions ( ReadEx() and WriteEx() ) that allow for "completion routines" to
be called when the I/O operation has ended. They are a little like ASTs on
VAX/VMS (if that rings a bell) except that they are only dispatched when the
thread is in an "alertable wait" state. One strategy is to issue a
subsequent read in the completion routine for the previous one. In addition
there is the WaitCommEvent() function that allows you to wait on an
outstanding operation. Ultimately you will come up with something that make
sense in your scenario.

There used to be a COMM sample in the PSDK - I just checked and failed to
find it. If you have the SDK you may want to look for yourself.

Regards,
Will
Nov 17 '05 #3
Okay - a little more data..

I need to emulate ASCII data - this might be my current problem with the windings.
Nov 17 '05 #4
"Mike" <an*******@disc ussions.microso ft.com> wrote in message
news:29******** *************** ***********@mic rosoft.com...
well, the ReadFile returns a '1', which if I'm correct in
assuming means the program itself is working correctly.
It means that the read completed successfully as zero signifies failure. The
function's fourth parameter should contain the number of bytes actually read
which are deposited into the buffer pointed to by the third parameter.
Is this some sort of normal character that C++
would output, or does it seem more like an
equipment problem?


Perhaps neither. Are you sure the other side sent anything? If you don't
have a way of tracing the transmission, I would add either look at the
buffer and length with the debugger after every read, or if that screws up
the timing, I would log the buffer's content up to the number of bytes read
in a trace file.

Regards,
Will
Nov 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
1913
by: Daniel Åberg | last post by:
I can't find how I can, in c#, open a serial port and read and write to it. Anyone that knows if there is any namespace with methods or code example.
6
4147
by: IanHale | last post by:
Is there any way of simply using the COM port from Visual Basic? All the solutions I've found seem to require the use of Visual Studio whereas I only have the the 'basic' version. I'm not after anything too complicated as all I want to do is read a serial stream of data. Thanks in advance
1
3633
by: Mike | last post by:
Sorry, don't know if this is the correct board for my question. I'm a novice so I guess I have a valid excuse My question : I'm using Visual C++ and I need to collect data from a serial port. Specifically, I have a piece of equipment that outputs ASCII data to my computer through the serial port. Is there some way I can call the serial port from within Vis C++ and then save the data I'd much rather do this than buy some sort of software,...
3
2733
by: Hema Malini Rajanthiran | last post by:
to whom may concern...im final year student doing a project using handphone to create wireless communication. im finding difficulties to get the codes to connect to serial port using c#(visual studio .net 2000)...kindly guide me plz... thank, r.hema malini --
4
11214
by: joe bloggs | last post by:
I am writing a mobile application to interface with a legacy system and I am planning to use web services to communicate with this system. The legacy system receives data through a serial port. What I would like to do is make the serial port accessible via a web service. The web service and the legacy application would be running on the same machine. The mobile application would access the web service via a network connection. It...
2
5262
by: hani | last post by:
hi, i'm try to do a program that can read serial port in web page. can anyone give me any opinion to do this? i've download the javacomm and try the examples. i'ts working. but it is in java client. someone advise me to use javabean. buat i don't quite understand how. thank you.
2
1856
by: Prasanth MN | last post by:
Hai, I want to write Hex codes in to serial port using visual basic 6. How I can write this program. Please give me a small sample program. thanks
2
2358
by: yo2osv | last post by:
I want read serial port and show on the screen using C programing
1
3113
by: Deigor | last post by:
Hi i am working on serial port programming using CreateFile function in VC. This function runs well in Visual Studio 6, while the same instruction fail to execute in VS2005. Can any one tell what will be the correct syntex or the possible cause of error. hComm = CreateFile("COM1:",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0); the above function runs fine in VS6 but it gives error no 2664: in VS2005. telling that "cannot convert...
3
5367
by: Mary Mah | last post by:
Hi, iam building a system which will send data from website to serial port using PHP, the problem that i want to send bits to the serial port not only data. i wrote a php code to do so but it still give me errors...any help please ?!? CODE: <?php require("php_serial.class.php"); $serial = new phpSerial(); $serial->deviceSet("COM1");
0
9943
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9793
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11151
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10419
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7974
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7134
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5804
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
4225
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3237
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.