as my output in the monitor but instead I'm getting:
00
00
00
10
Which suggests to me that I'm exiting the loop every iteration despite my message array being properly filled.
How I'd expect this to run is, the function is called, the local variables are created, the while loop is executed, iterates until the exit condition is reached, exits, calls the print statements, then the function exits.
Sketch below, some functions are copied from another sketch I was working on so they are commented out until I integrate them into this one.
//Variables
bool started = true; //True: Message is strated
bool ended = true; //True: Message is finished
bool msgEnd = false; //True: Message is finished
const byte msgLength = 16;
char msg[msgLength]; //Array to store message
//Function Prototypes
void recieveData(); //func to recieve data from XBee
void sendData(); //func to send data to XBee
void printData(); //func to print data to terminal
void getUserData(); // func to get data from user
void setup() {
//Start the serial communication
Serial.begin(9600); // Serial moniter on computer
//Serial1.begin(9600); //Baud rate must be the same as is on xBee module
//delay(1000);
Serial.println("enter number:");
}
void loop() {
getUserData();
printData();
}
void getUserData() {
static byte index = 0;
char endMarker = '\r';
char incomingByte;
while (Serial.available() > 0 && msgEnd == false) {
incomingByte = Serial.read();
if (incomingByte != endMarker) {
msg[index] = incomingByte;
index++;
if (index >= msgLength) {
index = msgLength - 1;
}
} else {
msg[index] = '\0';
index = 0;
msgEnd = true;
}
Serial.print(msgEnd);
Serial.println(Serial.available());
}
}
void printData() {
if (msgEnd == true) {
Serial.print("number entered: ");
for (int i = 0; i < 5; i++) {
if (msg[i] != '\0') {
Serial.print(msg[i]);
}
}
msgEnd = false;
}
}
// void printData() {
// if (started && ended) {
// for (int i = 0; i < 5; i++) {
// if (msg[i] != '\0') {
// Serial.print(msg[i]);
// }
// }
// Serial.println("");
// started = false;
// ended = false;
// }
// }
// void recieveData() {
// while (Serial1.available() > 0) {
// //Read the incoming byte
// incomingByte = Serial1.read();
// //Start the message when the '<' symbol is received
// if (incomingByte == '<') {
// started = true;
// index = 0;
// msg[index] = '\0'; // Throw away any incomplete packet
// }
// //End the message when the '>' symbol is received
// else if (incomingByte == '>') {
// ended = true;
// break; // Done reading - exit from while loop!
// }
// //Read the message!
// else {
// if (index < 6) // Make sure there is room
// {
// msg[index] = incomingByte; // Add char to array
// //Serial.print(msg[index]);
// index++;
// msg[index] = '\0'; // Add NULL to end
// }
// }
// }
// }