C# Serial Communication and ASCII Problems

I am using a C# form application to send data from the computer to the arduino decimilia through the usb virtual serial port. I have a 5 digit integer in the form of a string that is being sent through the serial port.

How do I read this string into the arduino and convert it to an integer?

You'll find what you need right there:

http://www.arduino.cc/en/Serial/Available

This will give you the single digits of your 5digit number. The rest is just math.

I have been using those commands, but the problem seems to be that it isn't reading the whole number. It is also converting them into their ascii representation, so if it reads a "1" the arduino sees a 49.

yes, that is true.

you need to build your own loop to read the 5 bytes from serial. the conversion from "human readable number" to ASCII representation is quite simple, have a look at http://www.asciitable.com/. digits from 0 to 9 have ASCII codes from 48 to 57 (decimal), that is by subtracting 48 from the byte value you get, you have what you need.

Another way to think of it is:

'1' - '0' = 1 '2' - '0' = 2 ... '9' - '0' = 9

So if you have an ASCII representation of a digit, you can get the numerical value by subtracting the ASCII representation of zero ('0').

char asciiDigit = '7'; int digit = asciiDigit - '0'; // this is the same as subtracting 48

  • Ben