Advertisement

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

Thursday, December 22, 2011

Batch File to Make Copies of a File in a Loop

During my work time I had to create a batch of files from a single file so that those can be used to load test a system. I wrote small batch file which does the job

SET /p NOOFFILES="No Of Files : "
SET I=0
SET COPYCMD=/Y
:Start
CP ./File.zip ./File-%I%.zip
SET /a I+=1
IF %NOOFFILES% == %I% (
    GOTO End
) ELSE ( 
    GOTO Start
)
:End
The script first prompts for the no of files which needs to be created and then creates those files.

Friday, December 2, 2011

A Comparison of CountDownLatch, CyclicBarrier and Semaphore

Recently I have been developing some applications with multithreading using java. And I wanted to use waiting of all Child Threads to finish in order to continue on with the Parent thread. I did some research and found out that from Java 1.5 onwards there have been some classes introduced within java.util.concurrent package where the scenario I am trying to create can be. the classes are;

  • CountDownLatch
  • CyclicBarrier
  • Semaphore
CountDownLatch and CyclicBarrier on the first look seems to do the same task and I read some blogs where they have tried to explain the difference of the two. Most common differences many were saying were;
  1. CountDownLatch can not be reused after meeting the final count.
  2. CountDownLatch can not be used to wait for Parallel Threads to finish.
  3. CyclicBarrier can be reset thus reused
  4. CyclicBarrier can be used to wait for Parallel Threads to finish.
From these explanation the picture I got was this;

If a Main thread creates 5 different thread. CountDownLatch can be used by the Main Thread to wait on the Child Threads. Where as CyclicBarrier can be used to enable waiting on Threads until each other finish.
Thus CountDownLatch is a top down waiting where as CyclicBarrier is across waiting.

But this wasn't convincing enough for me because no blog clearly explained the practical usage of the two classes. Furthermore there weren't not much talk about the powerful Semaphore class in those either. So I did some testing on that too and this is what I found out.

I try to explain the Theoretical as well as Practical use of the 3 classes. Ok here goes.

CountDownLatch can be used to monitor the completion of the Children Threads if the size of the created children is known forehand. CountDownLatch enables a Thread or Threads to wait for completion of Children Threads. But there is no waiting amongst the Children until they finish each others tasks. Children may execute asynchronously and after their work is done will exit making a countdown.

Practical Example : Main thread creates 10 Database Connections and Creates 10 different Threads and assigns those DB connection to the threads one each. But the Main thread must wait until all 10 Threads finish their DB Operation before closing the DB Connections. Children will exit after performing the DB Operation. A CountDownLatch can be used in this scenario.




import java.util.concurrent.*;
import java.util.*;
import java.text.*;
/**
 * @author Shazin Sadakath
 *
 */
public class CountDownLatchTest {
    private static final int MAX_THREADS = 5;

    public static void main(String[] args) throws Exception {
        CountDownLatch countDownLatch = new CountDownLatch(MAX_THREADS);
    
        System.out.println("Spawning Threads");
        for(int i=0;i<MAX_THREADS;i++) {
            Thread t = new Thread(new WorkerThread(countDownLatch, String.format("Thread-%d", i)));
            t.start();
        }
        System.out.println("Spawning Finished");
        System.out.println("Waiting All Threads to Finish");
        countDownLatch.await(); // Await is void
        System.out.println("All Threads are Finished");
    }
    
    private static class WorkerThread implements Runnable {
        private CountDownLatch countDownLatch;
        
        private String name;
        
        public WorkerThread(CountDownLatch countDownLatch, String name) {
            this.name = name;
            this.countDownLatch = countDownLatch;
        }
        
        public void run() {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");                
                System.out.printf("%s : Doing Some Work on %s\n", getFormattedDate(sdf), name);
                Thread.sleep(getRandomWaitTime());
                System.out.printf("%s : Doing Some more work on %s\n", getFormattedDate(sdf), name);
                Thread.sleep(getRandomWaitTime());
                System.out.printf("%s : Finished work on %s\n", getFormattedDate(sdf), name);
                countDownLatch.countDown(); 
                System.out.printf("%s : Count Down Latch count on %s is %d\n", getFormattedDate(sdf), name, countDownLatch.getCount());
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
        
        private String getFormattedDate(SimpleDateFormat sdf) {
            return sdf.format(new Date());
        }
        
        private int getRandomWaitTime() {
            return (int) ((Math.random() + 1) * 1000);
        }
        
    }
}

CyclicBarrier can be used to create a set of Children Threads if the size of the Threads created is known forehand. CyclicBarrier can be used to implement waiting amongst Children Threads until all of them finish. This is useful where parallel threads needs to perform a job which requires sequential execution. For example 10 Threads doing steps 1, 2, 3, but all 10 Threads should finish step one before any can do step 2. Cyclic barrier can be reset after all Threads are finished execution. This is a distinguishing feature from a CountDownLatch. A CountDownLatch can only be used for a single count down. Additionally a CyclicBarrier can be assigned an Additional Thread which executes each time all the Children Threads finish their respective tasks.

Practical Example : Processing of a Image Pixels Matrix row by row in the first step and in the second step saving the Pixel values to file row by row. In this scenario if there are 10 Threads running simultaneously to process the matrix row by row then all 10 should wait until all are finished before they move on to the next step which is saving those rows to file.


import java.util.concurrent.*;
import java.util.*;
import java.text.*;
/**
 * @author Shazin Sadakath
 *
 */
public class CyclicBarrierTest {
    private static final int MAX_THREADS = 5;

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(MAX_THREADS, new Runnable() {
            private int count = 1;
        
            public void run() {
                System.out.printf("Cyclic Barrier Finished %d\n", count++);
            }
        });
    
        System.out.println("Spawning Threads");
        for(int i=0;i<MAX_THREADS;i++) {
            Thread t = new Thread(new WorkerThread(cyclicBarrier, String.format("Thread-%d", i)));
            t.start();
        }
        System.out.println("Spawning Finished");
    }
    
    private static class WorkerThread implements Runnable {
        private CyclicBarrier cyclicBarrier;
        
        private String name;
        
        public WorkerThread(CyclicBarrier cyclicBarrier, String name) {
            this.name = name;
            this.cyclicBarrier = cyclicBarrier;
        }
        
        public void run() {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");                
                System.out.printf("%s : Doing Step 1 Work on %s\n", getFormattedDate(sdf), name);
                Thread.sleep(getRandomWaitTime());
                System.out.printf("%s : Doing Step 1 more work on %s\n", getFormattedDate(sdf), name);
                Thread.sleep(getRandomWaitTime());
                System.out.printf("%s : Finished Step 1 work on %s\n", getFormattedDate(sdf), name);
                int count = cyclicBarrier.await(); // Await returns an int which is the arrival index 1 means first 0 means last
                System.out.printf("%s : Cyclic Barrier count on %s is %d\n", getFormattedDate(sdf), name, count);
                if(count == 0) {
                    cyclicBarrier.reset();
                }
                System.out.printf("%s : Doing Step 2 Batch of Work on %s\n", getFormattedDate(sdf), name);
                Thread.sleep(getRandomWaitTime());
                System.out.printf("%s : Doing Some more Step 2 Batch of work on %s\n", getFormattedDate(sdf), name);
                Thread.sleep(getRandomWaitTime());
                System.out.printf("%s : Finished Step 2 Batch of work on %s\n", getFormattedDate(sdf), name);
                count = cyclicBarrier.await();
                System.out.printf("%s : Cyclic Barrier count end of Step 2 Batch of work on %s is %d\n", getFormattedDate(sdf), name, count);
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
        
        private String getFormattedDate(SimpleDateFormat sdf) {
            return sdf.format(new Date());
        }
        
        private int getRandomWaitTime() {
            return (int) ((Math.random() + 1) * 1000);
        }
        
    }
}



Semaphore can be used to create a set of Children Threads even when the size of the Threads to be created is not known fore hand. This is because a Semaphore can wait until a number of releases have been made but that number is not required to initialize the Semaphore. Semaphores can be used in other scenarios such as Synchronizing between different threads such as Publisher, Subscriber scenario.

Practical Example : Traversing through a folder with sub folders within sub folders and if  JPEG files are found, move them to a destination directory and then zip them. In this scenario the folder traversing is done recursively until a JPEG file is found. And then a Thread is invoked to move it to destination directory. But zipping needs to wait until all JPEG files are moved to the destination directory. In this scenario no of JPEG files available in the folder structure is not known but the zipping needs to wait till all files are successfully moved. Ideal scenario for a Semaphore based waiting.

import java.util.concurrent.*;
import java.util.*;
import java.text.*;
/**
 * @author Shazin Sadakath
 *
 */
public class SemaphoreTest {
    private static final int MAX_THREADS = 5;

    public static void main(String[] args) throws Exception {
        Semaphore semaphore = new Semaphore(0);

        System.out.println("Spawning Threads");
        int threadCount = 0;
        Random random = new Random();
        for(int i=0;i<MAX_THREADS;i++) {
            // Threads created will not always be MAX_THREADS
            // Because Threads are created only if Random no is Even.
            // Thus the No of Threads unknown at Semaphore Initialization
            if(random.nextInt(9999) % 2 == 0) {
                Thread t = new Thread(new WorkerThread(semaphore, String.format("Thread-%d", i)));
                t.start();
                threadCount++;
            }
        }
        System.out.println("Spawning Finished");
        System.out.println("Waiting All Threads to Finish");
        semaphore.acquire(threadCount); 
        System.out.println("All Threads are Finished");
    }
    
    private static class WorkerThread implements Runnable {
        private Semaphore semaphore;
        
        private String name;
        
        public WorkerThread(Semaphore semaphore, String name) {
            this.name = name;
            this.semaphore = semaphore;
        }
        
        public void run() {
            try {                
                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");                
                System.out.printf("%s : Doing Some Work on %s\n", getFormattedDate(sdf), name);
                Thread.sleep(getRandomWaitTime());
                System.out.printf("%s : Doing Some more work on %s\n", getFormattedDate(sdf), name);
                Thread.sleep(getRandomWaitTime());
                System.out.printf("%s : Finished work on %s\n", getFormattedDate(sdf), name);
                semaphore.release();                
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
        
        private String getFormattedDate(SimpleDateFormat sdf) {
            return sdf.format(new Date());
        }
        
        private int getRandomWaitTime() {
            return (int) ((Math.random() + 1) * 1000);
        }
        
    }
}
In conclusion, Each task has its separate unique use and it is Software Engineer's responsibility to understand which one is more suitable for the scenario they have to solve. In my case however CountDownLatch was the ideal one and I used it with pretty much success. It is advised to use these classes instead of trying to implement similar behavior on our own because they are developed and tested by Sun Microsystems expert Engineers.

Sunday, November 27, 2011

Java Source Code Hiding

I was thinking of a way to hide complex algorithms in source code and it turns out that Java Compiler can compile source code with unicode code character encoding. So for instance a typical HelloWorld class like this
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
 
Can be written as

\u0070\u0075\u0062\u006C\u0069\u0063\u0020\u0063\u006C\u0061\u0073\u0073\u0020\u0048\u0065\u006C\u006C\u006F\u0057\u006F\u0072\u006C\u0064\u0020\u007B\u0009\u0070\u0075\u0062\u006C\u0069\u0063\u0020\u0073\u0074\u0061\u0074\u0069\u0063\u0020\u0076\u006F\u0069\u0064\u0020\u006D\u0061\u0069\u006E\u0028\u0053\u0074\u0072\u0069\u006E\u0067\u005B\u005D\u0020\u0061\u0072\u0067\u0073\u0029\u0020\u007B\u0009\u0009\u0053\u0079\u0073\u0074\u0065\u006D\u002E\u006F\u0075\u0074\u002E\u0070\u0072\u0069\u006E\u0074\u006C\u006E\u0028\u0022\u0048\u0065\u006C\u006C\u006F\u002C\u0020\u0057\u006F\u0072\u006C\u0064\u0021\u0022\u0029\u003B\u0009\u007D\u007D

And it would compile just fine using javac and will run and print Hello, World!. I wrote a small application which converts any java source file to Unicode encoding so that you can hide your source within your computer from people who have access.

import java.io.*;
/*
 * @author Shazin Sadakath
 */
public class JavaUnicodeEncoding {
    public static void main(String[] args) throws Exception {
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new FileReader(args[0]));
            bw = new BufferedWriter(new FileWriter(args[1]));
            String line = null;
            while((line = br.readLine()) != null) {
                for(char c:line.toCharArray()) {
                    bw.write(String.format("\\u%04X",(int) c));
                }
                bw.flush();
            }
        } catch(ArrayIndexOutOfBoundsException e) {
            usage();
        } catch(Exception e) {
            System.err.println(e.getMessage());
        } finally {
            if(br != null) {
                br.close();
            }
            
            if(bw != null) {
                bw.close();
            }
        }
    }
    
    private static void usage() {
        System.out.println("java JavaUnicodeEncoding <input class filename /> <output class filename/>");
    }
}
You can even use the two interchangeably also
public class HelloWorld {
    public static void main(String[] args) {
        \u0053\u0079\u0073\u0074\u0065\u006D\u002E\u006F\u0075\u0074\u002E\u0070\u0072\u0069\u006E\u0074\u006C\u006E\u0028\u0022\u0048\u0065\u006C\u006C\u006F\u002C\u0020\u0057\u006F\u0072\u006C\u0064\u0021\u0022\u0029\u003B
    }
}

Thursday, November 24, 2011

DOS Batch File to Periodically Copy Files to a Location

During a Testing I had to do at my workplace I had to copy files to an input location at a random time so that there would be a constant supply of input files. I did some googling and found out several commands and integrated those together to create a batch file which can do that. The waiting is done using a ping command with a timeout. The timeout is taken from the system environment variable RANDOM so that it pauses for a random amount of time before copying files. After copying files I do a clean up on output files so that the storage is not spiked.

:again

SET COPYCMD=/Y

ping 123.45.67.89 -n 1 -w %RANDOM% > nul

xcopy <Source Folder with Files>\* <Destination Folder with Files> /s 

del /q <Folder Where Files to be Deleted Available>\*

goto again


COPYCMD Environment Variable is used to Enable overwriting of existing files without prompting.

Saturday, November 19, 2011

Arduino Google Voice Activated Servo Motor Controlling using Android

I was having some free time and wanted to put learn Android development. I found a Great Android Application called SL4A (Scripting Layer for Android) which is an intermediate Android app which sits between the Android OS native methods and popular scripting languages such as Shell Script, Python, Perl etc.

It opens up many possibilities to develop applications in Android really quickly with interpreted languages like Python. I always wanted to try out Door unlocking with an Android Google Voice API. For this system I wanted to connect to Wifi network and given the Voice command open or close a Door lock. So I came up with the following Circuit using Arduino;

Things required to build the Prototype.

  1. One Arduino (Any model)
  2. A Breadboard
  3. A Servo Motor
  4. Two LEDs (Green and Red)
  5. Two 1K resistors for LEDs
  6. Jumper Cables
Using the above mentioned equipment I put up the following prototype. 


The Green LED is driven using Pin 2, The Red LED is driven using Pin 3 and the Servo motor is attached to Pin 9 (Analog Output with PWM).

Android phone I have is a Samsung Galaxy ACE with Android OS 2.3.3 Gingerbread. I installed SL4A and  Python for Android to enable Python Scripting in Android.

#=======================================
#=          Shazin Sadakath            =
#=======================================

import android
import socket
# Android API Object SL4A Specific
droid = android.Android();

# Hostname or IP
hostname = "192.168.1.65";
# Port
port = 10000;
data = "";
# Creating a UDP Socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);
# Connecting to Host (Usually not required since it is UDP)
s.connect((hostname,port));
print "Connected!";

exit = False;
while not exit:
  # Using Android API for Google Voice and Recognizing command
  data = droid.recognizeSpeech().result;
  # Command is open or close proceding it to the Server else Error message
  if data == "open" or data == "close":
    # Sending command
    s.sendto(data,(hostname,port));
    # Recieving an ACK since UDP is unreliable 
    data = s.recvfrom(1024);    
    print "Ack ", data[0];
    # If ACK is success ending the program
    if data[0] == "success":
      exit = True;
  else:
    print "Invalid Command";
   

The Middle Man in this application is a Java Thread based UDP Server which listens for UDP packets from a connected Android app and Does the Serial communication to the Arduino Microcontroller.

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Shazin Sadakath
 */
public class SpeechDoor implements Runnable {
    private DatagramSocket socket;

    public SpeechDoor() {
        try {
            ArduinoBridge.init("COM27");
            socket = new DatagramSocket(10000);
            new Thread(this).start();
        } catch (SocketException ex) {
            Logger.getLogger(SpeechDoor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void run() {
        byte[] data;
        boolean success;
        DatagramPacket recv, ack;
        while (true) {
            try {
                data = new byte[1024];
                success = false;
                recv = new DatagramPacket(data, data.length);
                System.out.printf("Waiting on Socket : %s:%d\n", socket.getLocalAddress().toString(), socket.getPort());
                socket.receive(recv);
                System.out.printf("Packet Recieved From : %s:%d\n", recv.getAddress().toString(), recv.getPort());
                String value = new String(data, recv.getOffset(), recv.getLength());
                System.out.printf("Value : %s\n", value);
                if("open".equals(value)) {
                    ArduinoBridge.writeToArduino((byte) 1);
                    success = true;
                } else if("close".equals(value)) {
                    ArduinoBridge.writeToArduino((byte) 2);
                    success = true;
                }
                if(success) {
                    data = "success".getBytes();                    
                } else {
                    data = "fail".getBytes();
                }
                ack = new DatagramPacket(data, data.length, recv.getAddress(), recv.getPort());
                socket.send(ack);
                success = false;
                Thread.sleep(1000);
            } catch (Exception ex) {
                Logger.getLogger(SpeechDoor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void main(String[] args) {
        new SpeechDoor();
    }
}


Arduino Serial Communication is done using the RXTX Library for Serial Communication.


import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.OutputStream;
import java.util.Enumeration;

/**
 *
 * @author Shazin Sadakath
 */
public class ArduinoBridge {

    private static SerialPort port = null;
    private static CommPortIdentifier cpi = null;

    public static void init(String p) {
        Enumeration enums = CommPortIdentifier.getPortIdentifiers();

        while (enums.hasMoreElements()) {
            cpi = (CommPortIdentifier) enums.nextElement();
            if (p.equals(cpi.getName())) {
                break;
            }
        }

        if (cpi != null) {
            try {
                port = (SerialPort) cpi.open("ArduinoJavaBridge", 1000);
                if (port != null) {
                    port.setSerialPortParams(9600,
                            SerialPort.DATABITS_8,
                            SerialPort.STOPBITS_1,
                            SerialPort.PARITY_NONE);
                }

                System.out.println("Ready!");
                //new Thread(new ArduinoBridge()).start();

            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    }

    public static void writeToArduino(byte value) {
        try {
            
            OutputStream os = null;

            os = port.getOutputStream();
            
            os.write((byte) 0xff);
            os.write((byte) (value));
            os.flush();        

            if (os != null) {
                os.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

   
}


Finally the Arduino Sketch which is Loaded in to the Microcontroller


/* 
 * Shazin Sadakath
*/

#include <Servo.h>
#define MAX 150
#define MIN 0

int greenLedPin = 2;
int redLedPin = 3;
int servoPin = 9;
int command = 0;
boolean open = false;

Servo doorLock;

void setup() {
 Serial.begin(9600);
 doorLock.attach(9);
 pinMode(greenLedPin, OUTPUT);
 pinMode(redLedPin, OUTPUT);
 digitalWrite(greenLedPin, LOW);
 digitalWrite(redLedPin, HIGH);
}

void loop() {
 if(Serial.available() >= 2) {
  if(Serial.read() == 0xff) {
    command = Serial.read();
      if(command == 1) {
        if(!open) {
         doorLock.write(MAX); 
         digitalWrite(redLedPin, LOW);
         digitalWrite(greenLedPin, HIGH);
         open = true;
        }
      } else if(command == 2) {
        if(open) {
         doorLock.write(MIN);
         digitalWrite(greenLedPin, LOW);
         digitalWrite(redLedPin, HIGH);
         open = false;
      } 
     }     
  }  
 }  
 delay(10);
}

The video of the System is below. The accuracy completely depends on the way you pronounce the words "open" and "close", Surrounding noise and Google Voice API. In this video as you can see the The "open" word is not recognized first time. But the close word is.



Constructive Criticism is always welcome!

Trackbacks/Pings
  1. An Exercise in Servo Voice Control with Android - Hackaday 
  2. A Voice Activated Servo - SL4A Tutorials  

Saturday, November 12, 2011

Arduino Interrupt based LED with Toggle Button

I have been quit for sometime in my blog due to some work I had at work place. Got the time to work on Arduino Interrupts today and managed to put a small sketch on Arduino based Interrupts. Interrupts are a really powerful concept in hardware as well as in software. Specially in hardware, Interrupt eliminates polling saving precious processing cycles.

An interrupt is a Sporadic event which occurs asynchronously. For instance while reading a socket for data we can either Read that socket Periodically to see whether there is any data to be read or we can attach an ISR (Interrupt Service Routine) for that socket. Whenever there is data available in the socket buffer the ISR will be called asynchronously and the main program will be stopped executing. When the ISR is finished executing the main program will execute from where it stopped. This is called Context Switching.

Arduino UNO has two pins for External Interrupt handing INT0 (attached to pin 2) and INT1 (attached to pin 3). What I have tried to accomplish is without periodically reading pin 2 for a High value using Processing Cycles. Whenever there is FALLING (High to Low) in pin 2 a predefined ISR to be called which basically checks the state and does the opposite.

The circuit sketch looks as the following 



The Arduino Sketch for the program is as below. I have used INT0 with pin 2 for interrupt signal. As you can see the loop method doesn't do any polling on the value of pin 2. And I have used pin 10 for LED Output.

int pin = 10;
volatile int state = LOW;

void setup()
{
  pinMode(pin, OUTPUT);
  digitalWrite(2, HIGH);
  attachInterrupt(0, toggle, FALLING); // Attaching the ISR to INT0
}

void loop()
{
  // Does Nothing
}

// Interrupt Service Routine
void toggle()
{
  if(state == LOW) {
    state = HIGH;
  } else {
    state = LOW; 
  }
  digitalWrite(pin, state);
}

Tuesday, October 11, 2011

Ambient Lighting using an RGB LED and Arduino UNO

I had some spare time today and managed to put up an ambient lighting using a single RGB LED and an Arduino UNO Micro controller.

There are many implementations of Arduino Ambient light setups like

http://siliconrepublic.blogspot.com/2011/02/arduino-based-pc-ambient-lighting.html


The above implementation is a really cool one which uses a +RGB LED Strip to create the ambient light effect from the PC's averaged screen color.

But sadly I didn't have a RGB LED Strip but only one RGB LED. So I tried to create the ambient light effect using the single RGB LED. So the setup is as following








The RGB LED is a common anode (positive) one so the 5v is connected to the common anode via a 1k resistor. And I use pin 9, 10, 11 with Pulse Width Modulation (PWM) for Blue, Green and Red cathodes (negative) respectively.  I drive the PWM pins using the Arduino analogWrite(). But since the RGB pins are cathodes it negates the driving value. Meaning if I give a high value (255) it will dim the corresponding color and if I give a low value (0) it will increase the brightness of the corresponding color.

Sketch Code for Arduino UNO


int bluePin = 9;
int greenPin = 10;
int redPin = 11;
int blueBrightness = 0;
int greenBrightness = 0;
int redBrightness = 0;

void setup() {
  // Setting Up the COM Port
  Serial.begin(9600);
  // Changing PIN modes to OUTPUT
  pinMode(bluePin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(redPin, OUTPUT);
}

void loop() {
  if(Serial.available() >= 4) {
   if(Serial.read() == 0xff) {
    // 0, 0, 0 is Black
    // 255, 255, 255 is White
    redBrightness = Serial.read();
    greenBrightness = Serial.read();
    blueBrightness = Serial.read();
   } 
  }
  
  /*
   Since the RGB LED has cathode pins for 
   RGB we need to deduct value from 255 
   meaning if the brightness is 255 from the 
   PC for a color we need to give 0 so that it
   will eluminate brightly
  */
  analogWrite(bluePin, 255 - blueBrightness);
  analogWrite(greenPin, 255 - greenBrightness);
  analogWrite(redPin, 255 - redBrightness);
  delay(10); 
}



In order to capture the Screen Averaged color I used the implementation from the above mentioned post yet I used Java instead of Processing because I am familiar with it. I used RXTX Library for COM port writing.

The Java Code is below


package com.shazin.ambientrgb;

/**
 *
 * @author Shazin Sadakath
 */
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.awt.AWTException;
import java.awt.Robot; 
import java.awt.image.BufferedImage;
import java.awt.Rectangle;
import java.awt.Dimension;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AmbientRGB implements Runnable {

    private static Robot robot; 
    private static SerialPort port = null;
    private static CommPortIdentifier cpi = null;

    public static void main(String[] args) throws AWTException {
        Enumeration enums = CommPortIdentifier.getPortIdentifiers();
        robot = new Robot();
        while (enums.hasMoreElements()) {
            cpi = (CommPortIdentifier) enums.nextElement();
            if ("COM27".equals(cpi.getName())) {
                break;
            }
        }

        if (cpi != null) {
            try {
                port = (SerialPort) cpi.open("ArduinoJavaBridge", 1000);
                if (port != null) {
                    port.setSerialPortParams(9600,
                            SerialPort.DATABITS_8,
                            SerialPort.STOPBITS_1,
                            SerialPort.PARITY_NONE);
                }

                System.out.println("Ready!");
                new Thread(new AmbientRGB()).start();

            } catch (Exception e) {
                Logger.getLogger(AmbientRGB.class.getName()).log(Level.SEVERE, null, e);
            }


        }
    }

    public void run() {
        OutputStream os = null;
        try {
            os = port.getOutputStream();
        } catch (IOException ex) {
            Logger.getLogger(AmbientRGB.class.getName()).log(Level.SEVERE, null, ex);
        }
        while (true && os != null) {
            int pixel;
            float r = 0;
            float g = 0;
            float b = 0;

            Rectangle rectangle = new Rectangle(new Dimension(1366, 768));
            BufferedImage screenshot = robot.createScreenCapture(rectangle);


            int i = 0;
            int j = 0;

            for (i = 0; i < rectangle.getWidth(); i = i + 2) {
                for (j = 0; j < rectangle.getHeight(); j = j + 2) {
                    pixel = screenshot.getRGB(i, j); 
                    r = r + (int) (255 & (pixel >> 16)); 
                    g = g + (int) (255 & (pixel >> 8)); 
                    b = b + (int) (255 & (pixel)); 
                }
            }
            int totalPixels = (683 * 384); 
            r = r / totalPixels; 
            g = g / totalPixels; 
            b = b / totalPixels;


            try {

                os.write(0xff); 
                os.write((byte) (r)); 
                os.write((byte) (g)); 
                os.write((byte) (b)); 
                os.flush();
                Thread.sleep(10);
            } catch (Exception ex) {
                Logger.getLogger(AmbientRGB.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }
}


I used a White Paper Scroll to cover the RGB LED so that the light is evenly visible.