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.
Related
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
I'm currently developping my first app in java.
This app requires a direct connection with my BL652, which doesn' t accept any kind of pairing option. That being said, I'm stuck with the code below, which still tries to pair with my bluetooth device instead of just connecting. Therefore, I wanted to know what am i supposed to do in order to make a connection that doesnt require pairing.
Thanks in advance for any response.
String mac_address = "DA:72:21:29:0F:F0";
private static final UUID MY_UUID = UUID.fromString("E54B0002-67F5-479E-8711-B3B99198CE6C");
lvNewDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
BluetoothDevice device = (BluetoothDevice) mBluetoothAdapter.getRemoteDevice(mac_address);
try {
socket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
} catch (IOException e) {
e.printStackTrace();
}
I'm not sure about connection to external hardware but it's definetly possible to connect 2 phones without pairing. I made it using Android Nearby Connections . And yeah it's basically working with BLE. As far as I know it's possible to connect to RaspberryPi using that API.
Bluetooth devices can be made to communicate with each other using master-slave configuration. I first tried with two BLE-HC05s, made one as master and the other as slave, and as expected the master is able to send data, slave is able to receive data, that can be seen using the Serial Monitor in Arduino IDE. I have developed a similar app, which connects to a BLE-HC05 device, sends and receives data. But since you are trying to get data or send data to the App on your phone, Android will not support such unpaired anonymous communications. If you are having trouble with connection or pairing Bluetooth device and your app, I may help you with that. But as far as Bluetooth communication without pairing is concerned, you may not be able to find a way.
Edit: The code to connect any bluetooth device, like BLE-HC06 as you have mentioned, is 1234 (Only if you have not changed it)
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!
I am new to bluetooth programming, so please keep that in mind.
I am trying to connect to a pulse sensor from a desktop pc, specifically the Zephyr HxM BT. I am not using any device specific drivers, the Java bluetooth library I'm using is Bluecove, and my bluetooth stack is BlueSoleil.
From my understanding, the way I proceed is
1) Scan for BT devices
public void startSearch() throws BluetoothStateException{
System.out.println("Inquiry started");
localdevice.getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, this);
}
This works fine, it discovers my pulse belt and calls
public void deviceDiscovered(RemoteDevice arg0, DeviceClass arg1)
2) Search a device for services
Once a device has been discovered, it should be added to the DiscoveryAgent's list of cached devices, this is my first problem as the cache (and preknown devices) is always empty even though I've discovered my belt.
So the way that I do this now is to either keep my own list of devices, or simply start a service search directly from deviceDiscovered.
I am still a bit unsure if I'm using the correct parameters, but from reading the BT device manual and the javax.bluetooth documentation on DiscoveryAgent.searchServices:
public int searchServices(int[] attrSet,
UUID[] uuidSet,
RemoteDevice btDev,
DiscoveryListener discListener)
throws BluetoothStateException
My code:
public void searchServices(RemoteDevice device){
UUID[] uuidSet = new UUID[1];
uuidSet[0]=new UUID("1101",false); //Serial Port
System.out.println("Searching for services on " + device.getBluetoothAddress() );
try{
agent.searchServices(null,uuidSet, device,this);}
catch (BluetoothStateException e){
System.out.println("BluetoothStateException caught.");
}
}
I've set the attributes parameter to null, because the documentation states that this will have it search for services with the default attributes, however I've also tried to use only ServiceID (0x0003) as attribute with no luck.
This is where I'm stuck, I pass the correct BT device into the function, and it starts searching but never give me any results, it just searches forever for all I know, no exception, no calls to
public void servicesDiscovered(int arg0, ServiceRecord[] arg1)
or
public void serviceSearchCompleted(int arg0, int arg1)
So I guess my questions are:
- Am I doing something wrong? Any suggestions?
- What are the other approaches to connecting to a BT device, and what
information do I have to know about the device to do that?
Here is some information that I think is relevant from the device manual:
The following steps have to be undertaken to connect to a HxM device.
1) Activate the Bluetooth service of the device/computer wanting to connect to the HxM
2) Scan for Bluetooth devices in range
3) Pair with the HxM device found in range
4) Discover Services of Paired HxM
5) Connect to serial port of HxM device
The diagram above shows that the Bluetooth HxM typically communicates with a mobile device over the Bluetooth
link. The HxM only supports one link at a time and uses the Bluetooth SPP (Serial Port Profile) to communicate
with other devices with the following low-level protocol:
• 115,200 baud
• 8 data bits
• 1 stop bit
• No parity
Any suggestions are very much appreciated
edit: I just want to add that I'm testing the code with a console input loop, so the program is not immediately terminated after calling searchServices, it should have time to complete unless I'm misunderstanding async tasks
I just wanted to update this and say that I found the problem, it seems that I had to use a short UUID instead of a long. I should have tried both of these options before I deemed myself stuck, but I didn't think it would make any difference.
I would like to call some functions in my Android-app from the PC.
On the PC I would like to write a short java or C program.
Simplified, I think on something like this call on the PC:
myApp.Appfunction ();
and then the
Appfunction(){
}
in my app on the android-phone just simply called.
Is it possible?
Is there any way to achieve this
The interface is still open.
I have a Samsung Galaxy S3 so there are a lot possible interfaces:
NFC, Bluetooth, USB, WiFi Direct
I prefer an USB connection but if something else is easier to implement, I also work with other interfaces.
Thanks in advance for the answer
You need to build a server on your PC and wait for a socket connection you'll do througt android.
So, your api becomes:
public void pcFunction(){
//estabilish a socket connect
//send a message "cmd function" to server
}
on the server
//receives message and parse it
switch(cmd){
case fun1:
callFunction1();
break;
case fun2:
//
}