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);
}
-
1majenko.co.uk/blog/reading-serial-arduino majenko.co.uk/blog/arrays-pointers-what-cMajenko– Majenko2019年02月27日 11:32:50 +00:00Commented Feb 27, 2019 at 11:32
1 Answer 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 ?????????????????????????????????????????????????????????????????????????????????????????????????11111M.HARTAOUI– M.HARTAOUI2019年02月27日 13:17:50 +00:00Commented Feb 27, 2019 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– Michel Keijzers2019年02月27日 13:26:32 +00:00Commented Feb 27, 2019 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 lineM.HARTAOUI– M.HARTAOUI2019年02月27日 13:33:04 +00:00Commented Feb 27, 2019 at 13:33
-
1use arduino.cc/reference/en/language/functions/communication/serial/…Michel Keijzers– Michel Keijzers2019年02月27日 13:43:44 +00:00Commented Feb 27, 2019 at 13:43
-
You're welcome, good luck with your projectMichel Keijzers– Michel Keijzers2019年02月27日 15:53:01 +00:00Commented Feb 27, 2019 at 15:53