How to convert byte to int?
arduino, c
Solution
The return value of `Serial.read()` is an `int`. Therefore, if you have the following code snippet:
int input[3];
for (int i = 0; i < 3; i++) {
input[i] = Serial.read();
}
Then `input` should store three `int`s. However, the code:
char* input[3];
for (int i = 0; i < 3; i++) {
input[i] = Serial.read();
}
Will just store the byte conversion from `int` to `char`.
If you want to store this as a string, you need to do a proper conversion. In this case, use `itoa` (see Arduino API description).
The code snippet would be:
#include <stdlib>
char* convertedString = itoa(input[i]);
Problem
I have an Arduino which is reading in a set of three bytes from a program which correspond to degrees in which an actuator must turn. I need to convert these bytes into integers so I can pass those integers on to my actuators. For example, I know the default rest state value I receive from the program is 127. I wrote a C# program to interpret these bytes and that can get them to a single integer value. However, I am unable to figure out how to do this in the Arduino environment with C. I have tried typecasting each byte to a char and storing that in a string. However that returns garbled values that make no sense. ``` void loop() { if(Serial.available() && sw) { for(int j = 0; j < 3; j++) { input[j] = Serial.read(); } //command = ((String)input).toInt(); sw = 0; } String myString = String((char *)input); Serial.println(myString); ``` }