Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Arduino Android Bluetooth communication example
const int sensor_pin = A0;
const int led_pin = 13;
int sensor_value = 0;
int in_value = 0;
const int wait = 10;
void setup() {
Serial.begin(115200);
pinMode(led_pin, OUTPUT);
}
void loop() {
sensor_value = analogRead(sensor_pin); // read sensor value
Serial.print(sensor_value); // send value over serial (BT)
Serial.print("#"); // send termination character
Serial.flush(); // wait for data to be sent
if(Serial.available() > 0) { // check for incoming data
in_value = Serial.read(); // read incoming data
if(in_value == '0') digitalWrite(led_pin, LOW); // turn off led
if(in_value == '1') digitalWrite(led_pin, HIGH); // turn on led
}
delay(wait); // wait to avoid saturating serial with writes
}
/**
* <p>Ketai Library for Android: http://KetaiProject.org</p>
*
* <p>KetaiBluetooth wraps the Android Bluetooth RFCOMM Features:
* <ul>
* <li>Enables Bluetooth for sketch through android</li>
* <li>Provides list of available Devices</li>
* <li>Enables Discovery</li>
* <li>Allows writing data to device</li>
* </ul>
* <p>Updated: 2012-05-18 Daniel Sauter/j.duran</p>
*/
//required for BT enabling on startup
import android.content.Intent;
import android.os.Bundle;
import controlP5.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import ketai.net.bluetooth.*;
import ketai.ui.*;
import ketai.net.*;
import oscP5.*;
boolean isLEDon;
KetaiBluetooth bt;
String info = "";
KetaiList klist;
PVector remoteMouse = new PVector();
ArrayList<String> devicesDiscovered = new ArrayList();
boolean isConfiguring = true;
String UIText;
int value;
String value_buffer;
int led_mode;
ControlP5 cp5;
Chart chart;
RadioButton led_buttons;
//********************************************************************
// The following code is required to enable bluetooth at startup.
//********************************************************************
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bt = new KetaiBluetooth(this);
}
void onActivityResult(int requestCode, int resultCode, Intent data) {
bt.onActivityResult(requestCode, resultCode, data);
}
//********************************************************************
void setup()
{
orientation(PORTRAIT);
background(78, 93, 75);
stroke(255);
textSize(24);
//start listening for BT connections
bt.start();
UIText = "d - discover devices\n" +
"b - make this device discoverable\n" +
"c - connect to device\n from discovered list.\n" +
"p - list paired devices\n" +
"i - Bluetooth info";
value = 0; // current value of sensor
value_buffer = ""; // store chunks of data as they come over BT
led_mode = 0;
cp5 = new ControlP5(this);
// Chart to display sensor value
chart = cp5.addChart("dataflow")
.setPosition(width * 0.3, height * 0.1)
.setSize(int(width * 0.6), int(height * 0.8))
.setRange(0, 1023) // accurate repr of the sensor value
.setView(Chart.AREA)
.setStrokeWeight(1.5)
.setColorCaptionLabel(color(40));
chart.addDataSet("incoming");
chart.setData("incoming", new float[4096]);
// Radio buttons to control the LED
led_buttons = cp5.addRadioButton("led_modes")
.setPosition(width * 0.1 , height * 0.3)
.setSize(int(width * 0.1), int(width * 0.1))
.setColorForeground(color(120))
.setColorActive(color(255))
.setColorLabel(color(255))
.setItemsPerRow(1)
.setSpacingColumn(50)
.addItem("off", 0) // led off mode
.addItem("on", 1) // led off mode
.addItem("warn", 2) // led warning mode
.setNoneSelectedAllowed(false)
.activate(0);
}
void draw()
{
if (isConfiguring)
{
chart.hide();
led_buttons.hide();
ArrayList<String> names;
background(78, 93, 75);
//based on last key pressed lets display
// appropriately
if (key == 'i')
info = getBluetoothInformation();
else
{
if (key == 'p')
{
info = "Paired Devices:\n";
names = bt.getPairedDeviceNames();
}
else
{
info = "Discovered Devices:\n";
names = bt.getDiscoveredDeviceNames();
}
for (int i=0; i < names.size(); i++)
{
info += "["+i+"] "+names.get(i).toString() + "\n";
}
}
text(UIText + "\n\n" + info, 5, 90);
}
else
{
background(78, 93, 75);
pushStyle();
fill(255);
popStyle();
chart.show();
led_buttons.show();
}
drawUI();
}
void led_warning() {
if (led_mode != 2) return; // not warning mode
byte[] msg = new byte[2];
if (value > 512) { // trigger warning LED if value above 512
msg[0] = '1';
} else {
msg[0] = '0'; // otherwise turn off warning LED
}
msg[1] = '\n';
bt.broadcast(msg);
}
void led_modes(int mode) {
led_mode = mode;
if (led_mode == 2) return; // warning mode handled on sensor read, not here
byte[] msg = new byte[2];
if (led_mode == 0) { // turn LED off
msg[0] = '0';
} else {
msg[0] = '1'; // turn LED on
}
msg[1] = '\n';
bt.broadcast(msg);
}
//Call back method to manage data received
void onBluetoothDataEvent(String who, byte[] data)
{
if (isConfiguring)
return;
for(int i=0; i<data.length; i++) { // process each byte
char c = (char) data[i];
if ('#' == c) { // got termination char
value = Integer.parseInt(value_buffer); // read buffered value
chart.push("incoming", value); // add value to chart
value_buffer = ""; // clear buffer
led_warning(); // check for LED warning
} else {
value_buffer += c; // add data chunk to raw value
}
}
}
String getBluetoothInformation()
{
String btInfo = "Server Running: ";
btInfo += bt.isStarted() + "\n";
btInfo += "Discovering: " + bt.isDiscovering() + "\n";
btInfo += "Device Discoverable: "+bt.isDiscoverable() + "\n";
btInfo += "\nConnected Devices: \n";
ArrayList<String> devices = bt.getConnectedDeviceNames();
for (String device: devices)
{
btInfo+= device+"\n";
}
return btInfo;
}
/* UI-related functions */
void mousePressed()
{
if (mouseY <= 50 && mouseX > 0 && mouseX < width/3)
KetaiKeyboard.toggle(this);
else if (mouseY <= 50 && mouseX > width/3 && mouseX < 2*(width/3)) //config button
{
isConfiguring=true;
}
else if (mouseY <= 50 && mouseX > 2*(width/3) && mouseX < width) // draw button
{
if (isConfiguring)
{
//if we're entering draw mode then clear canvas
background(78, 93, 75);
isConfiguring=false;
}
}
}
public void keyPressed() {
if (key =='c')
{
//If we have not discovered any devices, try prior paired devices
if (bt.getDiscoveredDeviceNames().size() > 0)
klist = new KetaiList(this, bt.getDiscoveredDeviceNames());
else if (bt.getPairedDeviceNames().size() > 0)
klist = new KetaiList(this, bt.getPairedDeviceNames());
}
else if (key == 'd')
{
bt.discoverDevices();
}
else if (key == 'x')
bt.stop();
else if (key == 'b')
{
bt.makeDiscoverable();
}
else if (key == 's')
{
bt.start();
}
}
void drawUI()
{
//Draw top shelf UI buttons
pushStyle();
fill(0);
stroke(255);
rect(0, 0, width/3, 50);
if (isConfiguring)
{
noStroke();
fill(78, 93, 75);
}
else
fill(0);
rect(width/3, 0, width/3, 50);
if (!isConfiguring)
{
noStroke();
fill(78, 93, 75);
}
else
{
fill(0);
stroke(255);
}
rect((width/3)*2, 0, width/3, 50);
fill(255);
text("Keyboard", 5, 30);
text("Bluetooth", width/3+5, 30);
text("Interact", width/3*2+5, 30);
popStyle();
}
void onKetaiListSelection(KetaiList klist)
{
String selection = klist.getSelection();
bt.connectToDeviceByName(selection);
//dispose of list for now
klist = null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment