Arduino First Project (PIR Java motion sensor)

As a computer science graduate I didn’t get a chance to build many projects that functions outside the computer, Locked within that dimension I was able to interface with reality only through people, as in I relied on people’s input rather than sensors. I decided to change that, using some wires, the serial port and the Arduino Uno unit.

My ardunio Equipment

I ordered it few days ago, along with two sensors PIR (analog motion sensor) and Heat and Humidity digital reader, between these two sensors I’m going to build several applications that reads things from the physical dimensions and log them or perhaps even take action based on them, In a later stage I’m planning to take it to the next level making my code commit physical actions based on certain on-line events (twitter, email, or even some nagios alarm).

Installing the Aurdio wasn’t an issue, it was too simplistic to even mention it here, same goes for writing my first sketch that reacted to the push of a button (they use the word sketch cause obvious computer engineers avoid using the word code). For my first project I decided to build a motion sensor that interacts with a java code, I had two challenges:

Challenge I Hooking up the parts:

I brought up the PIR page, it had 3 pins, 1 GND (ground), 1 Power 5v and 1 sensor, using the cables I was smart enough to order I hooked up the ground to the ground, the power to the power and the sensor bit to the input pin2, online there was that simple sketch that detects when the pin goes low and writes to the serial port, which I compiled on arduino IDE and uploaded to the device, soon enough the device was detecting movement, I created my first analog motion sensor.

int ledPin = 13;                // choose the pin for the LED
int inputPin = 2;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val = 0;                    // variable for reading the pin status

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input


void loop(){
  val = digitalRead(inputPin);  // read input value
  if (val == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
  } else {
    digitalWrite(ledPin, LOW); // turn LED OFF
    if (pirState == HIGH){
      // we have just turned of
      Serial.println("Motion ended!");
      // We only want to print on the output change, not state
      pirState = LOW;

Challenge II having my Java code read the output :

Slightly trickier, it included mainly getting one of the libraries available in the arduino installation folder (RXTXcomm.jar) also for some reason that’s beyond me to copy rxtxSerial.dll from the arduino installation folder to c:\windows\system32 folder, once that was done I had an application that could read my arduion’s output (which was connected on COM10.

package aurdino;

import java.util.Enumeration;

public class serial_test implements SerialPortEventListener {
	SerialPort serialPort;
        /** The port we're normally going to use. */
	private static final String PORT_NAMES[] = {
			"/dev/tty.usbserial-A9007UX1", // Mac OS X
			"/dev/ttyUSB0", // Linux
			"COM10", // Windows
	/** Buffered input stream from the port */
	private InputStream input;
	/** The output stream to the port */
	private OutputStream output;
	/** Milliseconds to block while waiting for port open */
	private static final int TIME_OUT = 2000;
	/** Default bits per second for COM port. */
	private static final int DATA_RATE = 9600;

	public void initialize() {
		CommPortIdentifier portId = null;
		Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

		// iterate through, looking for the port
		while (portEnum.hasMoreElements()) {
			CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
			for (String portName : PORT_NAMES) {
				if (currPortId.getName().equals(portName)) {
					portId = currPortId;

		if (portId == null) {
			System.out.println("Could not find COM port.");

		try {
			// open serial port, and use class name for the appName.
			serialPort = (SerialPort),

			// set port parameters

			// open the streams
			input = serialPort.getInputStream();
			output = serialPort.getOutputStream();

			// add event listeners
		} catch (Exception e) {
	 * This should be called when you stop using the port.
	 * This will prevent port locking on platforms like Linux.
	public synchronized void close() {
		if (serialPort != null) {

	 * Handle an event on the serial port. Read the data and print it.
	public synchronized void serialEvent(SerialPortEvent oEvent) {
		if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
			try {
				int available = input.available();
				byte chunk[] = new byte[available];, 0, available);

				// Displayed results are codepage dependent
				System.out.print(new String(chunk));
			} catch (Exception e) {
		// Ignore all the other eventTypes, but you should consider the other ones.

Magic happened and the java application was reading the output, an output that I now hookup to Nagios (since its analog) or have it tweeted or even go as far as having the arduino take action based on that (turn on the lights). I reckon its a lot simpler to build in shell script, however I chose Java since I have several  projects in mind.


Spent a couple of hours trying to get it to work from shell script, the main problem was the fact that i had to read from a live stream and detect a certain event that will only be available when i query for it, finally I decided to go java all the way, and that dear reader is why I usually prefer java to shell scripting, anyway right now I have this application that detects movement around my laptop and tweets it.


2 thoughts on “Arduino First Project (PIR Java motion sensor)

  1. hi
    am an undergrad wanted a JAVA code that writes to COM port because its proving to be a nightmare
    looking forward to you response
    thanx in advance
    kelvin wexa

  2. The code is mentioned in the post, the trickiest part was adding RXTXcomm.jar to the project.

    alternatively if you are using linux you can have arduino write its output to a file and read that file and wipe it clean using a separate thread.

    please check the code as well as the mentioned approach and tell me if you need any additional help.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s