String serial communication - java

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?

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

Trouble Writing to Serial Port with Java RXTX Library

I'm trying to send some bytes from java code to a bluetooth module that is connected to an Arduino. Here is my code.
import gnu.io.*;
import java.io.IOException;
import java.io.OutputStream;
public class ArduinoSerialWriter {
private static OutputStream arduinoOutputStream;
public static void init() throws NoSuchPortException, PortInUseException,
UnsupportedCommOperationException, IOException {
SerialPort arduino = (SerialPort) CommPortIdentifier.getPortIdentifier("COM6")
.open(ArduinoSerialWriter.class.getName(), 2000);
arduino.setSerialPortParams(9600,
SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
arduinoOutputStream = arduino.getOutputStream();
}
public static void writeToArduino(byte[] bytes) throws IOException {
arduinoOutputStream.write(bytes);
}
public static void main(String[] args) {
try {
ArduinoSerialWriter.init();
} catch (Exception e) {
e.printStackTrace();
}
try {
arduinoOutputStream.write(new byte[]{(byte) -1, (byte) 90, (byte) 40});
} catch (IOException e) {
e.printStackTrace();
}
}
}
The init() seems to be working properly and connecting to the bluetooth module. The problem is that the call to arduinoOutputStream.write() is blocking indefinitely. I can also tell that the bytes have not been sent because the Arduino is not doing anything. However, no exceptions were thrown.
I read somewhere that it might be because the Arduino is resetting and needs time before it is ready to receive data, so I tried adding Thread.sleep(10000); before writing to the port, but that didn't change anything.
I also used a debugger to figure out where exactly the code was blocking and I traced it to these lines from the write(byte[]) method from RXTXPort.class in the RXTX library:
RXTXPort.this.waitForTheNativeCodeSilly();
RXTXPort.this.writeArray(var1, 0, var1.length, RXTXPort.this.monThreadisInterrupted);
From what I can gather, waitForTheNativeCodeSilly(); is called right before the bytes are actually sent in the next line, and this is where the code freezes.
I also tried adding arduinoOutputStream.flush(); after the call to the write method, but that didn't help either because the code froze before that line was even reached.
Any help would be appreciated.
Update:
I tried using removing the bluetooth module and using the USB cable for the Arduino instead and it worked perfectly. I think there might be something I need to setup with the bluetooth module.
It is an HC-06 bluetooth module. Here's where I got it from:
https://www.amazon.ca/JMT-Wireless-Bluetooth-Serial-Arduino/dp/B00HXAE0PQ/
The only thing I'm doing to set it up is going to manage bluetooth devices on my windows 10 pc and clicking pair. It says paired underneath it, so I'm not sure what the problem is.
Update Again:
I tried sending data to the bluetooth module using the serial monitor in the Arduino IDE, and the entire IDE completely froze. The only way I could shut it down was by killing the process in task manager. I'm fairly certain the Arduino IDE is having the same problem that I am, so its definitely something to do with the bluetooth chip and not my code itself.
Turns out I had the completely wrong idea. I was much better off using bluetooth connection as opposed to trying to treat the bluetooth chip as a COM port. I guess I was just fixated on that because I was used to it from Arduino.
I used the bluecove library for java and its working great now!

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 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();
...

Communication mismatch from Android to Arduino through RN42 bluetooth module

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

Categories

Resources