However, when I transmit a String from A, B only receive a small portion of it. I really have no idea why? Please assist.
A sends to B
Serial2.write("LAT: 1.234567 LON: 102.987654");
B receives and display
while(Serial1.available()) {
char b = Serial1.read();
Serial.print(b);
}
From the above code, B only able to display "LAT". Can someone advice me why is that so? What happened to the rest of the String? However, if I change "char b" to "byte b", my output is as below:
From the above code, B only able to display "LAT". Can someone advice me why is that so?
I'm pretty sure that the fine folks at http://snippets-r-us.com can help you with your snippets.
Consider, though, that serial data transmission is ssslllooowww, and that the Arduino is fast. By the time the while loop starts, only a little bit of the data has arrived. By the time it ends, nothing more has arrived. If you want to receive the whole string, you have three choices.
Make the string a fixed length, and wait for that number of characters to arrive.
Add a delay between reading characters. That will give time for the next character to arrive. I recommend two weeks.
Send a character that marks the end of the packet. Read and print (and store if there is a good reason for sending the data) the serial data until the end of packet marker arrives.
You can pound your head against the wall for as long as you like, but eventually you'll end up at choice 3 (unless you are zoomkat).
Sorry. I did not explain fully. The reason I said that earlier was because I had some concerns about the implementation of the codes in my current scenario, which is not simply,
Serial2.write("LAT: 1.234567 LON: 102.987654");
Nevertheless, from the way you said it, it seems sending a fix length or end of of packet marker is much better, I'll take a look at it, and update my codes accordingly.
Some arduino to arduino test code that uses a comma , as a data packet delimiter.
//zoomkat 3-5-12 simple delimited ',' string tx/rx
//from serial port input (via serial monitor)
//and print result out serial port
//Connect the sending arduino rx pin to the receiving arduino rx pin.
//Connect the arduino grounds together.
//What is sent to the tx arduino is received on the rx arduino.
//Open serial monitor on both arduinos to test
String readString;
void setup() {
Serial.begin(9600);
Serial.println("serial delimit test 1.0"); // so I can keep track of what is loaded
}
void loop() {
//expect a string like wer,qwe rty,123 456,hyre kjhg,
//or like hello world,who are you?,bye!,
if (Serial.available()) {
char c = Serial.read(); //gets one byte from serial buffer
if (c == ',') {
if (readString.length() >1) {
Serial.print(readString); //prints string to serial port out
Serial.println(','); //prints delimiting ","
//do stuff with the captured readString
readString=""; //clears variable for new input
}
}
else {
readString += c; //makes the string readString
}
}
}