2

I'm a new here and this is my first question. I would like to read from serial monitor and stock the information in a array of bytes. then I want to print this array in serial monitor. This is the code that I tried:

byte A[6];

void setup()
{
}

void loop() {
  A[6] = Serial.read();
  Serial.write (A);
}
1

If you want to print it only, I would suggest not to store it. But if you want to do some calculations, you might store it.

The problem you make is you always store the value in the 6th element of the array A, however A only has elements A[0] to A[5], so A[6] is beyond the storage space, and results in crashes (sometimes) or at least unexpected behavior.

To fix it you have to store the value in the correct element of A, and for that you need an index variable. Since you can only store 6 values, after the 6th, start with the 0 and process it.

Like:

byte arr[6];
index arrIndex;

void setup()
{
   arrIndex = 0;
}

void loop() {
  // Read serial.
  arr[arrIndex] = Serial.read();

  // Increase counter
  arrIndex++;

  // If the maximum is read, print values and reset it.
  if (arrIndex == 6) {
     // Print the elements.
     for (index = 0; index < 6; index++)
     {
        Serial.write(A[index]);
     }

     // Restart counter.
     arrIndex = 0;
  }
}

An improvement: instead of 6 everywhere, use a define:

#define MAX_ELEMENTS 6
  • Hey Michel, Thank you for your response-- I tried your code but some question marque keep showing up . if i print for example 11111. the Serial monitor show ?????????????????????????????????????????????????????????????????????????????????????????????????11111 – M.HARTAOUI Feb 27 at 13:17
  • I assume the read data are characters, if you try to print out non ascii values you might get the ? values... Try converting it to a string (with itoa(...) for example. Or maybe using an int array helps (not sure, cannot test it here). – Michel Keijzers Feb 27 at 13:26
  • I didn't explain it well, actually the question mark keep showing even if I print nothing. when I print something, the Serial monitor show it then go back to the next line – M.HARTAOUI Feb 27 at 13:33
  • 1
  • You're welcome, good luck with your project – Michel Keijzers Feb 27 at 15:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.