I'm trying to go through a string I get from serialcom. and look for letters/digits etc. in the text, one step at the time. Since this code above don't work, what is working?
Probably out to add a check that availableBytes is less than 32, and you might need to append a NULL onto the end of the array. Depends on what you are trying to do with the "string".
Okey.
So do I have to fill up string[32] with 32 characters?
Why do I need to set the size? Is there no sort of dynamic array in Arduino?
I'm sending something like this from matlab: "M:1;S:100;D1" where M is for motor, S is for speed and D is for direction. I'm trying to control a robotic arm with 4 motors on.
So you see that the number of characters in the text will depend on for example the speed. If the speed is only 50 there is only two character instead of three as in 100.
How do I append a NULL to the end of the array?
int byteAvailable = Serial.available();
for(int i = 0; i < byteAvailable; i++)//-1=stringsluttsignal
{
string[i] = Serial.read();
if(string[i] == 'M')
{
motor_number[0] = Serial.read();
delay(10);
}
and so on...
I thougth sizeof() was a brilliant function to use. I haven't tried this with sending text from matlab yet, but it compiled and uploaded to the board without any errors so thanks a lot so far
You don't have to fill the array with 32 characters, but you can't put more than 32 characters (including the terminating NULL) into it.
I just picked 32 as an example. You need to determine the maximum that could be present when you go to read.
Of course, you need not put the characters in an array, at all. You could read and process each byte as it arrives.
If matlab is sending "M:1;S:100;D1", you read the next character, and see that it is an M, so you know that that letter is to be followed by a colon and some numbers and a semicolon. So, you read and discard a character (the colon). Then, you read a value, convert it to an int (by subtracting '0'), multiply the previously set value by 10, and add the new value. Repeat until the byte read is a ';'.
Dynamic arrays require a lot of overhead. The space needs to be allocated, and freed up when you are done with it. The code space on a micro-controller is limited, so there must be compromises made. Dynamic arrays consume too much space for the benefit they provide, so they didn't make the cut.
You append a NULL each time you store a character: