Sunday, June 1, 2014

Room temperatuer logger using arduino and JAVA


 This post is all about a temperature logger module using two sensors(LM35) and uses serial communication to log data to MySQL server. And it does so by using Arduino at the logger end and JAVA at the server.

  The concept is so simple that the Arduino uses LM35 (providing analog output for measured temperature) ,which is connected to one of the analogIn pin of Arduino. The sketch burned to Arduino converts the read value from the pin to corresponding temperature. And it sends the data through the serial port.

  At PC side a JAVA application runs which uses TxRx library for communicating with the serial port. The application reads the data from the serial port and acknowledged to Arduino. It then saves the red data to a database.

LM35Logger.ino
#include <LiquidCrystal.h>

LiquidCrystal lcd(2,3,4,5,11,12);

float temp_R=0;

float temp_Pi=0;

int tempPinR = 0;

int tempPinPi = 1;

void setup()

{

  lcd.begin(16, 2);

  pinMode(9, OUTPUT);

  Serial.begin(9600);

  analogReference(INTERNAL);

}

void loop()

{

  temp_R = analogRead(tempPinR);

  temp_Pi = analogRead(tempPinPi);

  temp_R = temp_R *0.107421875;

  temp_Pi = temp_Pi *0.107421875;

 

  Serial.print("TEMPRATURE = ");

  Serial.print(temp_R);

  Serial.print("*C");

  Serial.println();

  lcd.clear();

  String content = "";

  char character;



  while(Serial.available())

   {

      character = Serial.read();

      content.concat(character);

   }

   if(temp_Pi>36)

   {

     digitalWrite(9, HIGH);

   }

   else

   {

     digitalWrite(9, LOW);

   }

  lcd.print(content);

  lcd.setCursor(0,1);

  lcd.print("R:");

  lcd.setCursor(2,1);

  lcd.print(temp_R); 

  lcd.setCursor(8,1);

  lcd.print("Pi:");

  lcd.setCursor(11,1);

  lcd.print(temp_Pi);

  delay(3000);

}

LM35Logger.java

package com.oksbwn.Arduino;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.OutputStream;



import gnu.io.CommPortIdentifier;

import gnu.io.SerialPort;

import gnu.io.SerialPortEvent;

import gnu.io.SerialPortEventListener;



import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Enumeration;



public class SerialTest implements SerialPortEventListener

{

 int i;

 SerialPort serialPort;

 String trmp;

 DateFormat DateF = new SimpleDateFormat("dd/MMM/yyyy");

 DateFormat TimeF = new SimpleDateFormat("HH:mm");

 DateFormat TimeM = new SimpleDateFormat("mm");

 private static final String PORT_NAMES[] ={"/dev/tty.usbserial-A9007UX1","/dev/ttyACM0","/dev/ttyUSB0","COM7",};

 private BufferedReader input;

 private OutputStream output;

 private static final int TIME_OUT = 2000;

 private static final int DATA_RATE = 9600;



 public void initialize()

  { Enumeration<?> ports = CommPortIdentifier.getPortIdentifiers();



        CommPortIdentifier portId = null;

        while (ports.hasMoreElements())

         {

             CommPortIdentifier curPort = (CommPortIdentifier)ports.nextElement();

           for (String portName : PORT_NAMES)

       {

        if (curPort.getName().equals(portName))

         {

          portId = curPort;

          break;

         }

       }

         }

           if (portId == null)

             {

              return;

             }



try {

 // open serial port, and use class name for the appName.

serialPort = (SerialPort) portId.open(this.getClass().getName(),

  TIME_OUT);



// set port parameters

serialPort.setSerialPortParams(DATA_RATE,

  SerialPort.DATABITS_8,

  SerialPort.STOPBITS_1,

  SerialPort.PARITY_NONE);



// open the streams

input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));

output = serialPort.getOutputStream();



// add event listeners

  serialPort.addEventListener(this);

  serialPort.notifyOnDataAvailable(true);

 } catch (Exception e) {

  System.err.println(e.toString());

 }

}



/**

 * 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) {

  serialPort.removeEventListener();

  serialPort.close();

 }

}



/**

 * 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 {

            i++;

   String x = "ALBERTO";

    Class.forName("com.mysql.jdbc.Driver");

      Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/alberto","root","");

      ResultSet res=con.prepareStatement("SELECT * FROM `lcd_data`").executeQuery(); 

      if (res.next())

        {

       x=res.getString("Data");

        }

   String inputLine=input.readLine();

   Date dat = new Date();

   trmp=inputLine.substring(13,inputLine.length()-2); 

   if(TimeM.format(dat).charAt(1)=='7')

   con.prepareStatement("INSERT INTO `room_temperature` (`Sl_No`, `Temperature`, `Date`, `Time`) VALUES (NULL, '"+trmp+"', '"+DateF.format(dat)+"', '"+TimeF.format(dat)+"')").executeUpdate();

   con.close();

   output.write(x.getBytes());

  } catch (Exception e) {}

 }

 // Ignore all the other eventTypes, but you should consider the other ones.

}



public static void main(String[] args) throws Exception {

 SerialTest main = new SerialTest();

 main.initialize();

 Thread t=new Thread() {

  public void run() {

   //the following line will keep this app alive for 1000 seconds,

//waiting for events to occur and responding to them (printing incoming messages to console).

  try {Thread.sleep(1000000);} catch (InterruptedException ie) {}

 }

};

t.start();

System.out.println("Started");

 }

}