Hi all,
I need to confirm if this program faithful for storing a chunk of char data in an array, namely "incomingByte"array as in program.
Please give your insights for improving the code if there is something wrong.
char incomingByte[10]; // for incoming serial data
int i;
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte[i] = Serial.read();
// say what you got:
Serial.print(incomingByte);
}
}
Thank you spycatcher2k, can you suggest what changes are required for faithfull output?
Thank You
First, take your code while it's in the IDE and press Ctrl-T before you post it. It will reformat it in a C style that is commonly used here.
char incomingByte[10]; // for incoming serial data
int i;
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte[i] = Serial.read(); // Point #1
// say what you got:
Serial.print(incomingByte); // Point #2
}
}
You've define an array of chars named incomingByte[] that is made up of 10 char-sized buckets. At Point #1 above, you read one byte of data via the call to Serial.read() and, because i is 0, you stuff it into bucket 0 of the array. At Point #2, you print what you received. However, because you used the name of the array without its brackets, it prints the entire content of the array. You just got lucky that global data fills that array with 0's when you defined it, since a 0 (actually, null, '\0') defines the end of a string array in C.
If you want to save each character as it comes in, you will need to increment i so you march through the buckets as the data comes in. Also, you will need to check to see if the user pressed the Enter key to terminate the input from the monitor. The easiest way to do this is with something like:
void loop() {
int charsRead;
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming bytes until Enter pressed or 9 chars read
charsRead = Serial.readBytesUntil('\n', incomingByte, sizeof(incomingByte) - 1);
incomingByte[charsRead] = '\0'; // Now it's a string
Serial.print(incomingByte);
}
}
I could explain how this works, but you'll learn more if you do it yourself.
Awesomely explained econjack.
A very big thank you.