Advertisement

Sri Lanka's First and Only Platform for Luxury Houses and Apartment for Sale, Rent

Sunday, December 22, 2013

Raspberry pi LED Blinker

Ever since I came to Malaysia my inventive side is becoming more and more sharper. Mainly because of the Electronic components available easily in Malaysia for affordable prices. I bought a myself a Raspberry pi Model B with a Transparent casing + 8 Gb SSD Card with Preloaded Noobs for just MYR 199 (USD 60.53).

Furthermore I went to an area called Jalan Pasar in Pudu where there are lots and lots of Electronic shops which sells all sorts of components. I am waiting to do more hacks and hobby projects in the future but to start off I did a small LED Blinker project using Raspberry pi.

The following steps needs to be carried out to Run the LED Blinker in Raspberry pi.
  • Login to Raspberry pi
  • Open a LXTerminal window
  • Download the python GPIO library
wget http://raspberry-gpio-python.googlecode.com/files/RPi.GPIO-0.4.1a.tar.gz



  • Untar the Tar file

  • tar zxvf RPi.GPIO-0.4.1a.tar.gz



  • Go into untared directory

  • cd RPi.GPIO-0.4.1a



  • Install GPIO for python

  • sudo python setup.py install

    If you get errors during the installation process then you must first do the following


    source/py_gpio.c:23:20: fatal error: Python.h: No such file or directory
    Compilation terminated.
    error: command 'gcc' failed with exit status 1
    
    • Run apt-get update
    sudo apt-get update
    
    • The install python dev (Debian)
    sudo apt-get install python-dev
    

    • Pidora 

    sudo yum -y install python-devel

    After that do the following wiring where an LED ground is connected using a 1K Resistor to the Raspberry pi GND pin 6. And pin 7 GPIO 4 is connected to the LED Positive.


    Then copy the following code to a text editor and save it as blink_led.py

    import RPi.GPIO as GPIO 
    import time 
    import threading
    
    GPIO.setmode(GPIO.BOARD) 
    GPIO.setup(7, GPIO.OUT) 
    
    class Blinker(threading.Thread):
        def __init__(self, speed, times):    
            threading.Thread.__init__(self);
            self.speed = speed;    
            self.times = times;
    
        def run(self):
            for i in range(0,self.times):
                print "Time : %d" % ((i+1))
                GPIO.output(7,True)
                time.sleep(self.speed)
                GPIO.output(7,False)
                time.sleep(self.speed)
            print "Blinking Complete!" 
            GPIO.cleanup()    
    
    blinker = Blinker(1, 10)
    blinker.start()
    
    • Finally close the LXTerminal and open a new one and execute the following
    sudo python blink_led.py
    

    Everything working together


    References
    • http://www.thirdeyevis.com/pi-page-1.php#gpio-setup
    • http://www.thirdeyevis.com/pi-page-2.php
    • http://www.raspberrypi.org/phpBB3/viewtopic.php?f=31&t=13003

      Saturday, October 19, 2013

      Giving RC Car a simple brain using Arduino + Ping (Ultrasonic) Sensor

      It has been quite a sometime from my last post. Mainly due to busy schedules and settling down in Malaysia I would say. But I came to back to Sri Lanka on vacation and got time on a lazy Saturday morning and put together a small Arduino + RC Car setup.

      In one of my previous posts I teared down a RC Car and explained the internals of that. Working further on that I managed to write a small Arduino sketch to work with a Ping Sensor to give a simple brain to the RC Car. What makes this distinguishable from other RC Car + Arduino hacks is that, Almost all other hacks use the Arduino to control the Remote Control not the Car itself. But I wanted to control the car directly using the Arduino so that I can eventually achieve the goal of using an Android phone connected to Arduino using a USB Host Shield to act as the Smart Brain of the RC Car.

      The following items were used in setting up this prototype.
      1. 1 Arduino UNO Rev 3
      2. 1 Breadboard
      3. 1 DFRobot URM37 V3.2 Ultrasonic Sensor
      4. Some Jumper Cables
      5. And of course a RC Car
      Following is the Arduino Sketch. The DFRobot Ultrasonic Sensor was used in TTL Mode and Arduino Pin 3 was connected to PWM and 5 was connected to COMP/TRIG of the Sensor. The Arduino Digital Out pin 11 was used for forward actuating and pin 10 was used for backward actuating of the RC Car . I have soldered jumper cables to the RC Car so that they can be easily used and distinguished. 

      int URPWM = 3; 
      int URTRIG=5; 
      int forwardPin = 11;
      int backwardPin = 10;
       
      unsigned int Distance=0;
      uint8_t EnPwmCmd[4]={0x44,0x02,0xbb,0x01};    
      boolean forward = false;
      boolean backward = false;
      int minDistanceCm = 5;
      
      void setup(){                                 
        pinMode(URTRIG,OUTPUT);                     
        digitalWrite(URTRIG,HIGH);                  
        
        pinMode(URPWM, INPUT);                      
        pinMode(forwardPin, OUTPUT);
        pinMode(backwardPin, OUTPUT);
      }
       
      void loop()
      {
         digitalWrite(URTRIG, LOW);
         digitalWrite(URTRIG, HIGH);               
         unsigned long DistanceMeasured=pulseIn(URPWM,LOW);
           
         if(DistanceMeasured==50000){              
               
         } else {
            Distance=DistanceMeasured/50;           
         }
        
         if(Distance > minDistanceCm) {
            forward = true;  
            backward = false;
         } else {
            forward = false;
            backward = true; 
         }
         
         if(forward) {
            digitalWrite(forwardPin, HIGH);
            delay(100);
            digitalWrite(forwardPin, LOW);
         } else {
            digitalWrite(backwardPin, HIGH);
            delay(200);      
            digitalWrite(backwardPin, LOW);     
         }
         delay(400);
      }                      
       
      
      

      The video below shows the prototype in action. The USB cable is only used to supply electricity for the Arduino. Adding a battery will eliminate the need for the USB cable.


      This prototype is by no means complete. I did this so that I can achieve the goal of using an Android phone with Camera + GPS as the brain. But this step was a necessary and crucial learning stage for me. Constructive criticism is always welcome.

      References
      1. DFRobot Ultrasonic Sensor Manual - http://www.dfrobot.com/wiki/index.php/URM37_V3.2_Ultrasonic_Sensor_(SKU:SEN0001)

      Monday, June 3, 2013

      New Country, New Job!

      I got to know about a job in Malaysia in the month of March while I was working at Virtusa. At that point I didn't know in which company I would be working in, but I wanted to work in a foreign country so applied. Days later I got a call from an agent in Sri Lanka that some people would be coming down from Malaysia for the interview and I would be called within 2 weeks time. To be honest I wasn't sure of what he said but kept my fingers crossed.

      Right after two weeks I did get a call from the agent saying I have an interview on 4th of April at Galadari Hotel Colombo. I went there and there were three people from Malaysia from the company MIMOS including the CTO.

      MIMOS is Malaysia's National Research and Development Institute for ICT. It comes directly under the purview of MOSTI, Ministry of Science, Technology and Innovation. It seemed a really good offer for me and I did quite well in the interview due to my preparedness. The CTO was impressed of my little Arduino Projects and during the interview I knew that I had at least 70% chance of getting in.

      After two more weeks I got the news that I have been selected out of 14 interviewees as one of the potential employees. I was over the moon and started preparing to come to Malaysia. After more than one month of preparing I finally landed in Malaysia on 02nd of June 2013 at 7:15 a.m.

      Now I am temporarily residing at Bukit Jalil which is closed to Technology Park Malaysia which is where MIMOS is located.

      All thanks to god for giving me such a wonderful opportunity. 

      Thursday, April 25, 2013

      RC Car Tear Down and Control Using Arduino

      In a previous post I showed the RC Car I bought and the internals of it. As I mentioned, there was a RX 2 Chip inside the Car but the pin layout was not exactly same as it is mentioned in the datasheet. So I had to ask my wife for help in controlling the car from the remote control and used a multimeter to find out which pins are being activated for each command. The datasheet mentioned that;


      1. Pin No 11 = Forward
      2. Pin No 12 = Backward
      3. Pin No 6 = Right
      4. Pin No 7 = Left
      But as it turns out 

      Pin No 6 is Left and Pin No 7 is Right. So after finding those out I soldered required wires to the Circuit and hoping to work more on that. 

      The video of the testing is below

      Wednesday, April 10, 2013

      Best Practice in Web Services Usage

      Web Services are everywhere and so widely used today. There are several types of Web Services but most widely used ones are SOAP based, REST based web services. I am not going to defferentiate the two here but SOAP based Web Services are much more widely used than REST based mainly because of their reliability and security.

      I am not going to implement a fully fledged web service here but just to provide some additional security measures that can be implemented to secure your web services. Nope this not about Authentication and Authorization. Those needs to be implemented anyhow.

      According to the famous US based Internet Application security vulnerability testing company Veracode, web services must only expose their WSDL, XSD only to their intended and authorized consumers. This enables the information web services expose to be really limited to people who are intended to use those. But by default web services allow to see the WSDL and XSD by calling the below url.

      http://<host>:<port>/MyApplication/services/MyService?wsdl

      or

      http://<host>:<port>/MyApplication/services/MyService?xsd
      

      This can be restricted by writing a Servlet Filter similar to the below one which Expects Query Strings to be Base64 Encoded and have the format like below

      ServiceDefinition#1234567890
      

      1234567890 can be replaced with a timestamp in milli seconds so that the Encoded string will be different each time.

      When encoded it will look like the following

      U2VydmljZURlZmluaXRpb24jMTIzNDU2Nzg5MA==
      

      The implementation of the Filter is as follows

      import java.io.ByteArrayOutputStream;
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.IOException;
      import java.io.InputStream;
      import java.io.UnsupportedEncodingException;
      import java.util.HashMap;
      import java.util.Map;
      
      import javax.servlet.Filter;
      import javax.servlet.FilterChain;
      import javax.servlet.FilterConfig;
      import javax.servlet.ServletContext;
      import javax.servlet.ServletException;
      import javax.servlet.ServletRequest;
      import javax.servlet.ServletResponse;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      
      import org.apache.axiom.om.util.Base64;
      import org.apache.commons.io.FilenameUtils;
      
      public class InvalidUrlFilter implements Filter {
          
          private Map<String, byte[]> wsdlMap = new HashMap<String, byte[]>();    
          
          private Map<String, byte[]> secureWsdlMap = new HashMap<String, byte[]>();
      
          @Override
          public void destroy() {
              wsdlMap.clear();
              wsdlMap = null;
          }
      
          @Override
          public void doFilter(ServletRequest request, ServletResponse response,
                  FilterChain filterChain) throws IOException, ServletException {
              doFilter((HttpServletRequest) request, (HttpServletResponse) response, filterChain);        
          }
          
          public void doFilter(HttpServletRequest request, HttpServletResponse response,
                  FilterChain filterChain) throws IOException, ServletException {
              String queryString = request.getQueryString();
              boolean isError = false;
              boolean isWsdlProcessed = false;
              if(queryString != null) {
                  queryString = queryString.toUpperCase();            
                  if(queryString.endsWith("WSDL") || queryString.endsWith("XSD")) {
                      response.sendError(HttpServletResponse.SC_NOT_FOUND);
                      return;
                  }
                  if(isValidWSDLRequest(request.getQueryString())) {
                      String serviceName = FilenameUtils.getBaseName(request.getRequestURI().toString());
                      
                      byte[] wsdlbytes = secureWsdlMap.get(serviceName);
                      if(wsdlbytes == null) {
                          wsdlbytes = wsdlMap.get(serviceName);
                          if(request.isSecure()) {                    
                              String wsdl = new String(wsdlbytes, "UTF-8");
                              wsdl = wsdl.replaceAll("location=\"http\"", "location=\"https\"");
                              wsdlbytes = wsdl.getBytes();
                              secureWsdlMap.put(serviceName, wsdlbytes);
                          } 
                      }        
                      
                      try {                
                          response.setContentType("text/xml");            
                          response.getOutputStream().write(wsdlbytes);
                          isWsdlProcessed = true;
                      } catch(Exception e) {
                          isError = true;
                      } finally {
                          if(!isError && isWsdlProcessed) {
                              response.getOutputStream().flush();
                              response.getOutputStream().close();
                          }
                      }
                  } 
              }
              
              if(!isWsdlProcessed) {
                  filterChain.doFilter(request, response);
              }
                      
          }
      
          @Override
          public void init(FilterConfig filterConfig) throws ServletException {
              ServletContext servletContext = filterConfig.getServletContext();
              File servicesDir = new File(servletContext.getRealPath("/WEB-INF/services"));
              
              loadWsdl(servicesDir);
              
          }
          
          private String decoder(String value) {
              String result = "";
              try {
                  if(value != null && !value.equals("")) {
                      String tmpResult = new String(new Base64().decode(value), "UTF-8");
                      
                      String[] vals = tmpResult.split("#");
                      if(vals.length > 1) {
                          result = vals[0];
                      }                
                  } 
              } catch (UnsupportedEncodingException e) {
                  // Must be Logged
              }
              return result;
          }
          
          private void loadWsdl(File servicesDir) {
              for(File directory:servicesDir.listFiles()) {
                  if(directory.isDirectory()) {
                      String serviceName = FilenameUtils.getBaseName(directory.getName());
                      InputStream is = null;
                      ByteArrayOutputStream os = null;
                      try {
                          is = new FileInputStream(directory.getAbsolutePath()+"/META-INF/"+serviceName+".wsdl");
                          os = new ByteArrayOutputStream();
                          
                          byte[] data = new byte[1024];
                          int read = 0;
                          while((read = is.read(data)) > 0) {
                              os.write(data, 0, read);
                          }
                          os.flush();                
                          
                          wsdlMap.put(serviceName, os.toByteArray());
                          
                      } catch (Exception e) {
                          // Must log                    
                      } finally {
                          if(os != null) {
                              try {
                                  os.close();
                              } catch (IOException e) {
                                  
                              }
                          }
                          
                          if(is != null) {
                              try {
                                  is.close();
                              } catch(IOException e) {
                                  
                              }
                          }
                      }
                      
                  }
              }
          }
          
          private boolean isValidWSDLRequest(String queryString) {
              boolean result = false;
              String[] values = queryString.split("&");
              for(String value:values) {
                  if(decoder(value).equals("ServiceDefinition")) {
                      result = true;
                      break;
                  }
              }
              return result;
          }
          
          
          
          
      }
      
      

      And web.xml will have the following

          <filter>
              <filter-name>InvalidUrlFilter</filter-name>
              <filter-class>com.shazin.filters.InvalidUrlFilter</filter-class>
          </filter>
          
          <filter-mapping>
              <filter-name>InvalidUrlFilter</filter-name>
              <servlet-name>AxisServlet</servlet-name>
          </filter-mapping>
      

      Now the WSDL can be accessed by using a URL similar to

      http://<host>:<port>/MyApplication/services/MyService?U2VydmljZURlZmluaXRpb24jMTIzNDU2Nzg5MA==
      

      Restricts the exposure of the Web Service WSDL to intended consumers only. But for this to work the web services must use HTTPS. If not just Base64 encoding wouldn't suffice. Then it needs to be encrypted before Base64 encoded.

      Tuesday, March 26, 2013

      My New RC Car

      This may sound really childish but yes I bought myself a Brand New Ferrari Model RC Car. It is a Red color car which you can see in the below image.


      The RC Car uses Radio Frequency 27 Mhz to receive control from the Remote. This is how the under the hood of the car looks like.


      Some more closer looks


      The IC in RC Car is RX - 2 which is the common IC in Chinese RC Cars.


      The under the hood of the Remote Control looks like this.


      The IC of the Remote Control is TX - 2. This is the datasheet for TX - 2 and RX - 2 

      Friday, March 22, 2013

      Android 4.1.2 Jelly Bean and Arduino Mega 2560 with USB Host Shield Communication

      Few  weeks ago I wrote my first Android Jelly Bean App named ColorChanger. Since then I wanted to integrate it with Arduino and Control a physical RGB LED Light from the ColorChanger Android App. I finally managed to get it done using the following Items.
      1. Arduino Mega 2560 Rev 3
      2. DFRobot USB Host Shield 
      3. Arduino IDE 0023
      4. ADK Library
      5. 1 RGB LED
      6. 1 1k Resistor
      7. Few Jumper Cables
      8. One USB to Micro USB Cable
      Few things changed from the original ColorChanger App starting from the AndroidManifest.xml where I had to allow my MainActivity to listen for USB_ACCESSORY_ATTACHED intent action and when my Accessory connects open the ColorChanger App.

      <?xml version="1.0" encoding="utf-8"?>
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.shazin.colorchanger"
          android:versionCode="1"
          android:versionName="1.0" >
          
          <uses-sdk
              android:minSdkVersion="8"
              android:targetSdkVersion="17" />
      
          <application
              android:allowBackup="true"
              android:icon="@drawable/ic_launcher"
              android:label="@string/app_name"
              android:theme="@style/AppTheme" >
              <activity
                  android:name="com.shazin.colorchanger.MainActivity"
                  android:label="@string/app_name" >
                  <intent-filter>
                      <action android:name="android.intent.action.MAIN" />
                      <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
                      
                      <category android:name="android.intent.category.LAUNCHER" />
                  </intent-filter>
                  
                  <meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
                      android:resource="@xml/accessory_filter" /> 
              </activity>
          </application>
      
      </manifest>
      

      The filtering criteria is placed in res/xml/accessory_filter.xml file which is as follows

      <?xml version="1.0" encoding="utf-8"?>
      
      <resources>
          <usb-accessory model="ColorChangerApp" manufacturer="Shazin Sadakath" version="1.0"/>
      </resources>
      
      Then my MainActivity class changed as follows
      package com.shazin.colorchanger;
      
      import java.io.FileDescriptor;
      import java.io.FileInputStream;
      import java.io.FileOutputStream;
      import java.io.IOException;
      
      import android.annotation.SuppressLint;
      import android.app.Activity;
      import android.app.PendingIntent;
      import android.content.BroadcastReceiver;
      import android.content.Context;
      import android.content.Intent;
      import android.content.IntentFilter;
      import android.graphics.Color;
      import android.hardware.usb.UsbAccessory;
      import android.hardware.usb.UsbManager;
      import android.os.Bundle;
      import android.os.ParcelFileDescriptor;
      import android.view.Menu;
      import android.widget.LinearLayout;
      import android.widget.SeekBar;
      import android.widget.SeekBar.OnSeekBarChangeListener;
      import android.widget.TextView;
      import android.widget.Toast;
      
      
      public class MainActivity extends Activity implements OnSeekBarChangeListener, Runnable {
      
          private TextView textViewColor;
          
          private SeekBar seekBarRed;
          
          private SeekBar seekBarGreen;
          
          private SeekBar seekBarBlue;
          
          private byte red, green, blue;
          
          private LinearLayout linearLayout;
          
          private UsbAccessory mAccessory;
          
          private ParcelFileDescriptor mFileDescriptor;
          
          private FileInputStream mInputStream;
          
          private FileOutputStream mOutputStream;
          
          private UsbManager mUsbManager;
          
          private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
              private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
               
                  public void onReceive(Context context, Intent intent) {
                      String action = intent.getAction();
                      if (ACTION_USB_PERMISSION.equals(action)) {
                          synchronized (this) {
                              UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
      
                              if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                                  if(accessory != null){
                                      //call method to set up accessory communication
                                      openAccessory();
                                  }
                              }
                              else {
                                  //Log.d(TAG, "permission denied for accessory " + accessory);
                                  Toast.makeText(context, "permission denied for accessory "+accessory, 2).show();
                              }
                          }
                          unregisterReceiver(mUsbReceiver);
                      }    
                      
                  }
              };
          
              public final BroadcastReceiver mUsbDetachReciever = new BroadcastReceiver() {
      
                  @Override
                  public void onReceive(Context context, Intent intent) {
                      String action = intent.getAction();
                      if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
                          UsbAccessory accessory = (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
                          if (accessory != null) {
                              cleanUp();                
                          }
                          unregisterReceiver(mUsbDetachReciever);
                      }
                      
                  }
                  
              };
              
      
      
              private boolean mPermissionRequestPending;        
              
              private void cleanUp() {
                  try {
                      if(mFileDescriptor != null)
                          mFileDescriptor.close();
                      
                      if(mInputStream != null) 
                          mInputStream.close();
                      
                      if(mOutputStream != null)
                          mOutputStream.close();
                      mAccessory = null;
                      mUsbManager = null;
                      Toast.makeText(this, "Closed all resources", 2).show();
                  } catch (IOException e) {
                      Toast.makeText(this, "Error occured "+e, 2).show();
                  }
              }
              
                  
          @SuppressLint("NewApi")
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              
              linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
              
              textViewColor = (TextView) findViewById(R.id.textViewColor);
                      
              seekBarRed = (SeekBar) findViewById(R.id.seekBarRed);
              seekBarGreen = (SeekBar) findViewById(R.id.seekBarGreen);
              seekBarBlue = (SeekBar) findViewById(R.id.seekBarBlue);
              
              seekBarBlue.setOnSeekBarChangeListener(this);
              seekBarGreen.setOnSeekBarChangeListener(this);
              seekBarRed.setOnSeekBarChangeListener(this);
              
              textViewColor.setText(String.format("(%d, %d, %d)", red, green, blue));
              linearLayout.setBackgroundColor(Color.rgb(red, green, blue));
              
              
              mAccessory = (UsbAccessory) getIntent().getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
              Toast.makeText(this, "USB Accessory = "+mAccessory, 2).show();
              
              mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
              Toast.makeText(this, "USB Manager = "+mUsbManager, 2).show();
              
              PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
              IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
              registerReceiver(mUsbReceiver, filter);
              Toast.makeText(this, "Intent Registered", 2).show();
              
              if(mUsbManager.hasPermission(mAccessory)) {
                  Toast.makeText(this, "Accessory has permission", 2).show();
                  unregisterReceiver(mUsbReceiver);
                  openAccessory();
              } else {            
                  Toast.makeText(this, "Accessory has no permission", 2).show();
                  synchronized (mUsbReceiver) {                
                      if (!mPermissionRequestPending) {
                          mUsbManager.requestPermission(mAccessory, mPermissionIntent);
                          Toast.makeText(this, "Permission Request Sent", 2).show();
                          mPermissionRequestPending = true;
                      }
                  }
              }
              
              IntentFilter filter2 = new IntentFilter(ACTION_USB_PERMISSION);
              filter2.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
              registerReceiver(mUsbDetachReciever, filter2);        
              
          }
          
          public void onDestroy() {
              super.onDestroy();
              cleanUp();
          }
          
          @SuppressLint("NewApi")
          private void openAccessory() {
              //Log.d(TAG, "openAccessory: " + accessory);
              mFileDescriptor = mUsbManager.openAccessory(mAccessory);
              Toast.makeText(this, "Accessory Opened", 2).show();
              if (mFileDescriptor != null) {
                  FileDescriptor fd = mFileDescriptor.getFileDescriptor();
                  Toast.makeText(this, "File Desc "+fd, 2).show();
                  mInputStream = new FileInputStream(fd);
                  mOutputStream = new FileOutputStream(fd);
                  
              }
          }
      
          @Override
          public boolean onCreateOptionsMenu(Menu menu) {
              // Inflate the menu; this adds items to the action bar if it is present.
              getMenuInflater().inflate(R.menu.main, menu);
              return true;
          }
      
          @Override
          public void onProgressChanged(SeekBar seekBar, int value, boolean flag) {
              if(seekBar == seekBarRed) {
                  red = (byte) value;
              } else if(seekBar == seekBarGreen) {
                  green = (byte) value;
              } else if(seekBar == seekBarBlue) {
                  blue = (byte) value;
              }
              linearLayout.setBackgroundColor(Color.rgb(red & 0xFF, green & 0xFF, blue & 0xFF));
              textViewColor.setText(String.format("(%d, %d, %d)", red & 0xFF, green & 0xFF, blue & 0xFF));
              if(mOutputStream != null) {
                  try {
                      byte[] data = new byte[4];
                      data[0] = 0x2;
                      data[1] = red;
                      data[2] = green;
                      data[3] = blue;
                      mOutputStream.write(data);
                      mOutputStream.flush();
                  } catch (IOException e) {
                      Toast.makeText(this, "Error "+e, 2).show();
                  }
              }    
          }
      
          @Override
          public void onStartTrackingTouch(SeekBar arg0) {
              // TODO Auto-generated method stub
              
          }
      
          @Override
          public void onStopTrackingTouch(SeekBar arg0) {
              // TODO Auto-generated method stub
              
          }
      
          @Override
          public void run() {
          
          }
      
      }
      
      

      And the Arduino Sketch is as follows

      #include <avrpins.h>
      #include <max3421e.h>
      #include <usbhost.h>
      #include <usb_ch9.h>
      #include <Usb.h>
      #include <usbhub.h>
      #include <avr/pgmspace.h>
      #include <address.h>
      
      #include <adk.h>
      
      #include <printhex.h>
      #include <message.h>
      #include <hexdump.h>
      #include <parsetools.h>
      // For Arduino IDE 1.0.x Only following two is needed
      #include <adk.h>
      #include &ltusbhub.h>
      
      USB Usb;
      USBHub hub0(&Usb);
      USBHub hub1(&Usb);
      ADK adk(&Usb,"Shazin Sadakath",
                  "ColorChangerApp", // This name Should match with xml/res/accessory_filter.xml name
                  "Color Changer App",
                  "1.0",
                  "http://shazsterblog.blogspot.com",
                  "0000000012345678");
      
      #define  LED1_RED       5
      #define  LED1_GREEN       4
      #define  LED1_BLUE       3
      
      void setup();
      void loop();
      
      void init_leds()
      {
          digitalWrite(LED1_RED, 0);
          digitalWrite(LED1_GREEN, 0);
          digitalWrite(LED1_BLUE, 0);
      
          pinMode(LED1_RED, OUTPUT);
          pinMode(LED1_GREEN, OUTPUT);
          pinMode(LED1_BLUE, OUTPUT);
      }
      
      void setup()
      {
          Serial.begin(115200);
          Serial.println("\r\nADK demo start");
              
              if (Usb.Init() == -1) {
                Serial.println("OSCOKIRQ failed to assert");
              while(1); //halt
              }//if (Usb.Init() == -1...
      
      
          init_leds();
      }
      
      void loop()
      {
        uint8_t rcode;
        uint8_t msg[4] = { 0x00 };
         Usb.Task();
         
         if( adk.isReady() == false ) {
           analogWrite(LED1_RED, 255);
           return;
         }
         uint16_t len = sizeof(msg);
         
         rcode = adk.RcvData(&len, msg);
         if( rcode ) {
           USBTRACE2("Data rcv. :", rcode );
         } 
         if(len > 0) {
           if(msg[0] == 0x2) {
               USBTRACE("\r\nData Packet.");
               uint8_t r = (msg[1]) & 0xFF;
               uint8_t g = (msg[2]) & 0xFF;
               uint8_t b = (msg[3]) & 0xFF;
               analogWrite(LED1_RED, 255 - r);
               analogWrite(LED1_GREEN, 255 - g);
               analogWrite(LED1_BLUE, 255 - b);
           }
           
      
         }
         
         msg[0] = 0x1;
         
            delay( 10 );       
      }
      

      The video of the whole thing working together is available below.

       

      References