Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading from serial port returns ASCII code of character received

Status
Not open for further replies.

Kuns

Programmer
Mar 31, 2007
2
0
0
FR
Note: I use Visual C++ 2005

I would like to read the received character from the serial port (e.g. 'a', 'b', ...). Instead I get the ASCII code of the character I received (97, 98, ...). Here's the code I use:

//defining the serial port
System::IO::ports::SerialPort^ mySerialPort;

...

//in the function
String^ string;
cli::array<unsigned char>^ buffer;
buffer = gcnew <unsigned char>(1);

mySerialPort->Open();
mySerialPort->Read(buffer,0,1);
string += buffer->getValue(0);
MessageBox::Show(string,"Character received");

Thanks for your Help
 
Maybe make buffer a regular char rather than an unsigned char.

Maybe cast the result of getValue() into a char.

I'm guessing that string += only does what you want when the thing being added is a char, for everything else it invokes the 'toString' conversion for whatever type it is, then appends the result of that to your string.

Oh, and please use [code][/code] tags when posting code.


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Hi Salem,

Thanks to your two suggestions I now am sure that the problem is the one you evoke: using string+= invokes the 'toString' conversion and gives me the ASCII code of the character.

I cannot yet find the solution:

- "Maybe make buffer a regular char rather than an unsigned char." I cannot because the mySerialPort->Read() function takes as first parameter a cli::array<unsigned char>^.

- "Maybe cast the result of getValue() into a char." Even when casting it back to a char the fact of using the string+= still puts the ASCII code of the character into string.

So my problem actually how to transform an array of unsigned char into a String?
 
Since your array is only 1 char long anyway, it seems a moot point to call it an array.

But anyway
Code:
char temp = buffer->getValue(0);
string += temp;
Does this still append '97' in place of 'a' ?


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top