Search This Blog

Saturday, January 7, 2012

Android java app - Blinking camera flash LED

I'm developing hardware control applications for the Android phone platform to replicate functionality I've previously used in gadgets for the Arduino.

Finally I achieved my goal of replicating the very first "I'm Alive!" hardware test on a new platform.  Whenever you make a new gadget, the first program you run blinks a light to show health.

I was able to get the LED used for the camera flash to blink!  Hooray!   In my earlier post I found the code and permissions needed to turn it on and off with a button press.   Then I had to find a suitable system clock to use to time the blinking, but got sidetracked generating audio tones.  So finally I put the two together and here is how I did it using the Android SDK in Eclipse.  This technique is limited to <500Hz because the system clock is milliseconds.   The next step will be to find a method to access a faster clock.  However if the goal is communicate to humans or slow serial interface, this might be good enough.

in AndroidManifest.xml you need (you may not need them all, didn't test that)

    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.FLASHLIGHT"/>
    <uses-permission android:name="android.permission.HARDWARE_TEST"></uses-permission>

The code I wrote looks like this (copied out the relevant bits from a larger program so hopefully I didn't leave out something critical).  This code was placed in a callback from a button press.  The actual flashing is just done with the for loops, but the rest starts it in another thread so the phone is locked up while this is running.  You don't have to do this but you might frustrate a user if you don't.  I tried it first without the additional thread.   The full app is here, but the relevant bits are below  http://code.google.com/p/arduino-java-xyzcnc/downloads/detail?name=Siliconfish%20Blink.zip&can=2&q=#makechanges
  
    //variables for light blinking
    private final int blinkrate_ms = 100;
    private long nextblink = blinkrate_ms;
        
            //blink the light
            // Use a new thread to flash as this can take a while
                final Thread thread = new Thread(new Runnable() {
                    public void run() {
                        handler.post(new Runnable() {


                            public void run() {                              
                                // loop to flash the camera LED
                                for(int q = 0; q<10; q++)  {
                            nextblink = SystemClock.elapsedRealtime() + blinkrate_ms;
                            while (SystemClock.elapsedRealtime()<nextblink) {
                            setOn(true, null);
                            }
                            nextblink = SystemClock.elapsedRealtime() + blinkrate_ms;
                            while (SystemClock.elapsedRealtime()<nextblink) {
                            setOn(false, null);
                            }
                            } //for
                                
                            }
                        });
                    } 
                }); //thread
                thread.start();
           
                  
It required these functions which turn on and off the LED
     
    // code largely copied from   http://www.java2s.com/Open-Source/Android/Tools/quick-settings/com/bwx/bequick/flashlight/Droid22Flashlight.java.htm
    // Controls the camera flash LED
    
    private Object mManager;


    public boolean isOn(Context context) {
        try {
            Object manager = getManager();
            if (manager != null) {
                Method getFlashlightEnabledMethod = manager.getClass()
                        .getMethod("getFlashlightEnabled");
                return (Boolean) getFlashlightEnabledMethod
                        .invoke(manager);
            }
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
        return false;
    }


    public void setOn(boolean on, Context context) {
        try {
            Object manager = getManager();
            if (manager != null) {
                Method setFlashlightEnabledMethod = manager.getClass()
                        .getMethod("setFlashlightEnabled",
                                boolean.class);
                setFlashlightEnabledMethod.invoke(manager, on);
            }
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
    }


    private Object getManager() {
        if (mManager == null) {
            try {
                Class<?> managerClass = Class
                        .forName("android.os.ServiceManager");
                Method methodGetService = managerClass.getMethod(
                        "getService", String.class);
                IBinder hardwareService = (IBinder) methodGetService
                        .invoke(managerClass, "hardware");


                Class<?> stubClass = Class
                        .forName("android.os.IHardwareService$Stub");
                Method asInterfaceMethod = stubClass.getMethod(
                        "asInterface", IBinder.class);
                mManager = asInterfaceMethod.invoke(stubClass,
                        hardwareService);
            } catch (Exception e) {
                Log.e(TAG, "", e);
            }
        }
        return mManager;
    }

5 comments:

  1. Hi,

    Great post (and great blog too). I just did a Google search on controlling the flash LED of an Android phone and ended up here - which was exactly where I needed to be.

    I'm in the beginning stages of trying to create a simple Visual Light Communications link from an Android Phone to my Arduino board. The fact that you've been able to flash the LED at 500Hz is certainly great news for me (It means I can probably get the data rate at up to 10bytes per second).

    Out of curiosity, did you get much further down the path to seeing if you could get the frequency higher? Or is the system clock too big an obstacle?

    Cheers,

    Keiran.

    ReplyDelete
  2. Out of town and didn't see this comment. Here is the problem. In a later post I discussed System.nanotime(), which is a faster timer, but rapidly you run into processor interrupts. I probably should have written more about that topic but veered off into publishing apps.

    If you flash the LED really fast you'll see that sometimes the processor gets busy and the flashing gets very flaky, since android is not a real time operating system.

    If you want to use it for communications, and I bailed on that idea, you are going to have to find a coding scheme that allows for an irregular clock. Let me know if you figure it out!

    ReplyDelete
  3. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete
  4. The Cuffmate LED is another wonderful flashlight that comes with a handcuff key made into it for all police officers. The Cuffmate is a dual LED flashlight made of an unbreakable polymer case with a steel alloy handcuff key attached to one end. Bussmann Fuses

    ReplyDelete