Serial Commands


I want to create a function where by I send values to specific parts of my code using the serial interface by preceding the number with a letter -

i.e. if i want to be able to alter the speed of two motors A & B, my idea is that i could send A50 to control mtr A (for example) and B10 to control mtr B.

in the code i want to use string.startsWith("A"), then use string.remove(0) to get the speed value.

however im running into all sorts of problems with the format of the data.

I have tried using char instead of string but then i cant use the string functions to remove the letter from the number ie A200.

thanks in advance.

remove might the thing you are looking for.

There are many ways to do what you want without using the String class. If your char array is as you described then array[0] will be either A or B so you can use this value to choose the motor. After that, get a copy of the AVR C library manual and keep it handy. I’ve attached a copy for your convenience.

Look up the atoi() function which will return the first integer it finds in a char array. The first integer is defined as those contiguous numeric entries until a non-numeric is found so 100s or 100\0 would both return 100. Okay you might think that A50 would get hung up on the A, and it would, but the atoi function wants a pointer as a parameter and you already know that the first entry is the A or B, so point to the second entry.

Example,char array[] = "A100"creates an array with members
array[0] = A
array[1] = 1
array[2] = 0
array[3] = 0
array[4] = \0 (the null terminator)

Similarly,char array[] = "B50C"creates an array with members
array[0] = B
array[1] = 5
array[2] = 0
array[3] = C
array[4] = \0 (the null terminator)

In both cases, array[0] contains the motor identifier and the integer value begins with array[1]. Now by default the identifier of a c-string (character array) is a pointer to the first element, so in these instances array points to array[0]. By extension, array + 1 points to array[1]. You can therefor use the atoi() function to return the first integer found beginning with the contiguous entries found from array + 1.

In the first case,
int var = atoi(array + 1) will return 100 and in the second case, 50.

Most (all) of the String class functions can be performed using c-string functions/macros. Maybe not as syntactically simple, but without the risks.

avr-libc-user-manual-2.0.0.pdf (1.6 MB)

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data. Especially look at the parse example that illustrates the sort of thing I think you want.