I am receiving ascii string from ARDUimu over serial into an array, and then using atoi function to convert this into an integer.
I edited the output format to !ANG:-11.35,-8.51,14.78 (message preamble,roll, pitch,yaw). I edited the following code from a former post in the forum .The code seems to work fine if the string data is just set up as a "string" in an initialized array but fails if i read stuff into a char array.
void setup() {
// initialize both serial ports:
Serial.begin(38400);
Serial1.begin(38400);
}
void loop() {
char arr[30];
// read from port 1, send to port 0:
if (Serial1.available()) {
char arr[30] ={ Serial1.read()};
Serial.write(arr);
}
char str[30];
float roll, pitch, yaw;
int errors = 0;
strcpy(str, arr);
// First is throwaway unless you want to do strcmp with "!ANG" or some such thing
char *chpt = strtok(str, ":");
if (chpt == NULL) {
Serial.println("First strok returns NULL");
++errors;
}
if (errors == 0) {
chpt = strtok(NULL, ",");
if (chpt == NULL) {
Serial.println("Second strok returns NULL");
++errors;
}
else {
roll = atof(chpt);
}
}
if (errors == 0) {
chpt = strtok(NULL, ",");
if (chpt == NULL) {
Serial.println("Third strok returns NULL");
++errors;
}
else {
pitch = atof(chpt);
}
}
if (errors == 0) {
chpt = strtok(NULL, ",\r\n");
if (chpt == NULL) {
Serial.println("Fourth strok returns NULL");
++errors;
// This is an input error: do something to handle it.
}
yaw = atof(chpt);
}
if (errors == 0) {
Serial.print("(");
Serial.print(roll);
Serial.print(", ");
Serial.print(pitch);
Serial.print(", ");
Serial.print(yaw);
Serial.println(")");
}
}
Output:
!First strok returns NULL
AFirst strok returns NULL
NFirst strok returns NULL
GFirst strok returns NULL
:First strok returns NULL
1First strok returns NULL
.First strok returns NULL
0First strok returns NULL
8First strok returns NULL
,First strok returns NULL
-First strok returns NULL
0First strok returns NULL
.First strok returns NULL
1First strok returns NULL
3First strok returns NULL
,First strok returns NULL
3First strok returns NULL
5First strok returns NULL
.First strok returns NULL
8First strok returns NULL
4First strok returns NULL
As you can see the serial data received is printed vertically as the first letter of each output line.
However when i run the first serial.read and serial.write commands alone putting everything else as comment. the output is as follows
!ANG:1.01,0.09,34.84
!ANG:1.02,0.17,34.84
!ANG:1.37,0.25,34.85
!ANG:1.08,0.47,34.85
!ANG:1.49,0.36,34.85
!ANG:1.13,0.08,34.85
!ANG:1.38,0.14,34.85
!ANG:1.00,0.17,34.84
!ANG:1.34,0.20,34.83
!ANG:1.35,0.15,34.86
!ANG:1.27,0.30,34.85
!ANG:1.30,0.46,34.85
!ANG:1.43,0.04,34.87
!ANG:1.13,0.30,34.87
Help me please i cant understand why the code doesn't work. However the code works if the value of the string arr[30] is given as
char arr[30] = {
"!ANG:-11.35,-8.51,14.78"
};
and not received in serial. =(
Is there another easy way to get the variables from the string received