Max Abrahamsson
Max Abrahamsson

Reputation: 1498

How to send integers to arduino via serial?

I want to send integers to Arduino via a serial connection. For example, when I send "1" the data received by Arduino is "49" and when I send "a" the data received by Arduino is "97"

There are two functions in Python, ord() and unichr(). They behaved like this:

unichr(97) = u"a"
ord(u"a")=97

Are there equivalent C functions?

Upvotes: 1

Views: 2576

Answers (2)

SvenS
SvenS

Reputation: 795

As long as you have your characters stored as their ASCII-value, the easiest way - if your goal is converting single digits - is to subtract the ASCII-value of 0: '8'-'0' will give you the unsigned char value 8. You need to make sure it's a digit and not some character, but that is easily done by just checking if the result is below or equal 9.

Similarly, you get the ASCII-value of a single digit z by adding the value of '0'.

Upvotes: 2

Anycorn
Anycorn

Reputation: 51565

Use the alphanumeric to integer function.

You may also find header cstdlib, stdlib.h, C Standard General Utilities Library useful. Although it says C++, this particular section is the standard C library. Notice that you can use C++ with Arduino.

Upvotes: 2

Related Questions