Archive

Archive for the ‘JAVA’ Category

Orange Pi Zero GPIO Programming using JAVA

April 19th, 2017 No comments

Orange Pi Zero GPIO ProgrammingThis is a simple tutorial on Orange Pi Zero GPIO Programming using JAVA. For this, I have used Pi4J library which also works with Raspberry Pi. This tutorial might help you to interact with GPIO in your IOT projects. In his tutorial, I have tested the application with LUBUNTU OS on Orange Pi Zero.

Links :
Install LUBUNTU on Orange Pi Zero
JAVA Applications on Orange Pi Zero

Github Repository: bit.ly/2oEkHDA

Connection Schematic: bit.ly/2oEBgzm
Website (Orange Pi Zero): bit.ly/2i4g9S0

Buy Orange Pi Zero: bit.ly/2ptMSoN

 

Read more…

IIC (I2C) Communication on Raspberry Pi by using JAVA

January 27th, 2017 No comments

IIC

This tutorial is all about IIC (I2C) communication on Raspberry Pi by using JAVA and for that, I have used Pi4J library. To demonstrate this in the tutorial I have used MCP23017 Port expander IC with Raspberry Pi. MCp23017 is a 16 Bit input/output Port Expander ICcomes with I2C Interface. To interact with the IC suing IIC (I2C) port  here we have used Pi4J and JAVA.

MCP23017 Features:
16-bit input/output port expander with interrupt output
Cascadable for up to 8 devices on one bus
25mA sink/source capability per I/O
Supports 100kHz, 400kHz, and 1.7MHz I2C™Compatible compatible modes

Read more…

Measure Distance using Ultrasonic Sensor HC – SR04 | Pi4J | JAVA | Raspberry Pi

January 16th, 2017 No comments

HC - SR04This is a simple tutorial showing how to interface HC – SR04  ultrasonic ranging module with Raspberry Pi to measure distance using JAVA. Ultrasonic ranging module HC – SR04 provides 2cm – 400cm non-contact measurement function, the ranging accuracy can reach to 3mm. The modules include ultrasonic transmitters, receiver and control circuit. The basic principle of work:

(1) Using IO trigger for at least 10us high-level signal,
(2) The Module automatically sends eight 40 kHz and detect whether there is a
pulse signal back.
(3) IF the signal back, through high level, time of high output IO duration is the time from sending ultrasonic to returning.
Read more…

Thermocouple Interfacing usng MAX31855 | Raspberry Pi

December 20th, 2016 No comments

thermocouple MAX31855Reading thermocouple data on Raspberry Pi using JAVA and Pi4J with the help of MAX31855 14 bit thermocouple to digital converter. The MAX31855 performs cold-junction compensation and digitizes the signal from a K-, J-, N-, T-, S-, R-, or E-type thermocouple. The data is output in a signed 14-bit, SPI-compatible, read-only format. This converter resolves temperatures to 0.25°C, allows readings as high as +1800°C and as low as -270°C, and exhibits thermocouple accuracy of ±2°C for temperatures ranging from -200°C to +700°C for K-type thermocouples.

Source : MAXIM Integrated(bit.ly/2i3GvZ4)

 

 

Read more…

CRC16 Calculator using JAVA

March 8th, 2016 No comments

           CRC codes are numerously used fro error checking purposes. So many times working around Embedded Devices you will find CRC used in different communication protocols. So guys here i have written a piece of code to generate CRC16 using provid
ed packets in JAVA.

CODE:

package crcCalculator;
public class calculateCrc16 {
long hb_CRC;
long lb_CRC;
public long getHCrc()// Returns High byte of CRC
{
return this.hb_CRC;
}
public long getLCrc()// Returns Low byte of CRC
{
return this.lb_CRC;
}
public static void main(String[] args)

{
char[] buf={(char)1,(char)4,(char)4,(char)0,(char)1,(char)46};// Packets for which //CRC is to be calculated
calculateCrc16 c16=new calculateCrc16();
c16.CalculateCRC16(buf);
System.out.println( c16.getHCrc()+" "+c16.getLCrc());
}
public void CalculateCRC16(char[] buf)
{
long crc = 0xFFFF;
for (int pos = 0; pos < buf.length; pos++) {
crc ^= (long)buf[pos];
for (int i = 8; i != 0; i--)
{
if ((crc & 0x0001) != 0)
{
crc >>= 1;
crc ^= 0xA001;
}
else 
            crc >>= 1;                    
}
}
lb_CRC= (crc & 65280)>>8;
hb_CRC= (crc & 255);
}
}
Categories: Calculator, CRC, CRC16, IOT, JAVA, MODBUS, oksbwn, weargenius Tags:

Send note as E-Mail from PC application using JAVA

January 12th, 2016 No comments
Hi guys. This is my first post using my home management system. Here i am going to post codes on making a simple app that can be used to send email with notes to your own mail. this comes handy when you are working on office or other PC and you want to save something interesting, In that scenario hopefully you will not be interested to open your mobile and get on typing. Hope this helps. But to use this you need to enable IMAP and POP in your mail settings.
** Make sure yo change your mail username and password in saveNote.java File.
From now on i will be providing codes on bitbucket only.

Categories: eNotes, JAVA, Notes, oksbwn, StickyNotes Tags:

External ADC with Raspberry Pi.

November 24th, 2014 No comments

           Really I tried a lot with MCP3208 external ADC to interface with the Raspberry pi. Searched for various codes but nothing was available in JAVA. So after some research i got some python code and modified that to JAVA.  in this i have used the Pi4J library.

/****
*Author : Bikash Narayan Panda
*Use : This is used to read ADC data foem the MCP3208 SPI based ADC.
*Date :19/Nov/2014
*Tags: Please Include the Pi4J Library.
*
*
**/
import java.io.IOException;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinPullResistance;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;

public class SensorTest {

    public static int readadc(int adcnum, GpioPinDigitalOutput clockpin,
            GpioPinDigitalOutput mosipin, GpioPinDigitalInput misopin,
            GpioPinDigitalOutput cspin, GpioController gpio) {
        if ((adcnum > 7) || (adcnum < 0))
            return -1;

        cspin.high();
        clockpin.low();
        cspin.low();

        int commandout = adcnum;
        commandout |= 0x18;
        commandout <<= 3;
        for (int i = 0; i < 5; i++) {
            if ((commandout & 0x80) != 0) {
                mosipin.high();
            }

            else {
                mosipin.low();
            }
            commandout <<= 1;
            clockpin.high();
            clockpin.low();
        }

        int adcout = 0;
        for (int i = 0; i < 14; i++) {
            clockpin.high();
            clockpin.low();
            adcout <<= 1;
            if (misopin.getState() == PinState.HIGH) {
                adcout |= 0x1;
            }

        }

        cspin.high();

        adcout >>= 1;
        return adcout;

    }

    public static void main(String[] args) throws InterruptedException,
            IOException {

        System.out.println("<--Pi4J--> GPIO Listen Example ... started.");

        // create gpio controller
        GpioController gpio = GpioFactory.getInstance();

        GpioPinDigitalOutput SPICLK = gpio.provisionDigitalOutputPin(
                RaspiPin.GPIO_14, "SPICLK", PinState.LOW);
        GpioPinDigitalInput SPIMISO = gpio.provisionDigitalInputPin(
                RaspiPin.GPIO_13, "SPIMISO", PinPullResistance.PULL_DOWN);
        GpioPinDigitalOutput SPIMOSI = gpio.provisionDigitalOutputPin(
                RaspiPin.GPIO_12, "SPIMOSI", PinState.LOW);
        GpioPinDigitalOutput SPICS = gpio.provisionDigitalOutputPin(
                RaspiPin.GPIO_11, "SPICS", PinState.LOW);


      
        for (int i=0;i <= 20;i++) {
            float value = readadc(0, SPICLK, SPIMOSI, SPIMISO, SPICS, gpio);
            System.out.println("sensor 0value= " + value);
            value = readadc(1, SPICLK, SPIMOSI, SPIMISO, SPICS, gpio);
            System.out.println("sensor 1value= " + value);
            Thread.sleep(500);
            value = readadc(2, SPICLK, SPIMOSI, SPIMISO, SPICS, gpio);
            System.out.println("sensor 2value= " + value);
            Thread.sleep(500);
            value = readadc(3, SPICLK, SPIMOSI, SPIMISO, SPICS, gpio);
            System.out.println("sensor3 value= " + value);
            Thread.sleep(500);
            value = readadc(4, SPICLK, SPIMOSI, SPIMISO, SPICS, gpio);
            System.out.println("sensor 4value= " + value);
            Thread.sleep(500);
            value = readadc(5, SPICLK, SPIMOSI, SPIMISO, SPICS, gpio);
            System.out.println("sensor 5value= " + value);
            Thread.sleep(500);
            value = readadc(6, SPICLK, SPIMOSI, SPIMISO, SPICS, gpio);
            System.out.println("sensor 6value= " + value);
            Thread.sleep(500);
            value = readadc(7, SPICLK, SPIMOSI, SPIMISO, SPICS, gpio);
            System.out.println("sensor7 value= " + value);
            Thread.sleep(500);
            Thread.sleep(500);
           
            Thread.sleep(500);
        }
      
      
        gpio.shutdown();

    }
}

 

Running particular application when Rspberry Pi boots up

August 8th, 2014 No comments
              While using Raspberry Pi you might not be interested to take  a mouse and keyboard to run certain application when the Pi reboots. To avoid this many procedures are available . In this post i have used crontab to run a JAVA based application each time the Pi reboots. Actually crontab provides many more features.

First login to your pi. Change yourself to root user. Command is 

sudo -s

After that to edit the crontab type
crontab -e
At the beginning of the file append 

@reboot /usr/bin/java -classpath /home/pi/:/home/pi/Desktop/DisplayOne_lib/*.jar -jar /home/pi/Desktop/DisplayOne.jar

Here the library and .jar file paths are provided as of the location of my application file.
Have a good day…

Run GUI based application on raspberry Pi Startup

August 7th, 2014 No comments

          Belief me i went through several websites and tested many proposals to run my JAVA based GUI application on Raspberry Pi start-up. Finally the following worked out

First check inside the .config folder if it contains autostart folder or not , if not then create a folder named as autostart.

Create a myApp.desktop file inside the autostart folder.The myApp.desktop file should contain the following

[Desktop Entry]

Encoding=UTF-8

Typr=Application

Name=nds

comment=

Exec=sudo /usr/bin/java -classpath /home/pi/:/home/pi/Desktop/Display_lib/*.jar -jar /home/pi/Desktop/Display.jar

StartupNotify=false

Terminal=false

Hidden=-false



Thats all reboot your pi and your application should run now….. You can also do that by following method.. edit rc.local file and put the code just befor the exit 0.

#sudo  /usr/bin/java -classpath /home/pi/:/home/pi/Desktop/Display_lib/*.jar -jar /home/pi/Deskt/Display.jar
Another thing is to run the GUI app continuously you also need to disable the default screen blackout. To do that just edit the rc.local file and put the following codes.

setterm -blank 0 -powerdown 0 -powersave off

Or edit the ~/.xinitrc file and put the following codes..

. /etc/X11/Xsession

xset s off

xset -dpms

xset s noblank

Pi Rocks…

setterm – terminal blanking

On a per session basis, you can run:
setterm -blank 0 -powerdown 0
This will set the timeout of your monitor to 0, which will prevent it from going to sleep.
If you get yelled at about permissions, try “sudo setterm” instead.
You might not want to enter these commands every time you boot up your Pi. In this case, open up your .bashrc file (or .extras or other custom file you might use).
nano ~/.bashrc
At the end of the file add a new line with the setterm command you entered before.
setterm -blank 0 -powerdown 0
Hit ctrl+x to exit, ‘y’ to save your changes and enter to save the file.
Note: the default value for the -blank option is 0 so it may be excluded
Now when you boot up, your monitor will never sleep.

kbd configuration – terminal blanking

Open up your configuration:
sudo nano /etc/kbd/config
Find the line for BLANK_TIME and POWERDOWN_TIME and set them to 0.
BLANK_TIME=0
POWERDOWN_TIME=0
If these lines doesn’t exist go ahead and add them.

lxde configuration – Xsession blanking

The previous methods should work for the terminal. This method should prevent your screen saver from coming on in the GUI.
Open up your lxde autostart file:
sudo nano /etc/xdg/lxsession/LXDE/autostart
If your Pi is newer, the file you’ll need to change may be:
sudo nano /etc/xdg/lxsession/LXDE-pi/autostart
Add these lines:
@xset s noblank
@xset s off
@xset -dpms

lightdm configuration – Xsession blanking

If adding those settings to your LXDE autostart didn’t work, this might help if you’re booting straight into the GUI.
Open your lightdm configuration:
sudo nano /etc/lightdm/lightdm.conf
Anywhere below the [SeatDefaults] header, add:
xserver-command=X -s 0 -dpms
This will set your blanking timeout to 0 a

sudo apt-get install x11-xserver-utils
  • now lets make a file to run on the start of X with settings
cd /home/pi 
touch .xinitrc
nano .xinitrc
  • Now you should edit .xinitrc and add these lines (disable ss, say no monitor timeout, set no blanking)
xset s off 
xset -dpms
xset s noblank

Room temperatuer logger using arduino and JAVA

June 1st, 2014 No comments

 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");

}

}
Categories: Arduino, bikash, c, JAVA, LM35, nist, oksbnw, temperature logger Tags: