I am trying to receive some numbers that the numbers can be either positive or negative.
I am able to receive the numbers correctly using char but not int.
Since that I want to convert char back to int, but I have no luck with that (only some random numbers and totally differently from the original)...
Any suggestion how to do it? My code is below. Thanks guys.
char recievedChar;
int value;
void setup()
{
Serial.begin(115200);
Serial2.begin(115200);
}
void loop()
{
if (Serial2.available()){
recievedChar = Serial2.read();
value = recievedChar;
Serial.print(value);
}
Char occupies 1 byte. Int requires two bytes. To transmit an int you need at least 2 bytes. More if you convert it to a human-readable string. To receive multibyte strings you need an end-of-string marker, for example \n, or any other char that would be invalid inside the string.
ASCII, I am actually receiving data from another arduino.
On the other arduino, I only use:
Serial.println(data);
data is in int form which can be either positive or negative numbers.
I am not sure if I am sending the format incorrectly or not but what I send from Arduino A to Arduino B, the received values are matched with the transmitted values.
But I am not able to use the value on Arduino B...
AWOL:
Have you thought about using "atoi"?
(Hint: You're not the first person to ask this question, just the first this week)
I tried before, but no luck....
Arduino says:
error: invalid conversion from 'char' to 'const char*'
error: initializing argument 1 of 'int atoi(const char*)'
char recievedChar;
int value;
void setup()
{
Serial.begin(115200);
Serial2.begin(115200);
}
void loop()
{
if (Serial2.available()){
recievedChar = Serial2.read();
value = atoi(recievedChar);
Serial.print(value);
}
}
I tried before, but no luck....
Arduino says:
error: invalid conversion from 'char' to 'const char*'
error: initializing argument 1 of 'int atoi(const char*)'
That's because "atoi" takes a C string as its argument, not a single char.
Seriously, this comes up at least once a week - have a search through the forum.
I think Nick Gammon recently posted a tutorial on the subject.