Wednesday 29 April 2015

Bluetooth communication between Arduino and Android

      Communication between Arduino and Android might seem scary and troublesome at first when you start to get errors in communicating and you don’t find where exactly the problem lies. Believe me it’s lot simpler than it looks. The only thing required is a proper guidance. While doing it on my own I have had many problems and would want others not to face the similar problems. 

      So here in this post I will be controlling a LED light that is connected to the Arduino board from an Android device via Bluetooth.

The hardware requirements are:

      1)      Arduino Uno  
      2)      Bluetooth Module (Example: HC-05) 
      3)      An Android Device (Example: Samsung Galaxy)  
      4)      A LED Light

Once these devices are available the connections that need to be made are as shown in the following fig:


Connect the anode pin of LED light to the Pin12 and cathode pin to the GND Pin of Arduino.

                                                  
The JY-MCU module (Bluetooth module) communicates with the Arduino via a serial connection. The 4 pins that we will be using are:
  • VCC => used to power the module. It needs to be connected to the Arduino 5V pin
  • GND => the ground pin. It needs to be connected to the Arduino GND pin
  • TXD => used to send data from the Bluetooth module to the Arduino. It needs to be connected to the  receive pin (RXD) of the Arduino, which in our case is pin 6 on the UNO.
  • RXD => used to receive data from the Arduino. It needs to be connected to the the Arduino transmit pin (TXD), which in our case is pin 7 of Arduino Uno.
  • We will not be using the “STATE” and the “KEY” pins of the Bluetooth module, so they need not be connected.

Once these connections are done, we have to code the Arduino UNO to accept Bluetooth serial data and make 
the LED ON or OFF depending on the input byte.

To start with, first download the Arduino IDE by visiting the following link:

Then connect the Arduino UNO board to your computer via the USB cable and open the Arduino IDE by clicking on the .exe file that you’ve just downloaded. Then copy the following code to your IDE and save it. Then click the upload button to build, compile and upload the code to your android UNO board. Once the compilation is successful your Arduino board is ready to receive the data.
The arduino code is fairly simple.
  • It establishes a serial connection between the Arduino and the Bluetooth module
  • RXD(Pin 6) and TXD(Pin 7) Arduino pins communicate with the TXD and RXD pins of the module
  • Listen for input on the serial port 12 and process it
  • Turn the LED on pin 12 ON, if it reads 1 (one) as serial input
  • Turn the LED on pin 12 OFF, if it reads 0 (zero) as serial input

Arduino code

#include <SoftwareSerial.h>     //Software Serial Port
#define RxD 6        // This is the pin that the Bluetooth (BT_TX) will transmit to the Arduino (RxD)
#define TxD 7        // This is the pin that the Bluetooth (BT_RX) will receive from the Arduino (TxD)

SoftwareSerial blueToothSerial(RxD,TxD);
char incomingByte;  // incoming data
int  LED = 12;      // LED pin

void setup() {
 Serial.begin(9600);          // Allow Serial communication via USB cable to computer (if required)
pinMode(RxD, INPUT);    // Setup the Arduino to receive INPUT from the bluetooth shield on Digital               Pin 6
pinMode(TxD, OUTPUT);  // Setup the Arduino to send data (OUTPUT) to the bluetooth shield on Digital Pin 7
pinMode(LED, OUTPUT);
setupBlueToothConnection();
}

void loop()
{  
   if(blueToothSerial.available())     // If the bluetooth is connected and sent any characters
  {
        incomingByte = (char)blueToothSerial.read();            // read byte
        if( incomingByte == '0' )
        {
               digitalWrite(LED, LOW);                                          // if 0, switch LED Off
       }
      if( incomingByte == '1' )
      {
          digitalWrite(LED, HIGH);                                  // if 1, switch LED ON
      }
  }
}

void setupBlueToothConnection()
{
   //Setup Bluetooth serial connection to android
  blueToothSerial.begin(115200);
  blueToothSerial.print("$$$");
  delay(100);
  blueToothSerial.println("U,9600,N");
  blueToothSerial.begin(9600);
 }

Next create a new Android project in Eclipse and copy the following code into your MainActivity.java file:

MainActivity.java

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class ConnectArduino extends Activity{           
    BluetoothAdapter mBluetoothAdapter;
    BluetoothSocket mmSocket;
    BluetoothDevice mmDevice;
    OutputStream mmOutputStream;
    InputStream mmInputStream;
   
    TextView status;
    Button connect;
    Button disconnect;
    Button turn_LED_ON;
    Button turn_LED_OFF;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                        // TODO Auto-generated method stub
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                        connect = (Button)findViewById(R.id.connect);
                        disconnect = (Button)findViewById(R.id.disconnect);
                        turn_LED_ON = (Button)findViewById(R.id.on);
                        turn_LED_OFF = (Button)findViewById(R.id.off);
                        status = (TextView)findViewById(R.id.status);
                        status.setText(“Bluetooth Disconnected”);
                        disconnect.setEnabled(false);
                        turn_LED_ON.setEnabled(false);
                        turn_LED_OFF.setEnabled(false);                   

connect.setOnClickListener(new View.OnClickListener()
                     {
                         public void onClick(View v)
                         {     
                        try
                                    {
                                    findBT();
                                    }
                           catch (IOException ex) { }
}
                     }); 
                        disconnect.setOnClickListener(new View.OnClickListener()
                     {
                         public void onClick(View v)
                         {     
                        try
                                    {
                                    closeBT();
                                    }
                           catch (IOException ex) { }
}
                     }); 
                        Turn_LED_ON.setOnClickListener(new View.OnClickListener()
                     {
                         public void onClick(View v)
                         {     
                        try
                                    {
                                    sendData(“1”);
                                    }
                           catch (IOException ex) { }
}
                     }); 
                        Turn_LED_OFF.setOnClickListener(new View.OnClickListener()
                     {
                         public void onClick(View v)
                         {     
                        try
                                    {
                                    sendData(“0”);
                                    }
                           catch (IOException ex) { }
}
                     }); 
}

void findBT() throws IOException
    {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null)
        {
            status.setText("No bluetooth adapter available");
        }
        if(!mBluetoothAdapter.isEnabled())
        {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        mmDevice = mBluetoothAdapter.getRemoteDevice("20:13:09:23:00:48");
         //”20:13:09:23:00:48” is the MAC address of the Bluetooth module
        if (pairedDevices.contains(mmDevice))
        {
             status.setText("Bluetooth Device Found, address: " + mmDevice.getAddress() );
                Log.d("ArduinoBT", "BT is paired");
        } 
      
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
        mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(uuid);
        Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
        mmSocket = (BluetoothSocket) m.invoke(mmDevice, 1);
        mBluetoothAdapter.cancelDiscovery();
        mmSocket.connect();       
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();

        status.setText("Bluetooth Connected");
        connect.setEnabled(false);
        disconnect.setEnabled(true);
        turn_LED_ON.setEnabled(true);
        turn_LED_OFF.setEnabled(true); 
}
void sendData(String m) throws IOException
 {
mmOutputStream.write(m.getBytes());
}
void closeBT() throws IOException
{                  
mmOutputStream.close();
mmInputStream.close();
            mmSocket.close();
            status.setText("Bluetooth Disconnected");
              connect.setEnabled(true);
              disconnect.setEnabled(false);
              turn_LED_ON.setEnabled(false);
              turn_LED_OFF.setEnabled(false);      
}
}

In your activity_main.xml file create four buttons for connect, disconnect, turn_LED_ON, turn_LED_OFF operations and a TextView to display the status of the Bluetooth.


Also, include the following uses-permission in your AndroidManifest.xml file
<uses-permission android:name=”android.permission.BLUETOOTH” />

NOTETo find out the MAC address of your Bluetooth module you need to connect your module to PC and then click on the device’s properties window. You can then read the MAC address of your module from the properties window.


Hope this information was useful. If you have any doubts or you’re still encountering any errors just leave a comment and I will try my best to help you out. Keep reading! J




D3 - Knowing the insights

     D3 namely Data Driven Documents is gaining popularity among the Javascript developers and many other developers working in the field of Visualization and Data Science.
     D3.js as named is a Javascript library used for visualization and by visualization I mean serious visualization which cannot be ignored.
     Before going into D3 lets understand why do we need it. I suppose the person reading this post must be familiar with basic HTML, CSS and Javascript.

     To understand about what sort of features D3 provides we will first look at the underneath technologies used for interactive graphics :
1) WebGL - It's a javascript API for rendering interactive 3D graphics and 2D graphics without the use of plugins.

2) Canvas - Anyone who has worked on HTML5 must have heard this term frequently. Canvas is part of HTML5 and it allows for dynamic rendering of 2D shapes and bitmap images. It consists of a drawable region where some of its anticipated uses are building graphs, animations, games etc.

3) SVG - If you intend to understand D3 then the first thing that will get into your way is Scalable Vector Graphics. SVG is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation. Basically its an image format for vector graphics

Some of the benefits of SVG that you should be aware of :
small file sizes that compress well
scales to any size without losing clarity
looks great on retina displays 
design control like interactivity and filters

SVG code can be included directly within any HTML document. Web browsers have supported the SVG format for years (Except for Internet Explorer), but it never quite caught on, until now.

Now all of these technologies are the low level technologies and can be used for creating interactive visualizations but the problem that most of the developers face is they have to write a lot of code and the development cycle gets longer. To solve this problem D3 was built on top of SVG considering the advantages that it(SVG) provides. But remember the low-level technologies will provide you more flexibility than the technologies built on top of that. Again there are many libraries built on top of D3 such as C3.js, NVD3, Dimple.js and many more. But the flexibility reduces high the order and you will be limited to very few options. Rather the development time will be less. But I suggest you stick with D3.js where you will understand how exactly it works and you can be more flexible with your design.


Okay I understand that was a lot of theory but I tried to make it as concise as possible.
Lets now dive into D3 and understand its fundamentals.

D3 has quite a lot of functions that need to be understood but dont worry we will be going through some of them before getting started with writing D3 code and some more as we go on with the complex examples

Selection Functions

d3.select - selects an element from the current document
d3.select is analogous to Javascript's DOM element selection method

document.getElementById('#id') or document.getElementByClass('.class')

whereas the same code can be written resp. in d3 as

Example:
d3.select('#id') or d3.select('.class')

To select multiple elements of the same class or id use d3.selectAll method which selects all the elements matching the id or the class value from the current document

Example:
d3.selectAll('#id') will select all elements with id attribute as 'id'

The d3.select or d3.selectAll method will always return a selection which you can use for accessing the attributes of that element
Remember, d3 works on the pipeline architecture and you will understand it with the next example

Now suppose I have a input element with a value attribute attached to it as

Example:
<input type="text" value="Hello World" ></input>

d3.select('input') selects the input text element
d3.select('input').attr("value", "Hello") can be used to set the value attribute whereas
d3.select('input').attr("value") will return the text value "Hello World"


Thus,
selection.attr - used for getting or setting attribute values

Similarly,
selection.classed - used to add or remove CSS classes

selection.style - used to get or set style properties

selection.property - used to get or set raw properties

selection.html - get or set inner HTML content

Now, to add an element to the current DOM element we have
selection.append which creates and appends new elements to the selected element


To append a <P> tag between div element we would use something like

Example:
<div></div>

d3.select('div').append("p")

Obviously we will be appending more complex elements in the future examples but this is just to give you a taste of the functions.

Okay, this should get you started to start writing the d3 code. There are still a lot of functions to be studied and we will understand them as we proceed with the examples.

Now, lets first create a circle using the SVG code and then try to draw it using the selection functions that we have studied above

<svg width="200" height="200">
   <circle cx="25" cy="25" r="25" fill="purple" />
</svg>


Corresponding d3 code :

d3.select("body").append("svg")
.attr("width", 50)
.attr("height", 50)
.append("circle")
.attr("cx",25)
.attr("cy",25)
.attr("r",5)
.style("fill", "purple");

That looks simple right! But suppose if an element has 20 attributes we have to repeat that .attr() function 20 times to set those values. God save me!!!
Well, d3 was developed to make developers life simple and d3 enables us to set multiple attributes at a time in the json form as below

d3.select("body").append("svg")
.attr("width", 50)
.attr("height", 50)
.append("circle")
.attr({
"cx":25,
"cy":25,
"r":5,
"fill": "purple"
});

Good. Lets move on!

Below I have written the SVG code for drawing a rectangle and an ellipse.
Now its your turn to get your hands dirty with basic d3 functions. Go on and try to draw these shapes in d3 using the functions that we've learnt today and don't forget to include the d3.js library in your html document.

SVG code for drawing a rect :

<svg width="200" height="200">
   <rect x="20" y="0" width="50" height="50" fill="red" />
</svg>


SVG code for drawing an ellipse :

<svg width="200" height="200">
   <ellipse cx="50" cy="50" rx="20" ry="10" fill="blue" />
</svg>


Okay! So we've come too far and I guess this is enough for this post. Give me a rest :P
But you guys don't stop and check out my next post to further dive deep into d3.
Thanks!







References:
https://github.com/mbostock/d3/wiki/API-Reference
D3.js Documentation