I want to receive simple data from arduino with bluetooth module attached. I am recieving data, everything works fine, but i cant read it well. Here is arduino code:
char incomingByte;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(2);
delay(1000);
}
Here is Android code for reading data from InputStream (BufferedInputStream):
mInStream = socket.getInputStream()
public void run() {
BufferedReader r = new BufferedReader(new InputStreamReader(mmInStream));
while (true) {
try {
int a = r.read();
Log.d(TAG, Integer.toString(a));
} catch (IOException e) {
break;
}
}
}
Here is problem: When Arduino sends number 1, Android should receive it through Buffered Input Reader as decimal value for 1 and it is equal to 49. But i get 2 additional lines in Log, always same values: 10 and 13. How to avoid reading/receiving this? Here is Logcat output for number 1 sent from Arduino:
TAG: 49
TAG: 13
TAG: 10
Whats wrong? Why does Android app receive last two lines?
This is what println()
does according to Arduino's Documentation :
Prints data to the serial port as human-readable ASCII text followed by a carriage return character (ASCII 13, or '\\r') and a newline character (ASCII 10, or '\\n').
Use Serial.print()
instead.
I will focus on two aspects of the above program.
In the above program, two extra tags that are been printed are ASCII Values - 10
for " line feed " and 13
for " carriage return ".
The Serial.println
adds a " carriage return " and " line feed character " to the end of what is being printed. Serial.print
doesn't add anything.
So you can use Serial.print
.
Also, for the part of reading from InputStream
, you can also prefer the following code: link
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder total = new StringBuilder(); String line; while ((line = r.readLine()) != null) { total.append(line).append('\\n'); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.