Communication mismatch from Android to Arduino through RN42 bluetooth module - java

after this problem
Bluetooth connection in Android > 4.1.2
that I fixed by forcing connection by repeatedly try to connect with a while iteration, now I'm having an other issue with Android/Arduino communication.
My HW is Nexus 7 MY2012 with Android 4.3, Arduino UNO R3 and a BT module RN42.
From Android I'm sending an array of bytes to Arduino got from a string.
At the beginning, with Baudrate 115200 and no parity, only the first byte arrives correct and the rest was apparently mismatched (mostly in a repetitive manner).
After setting parity EVEN in the RN42 module, I see that at least first 3 bytes arrive correctly, and the rest is messed up.
Here below the core part of comunication from Android (initialization of BT basically follows the SDK example). It is located inside a class estended from AsyncTask used to manage connection work:
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
mHardwareToServiceHdlr.obtainMessage(MSG_ERR_BT_WRITE).sendToTarget();
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
and Arduino sketch
#include <SoftwareSerial.h>
#include <Streaming.h>
const int bluetoothTx = 2;
const int bluetoothRx = 3;
byte incomingByte;
String incomingString;
SoftwareSerial bluetooth(bluetoothTx,bluetoothRx);
void setup() {
Serial.begin(115200);
bluetooth.begin(115200);
bluetooth.print("$$$");
delay(100);
bluetooth.println("U,115K,E");
bluetooth.begin(115200);
delay(100);
}
void loop(){
if (bluetooth.available() > 0) { // if the data came
incomingByte = bluetooth.read(); // read byte
Serial.println((char)incomingByte);
}
}
If I send to Arduino a string such as "hello horld" this is what I get in serial monitor in a serie of transmissions:
hel,o wo2ld
hel<o wo2ld
hel,o7orld
hel,o wo2ld
hel,o wo2ld
hel<o7or6d
hel,o wo2ld
hel,o wo2ld
hel,o wo2ld
hel<o wo2ld
hel,o7orld
hel<o wo2ld
This is just example, result depends also on how much often I send the string to Arduino.
The most of the times, the fourth and the nineth byte (but not always in the same manner and not always only them) are mismatched.
Transmitting data from Arduino to Android seems to work fine with any particular trouble.
Any help would be greatly apreciated, this thing is making me crazy as far as I need to transmit data longer than 3 bytes.
Thanks

There could be multiple issues with your setup:
Don't use SoftwareSerial's begin() multiple times. If you need to empty the buffer then use bluetooth.flush() after the println() and before the delays.
Taken from the SoftwareSerial docs:
If using multiple software serial ports, only one can receive data at a time.
Try using UART as the serial port instead of a bit-banged serial port.
The Arduino UNO supports interrupts only for pins 2 and 3, and they are frequently used for something else, check that they are really free in your design.
Try using a slower baud rate, there could even be RF issues with your layout at 115200 bps.
If the previous approaches don't work, try storing the characters in a buffer before doing the Serial.print in the main loop. After you are done, finally print it, like this (mind the boundary checks):
char buffer[MAX_LEN];
unsigned int count = 0;
void loop(){
if (bluetooth.available() > 0) { // if the data came
buffer[count++] = bluetooth.read(); // read byte
}
buffer[count] = '\0';
Serial.print(buffer);
count = 0;
}

Kindly ensure pairing the device explicitly from your Android phone’s settings. Usually the pair code is 1234. The Hardware Tx,Rx pin are preferred if free on the Arduino. 96200 baud rate is generally better

Related

Reconnect raspberry pi's bluetooth to an HC-06 in a processing sketch

I have a working setup in which a raspberry pi runs a headless processing sketch upon booting. This sketch connects the Pi's onboard bluetooth to an HC-06. The Pi also sets up a serial connection to an arduino nano through a USB cable. The processing sketch acts as a relay. It relays bytes from the arduino to the Hc-06 and vice versa.
The device with the HC-06 is an arduino nano. This device sends out a handshaking signal so the arduino on the Pi's end knows it's connected and sends a respons.
This all works like a charm but on one condition. The Hc-06 needs to be 'on' before the processing sketch boots. If I turn on the HC-06 too late or if I turn it on/off I cannot reconnect and the processing sketch is to be rebooted.
I want to program a more advanced hand shaking protocol with an time-out feature. So both device will be aware that the connection is severed.
I start the processing sketch via a shell script
sudo rfcomm bind hci0 20:14:04:15:23:75
sudo killall java
xvfb-run processing-java --sketch=/home/pi/Documents/bluetooth --run # runs headless
The rfcomm bind command is only yo be run once upon booting.
And the bluetooth script:
import processing.serial.*;
Serial handController;
Serial central;
byte mode;
void setup()
{
printArray(Serial.list());
size(200,200);
background(0); // black
central = new Serial( this, Serial.list()[3], 115200);
handController = new Serial( this , Serial.list()[0] , 115200 );
}
long prev;
byte tgl = 0;
void draw()
{
if(handController.available() > 0) {
int c = handController.read();
println(" handcontroller:\t" + (char) c + "\t" + c); // as well char as dec value
central.write(c);
}
....
Is it possible that from within this sketch that I terminate the serial connection to rfcomm0 and then restart it?
It seems that this line sets up the bluetooth connection.
handController = new Serial( this , Serial.list()[0] , 115200 ); // rfcomm0
I am not extremely familiar with java. How can I destroy the serial object? And can I do 'new' a 2nd time from out a function?
Kind regards,
Bas
You can use the Serial's stop() method to close the serial connection.
You can then re-initialise the port as required.
Here's a rough(untested example):
void restartSerialPort(Serial reference,String portName, int baudRate){
// pause rendering (draw loop)
noLoop();
// stop previous connection
if(reference != null){
reference.stop();
reference = null;
}
// start connection anew
try{
reference = new Serial( this, portName, baudRate);
}catch(Exception e){
println("error opening serial port: " + portName);
e.printStackTrace();
}
// resume rendering
loop();
}
Bare in mind this needs to be tested/tweaked: I'm not 100% the passed reference will update that easily (otherwise the new Serial object probably needs to be returned by the method and re-assigned to the original reference).
Also not that Processing requires a windowing environment, so it's not quite fully headless.
As a quick alternative to a pure commandline option you can look at Python and the pyserial module

Arduino HC-05 Bluetooth module disconnects when sending data

I'm new to Arduino. I'm trying to build a program to control a breadboard through Arduino using the bluetooth module HC-05. At the moment I don't have anything on the breadboard and I'm just trying to test the connection. This is what I've done so far:
I put the module on the breadboard and I've paired it with the computer. When it's paired, the red led starts blinking slowly. I've connected the bluetooth Rx to Arduino Tx and Arduino Rx to bluetooth Tx following this tutorial: http://playground.arduino.cc/Learning/Tutorial01
I've also implemented both Java and Arduino programs following that tutorial. Here they are:
JAVA
public class Arduino extends PApplet{
public void connect(){
String[] serials = Serial.list();
Serial port = new Serial(this, Serial.list()[0], 9600);
port.write('H');
port.dispose();
}
ARDUINO
void setup() {
Serial.begin(9600);
Serial.println("Start");
}
void loop() {
if(Serial.available()){
int a = Serial.read();
Serial.print(a);
}
}
The Java part should send the letter H to Arduino and Arduino should detect that and print it on the Serial monitor. But what actually happens is that I send data, and the led on the HC-05 starts blinking faster (which means the connection is lost). Why does that happen? I'm pretty confused. For the communication I'm using the port COM6 and COM7. It depends on how it connects. To see what port to use I just run the Java program: if the port is not correct, it will just get stuck and send nothing.
Any help is appreciated. Thanks!
In the end, I've solved this problem by removing this line of code:
port.dispose();
It would never work with it because I was getting rid of the connection. I don't know what I was thinking at the time I did that. That was very silly of me.
Ok so I had this problem.
If you are using the L293D motor shield, you'll be running the arduino of the same power supply, which I think must affect the power output the the bluetooth HC05 module.
Take out the jumper plug on the L293D motor shield, and run the arduino of a separate power source (e.g PP3 battery) and the problem disappears, OK.

How to send midi from a java program to an IAC bus on OSX

I'm trying to write a program that will send MIDI messages to external synthesizers. It does work when using the default synth in Java (1.8 on a mac) and makes a nice ping sound every second when connected to the default synthesizer in Java. As expected this is a boring sound, but it does verify that I'm able to make short midi sequences that are interpreted as sounds by a synth.
I then try to route that signal to an IAC device, so that it can be picked up by other programs (including synthesizers) that can make interesting sounds. However, it seems that none of the events I produce are actually picked up by the IAC device. It doesn't seem like they are sent outside of the JVM, or if they are they are somehow dropped.
My question is simply: Has anyone done this, and can they tell me what they did?
In essence my code does this:
final MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
for (int i = 0; i < infos.length; i++) {
final MidiDevice device = MidiSystem.getMidiDevice(infos[i]);
final String deviceInfo = device.getDeviceInfo().getName();
// My IAC device is called "Bus 1"
if ("Bus 1".equals(deviceInfo)) {
Receiver rcvr = device.getReceiver()
ShortMessage myMsg = new ShortMessage();
// Start playing the note Middle C (60),
// moderately loud (velocity = 93).
myMsg.setMessage(ShortMessage.NOTE_ON, 0, 60, 93);
rcvr.send(myMsg, timeStamp);
}
}
I the test this by connecting the IAC device to an MS-20 soft synth, no sounds are produced. I then connect a "MockMidi" keyboard up to the "Bus 1" IAC device, and I can then play the MS-20 bus. I then try to hook the MockMidi keyboard up to the Bus 1 as an input device, but I don't see any events.
Looks straightforward, but as far as I can tell, no midi messages are ever received at the IAC device when sent from Java, yet the mechanism seems to be working fine both inside java, and outside Java.
I'm stuck, all help will be highly appreciated (and source code will be shared on github when it works (sending to IAC would count as working)). :-)
The documentation for getReceiver() says:
Obtaining a Receiver with this method does not open the device. To be able to use the device, it has to be opened explicitly by calling open().

How to Get image from ComPort

I have some problems in my work..
I have stored TTL serial camera images to MicroSD card successfully using Arduino UNO with the help of Adafruit Tutorial (learn.adafruit.com/ttl-serial-camera/overview) but when i m transferring that images through Zigbee transmitter, At the comport (Zigbee receiver) i m receiving random words. And i think its ASCII.
I want to save images receiving from comport to the folder of my PC.
Is it possible?
I have seen in some forums that use the java or python code, but i can't understand how to use it?
Read image data from COM7 port in Java
I guess this is what you are looking for:
import serial
ser = serial.Serial('/dev/tty.usbserial', 9600)
image = ser.read()
with open('/tmp/image', 'wb') as file:
file.write(image)
Works only in Python 3, in Python 2 you need to use io.open. You may need to install serial-modul first if you don't already have it. I'm not familiar with the Arduino-C-dialect you need to send the image over the com-port...
Arduino IDE's Serial Monitor is using the Serial class to communicate over a serial comm. port.
// Receive & send methods from the SerialMonitor class.
private void send(String s) {
..
serial.write(s);
}
public void message(final String s) {
..
textArea.append(s);
}
My suggestion is to reuse that (Java) code, but since the Serial class is designed for text-only communication you would need to encode the image bytes into e.g. Base64 encoding with this library and decode it on the PC.
If the transfer speed is important, and there is an Arduino binary-based serial communication library, you should use that.
UPDATE
You can read raw bytes from the serial port via the mentioned Serial class like this:
...
Serial port = ...;
byte[] buffer = new byte[1024]; // 1KB buffer
OutputStream imageOutput = new FileOutputStream(...);
// Wait for the image.
while (port.available() > 0) {
int numBytes = port.readBytes(buffer);
if (numBytes > 0) {
imageOutput.write(buffer, numBytes);
}
}
imageOutput.flush();
imageOutput.close();
...

String serial communication

I'm just learning Java for about a couple weeks now. My end goal is to have my Arduino measure some sensors and send the results to my android via USB cable. However I'm just trying to get my Arduino to communicate with the Java console on my computer first, and then I figure it's pretty much copy and paste from there.
I can get my Arduino and Java console to communicate with each other as long as it's a simple byte. Anything passed that is giving me a result of the quadratic equation exploding.
In my Arduino serial Monitor I get this:
Engine Temp:100
Air Temp:95
Engine Speed:10000 RPM
Wheel Speed:30 MPH
and in my Java console I get this:
Normal println
[B#6f5f6479
String
€˜3Àf`Ì󀘀
UTF
??3?f`??
Here is my reader code:
#Override
public void serialEvent(SerialPortEvent arg0) {
byte[] readBuffer = new byte[1000];
try {
int availableBytes = input.available();
if (availableBytes > 0) {
// Read the serial port
input.read(readBuffer, 0, availableBytes);
// Print it out
System.out.println("Normal println");
System.out.println(readBuffer);
System.out.println("\nString");
System.out.println(new String(readBuffer, 0, availableBytes));
System.out.println("\nUTF");
System.out.println(new String(readBuffer,"UTF-8"));
System.out.println("\nDone");
}}
catch (IOException e) {
}
}
input is my InputStream.
Ensure that the Arduino and the serial port on the android are at the same speed. The provided code does NOT show how the serial ports are defined and opened/started so its impossible to know if this is the problem.
The characters displayed at the android appear like the typical garbage seen when the two end-points of a serial line are not similarly configured.
It looks like the Arduino is correctly sensing the engine's dynamics?

Categories

Resources