Serial to Array

Hello! I want to ask, if i want to save the char data from the serial like AFH and i want to save into char hitung[3] how can i do that? I tried doing like this, but it won’t work, it only print A.

while (Serial.available()>0){
    char perintah = Serial.read();
    if(z<4){
     hitung[z]=perintah;
     Serial.print(hitung[z]);
      z++;
    }else{
      z=0;
    }
}

Really appreciate any help, thanks!

I want to ask, if i want to save the char data from the serial like AFH

Only you know if you want to save data. Why ask us?

but it won't work, it only print A.

We can't see what you are sending to the program. We can't see all of your code. We can't see what output the code is generating.

You can't store a 3 character string in a 3 element array, if you want to then pass the array to any string functions.

Serial data arrives ssslllooowwwlllyyy. You MUST account for that.

AFH is send in pieces. So if you run it while only ‘A’ is received yet it will just put A in. But I have no idea when you call it, how you call it, who z is defined etc.

Also remember, to store the string “AFH” you need an array of 4 because you need to null terminate it! At least if you want to use it as a regular string.

Read the updated serial input basics threads for ideas.

Sorry, i meant i send ‘A’ ‘F’ ‘H’ as a separate char and save it to Array. So if hitung[0]=‘A’, it will be printed, if hitung[1]=‘F’ it will turning on the LED, if hitung[2]= H it will open the sd card.

It will be used for switch case statement.

And thanks for the serial example.

Yeah, but still. We don't see when you try to do this? How z is stored etc. Because if serial is available, because it's slow, fat change only 'A' is available once you start reading.

So all the code please. And if it's to long, try to make a shorter version with the same problem. In 90% of the cases you spot the problem while doing so.