+1  A: 

Where are you allocating tagbuffer, how large is it?
It's possible that you are overwriting 'buf' because you are writing past the end of tagbuffer.

Martin Beckett
+1  A: 

It seems unlikely that those two lines would have that effect on a correct program - maybe you haven't allocated sufficient space in buf for the whole length of the string in tagBuffer? This might cause a buffer overrun that is disguising the real problem?

1800 INFORMATION
+1  A: 

The first thing I'd say is a piece of general advice: bugs aren't always where you think they are. If you've got something going on that doesn't seem to make sense, it often means that your assumptions somewhere else are wrong.

Here, it does seem very unlikely that an sprintf() and a WriteFile() will change the state of the "buf" array variable. However, those two lines of test code do write to "hSerial", while your main loop also reads from "hSerial". That sounds like a recipie for changing the behaviour of your program.

Suggestion: Change your lines of debugging output to store the output somewhere else: to a dialog box, or to a log file, or similar. Debugging output should generally not go to files used in the core logic, as that's too likely to change how the core logic behaves.

DavidK
Thanks for the advice.I removed those lines and output them to stdout This is what I got:buf is !tagBuffer is s!buf is !tagBuffer is h!buf is !tagBuffer is e!buf is !tagBuffer is l!buf is !tagBuffer is f!buf is !tagBuffer is 0!buf is !tagBuffer is 0!buf is !tagBuffer is 1!
Steve
It seems like buf is not storing anything
Steve
I'd also suggest adding logging to stdout in all the cases where your indexing variable 'i' gets re-set to zero. Is one of those cases getting triggered for every character read?
DavidK
A: 

In my opinion, the real problem here is that you're trying to read and write the serial port from a single thread, and this is making the code more complex than it needs to be. I suggest that you read the following articles and reconsider your design:

In a multithreaded implementation, whenever the reader thread reads a message from the serial port you would then post it to your application's main thread. The main thread would then parse the message and query the database, and then queue an appropriate response to the writer thread.

This may sound more complex than your current design, but really it isn't, as Newcomer explains.

I hope this helps!

ChrisN