ARDUINO DUE - JAVA ARAYÜZ PROGRAMLAMA

M. Turhan ÇOBAN

Burada ARDUINO DUEmikrodenetleyici kartını java arayüz programıyla nasıl kullanacağınızın örnekleri verilecektir. Javayla ARDUINO denetleyicinizi bağlamak için seri iletişimkanalını kullanmanız gerekir, bunun için ilk işlem java programlarının seri iletişim kurmasını sağlamaktır. Bu iletişimi oluşturacak programlara (RXTX)

http://fizzed.com/oss/rxtx-for-java

adresinden ulaşabilirsiniz.

Bu programlar c dilindedir, bu yüzden kendi bilgisayarınıza uygun olan alt setleri seçerek kullanmalısınız. Benim bilgisayarım 64 bit Windows kökenli olduğundan ben burada bundan bahsedeceğim. Windows 64 için bu siteden mfz-rxtx-2.2-20081207-win-x64.zip dosyası geldi. Bu dosyayı açtığımızda aşağıdaki programları göreceksiniz.

Listedeki RXTXcomm.jar dosyasını bilgisayarınızdaki java derleyicisini yerleştirdiğiniz dosya sisteminin altındaki jre\lib\ext dosyasına kaydetmelisiniz. rxtxSerial.dll dosyasını da bilgisayarınızdaki java derleyicisini yerleştirdiğiniz dosya sisteminin altındaki jre\bin dosyasına kaydetmelisiniz. Ayrıca ben burada mikrokontrol sisteminden aldığınız veriyi SQLite veri tabanına kaydederek kullanılmasından da bahsedeceğim. Bunun için de SQLite-java bağlantı programına ihtiyacınız olacak. Bu programı da https://bitbucket.org/xerial/sqlite-jdbc/downloads/

 

Adresinden edinebilirsiniz.

Bu adreste bulacağınız sqlite-jdbc-3.21.1.jar dosyasını da java derleyicisini yerleştirdiğiniz dosya sisteminin altındaki jre\lib\ext dosyasına kaydetmelisiniz. Bu prosesi otomatik yapmak için aşağıda verilen bat dosyasını kullanabilirsiniz.

RXTX.bat

SET JAVA_HOME=%1

copy sqlite-jdbc-3.16.1.jar %JAVA_HOME%\jre\lib\ext\

copy RXTXcomm.jar %JAVA_HOME%\jre\lib\ext\

copy rxtxSerial.dll %JAVA_HOME%\jre\bin\

 

Bu derlemede java 8 64 bit kullanıldığı varsayılmıştır. Java programını

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

adresinden indirebilirsiniz.

 

Burada değişik projeler üzerinden bu bağlantıları göstermeye çalışacağız. Arduino programlarını yazmak için bir editör ve yükleme programına ihtiyacınız olacak. Bu amaçla kullanabileceğiniz bir editör programını https://www.arduino.cc/en/Main/Software adresinde bulabilirsiniz.

Yapısal komutlar

·      setup()

·      loop()

Kontrol yapıları

·      if

·      if...else

·      for

·      switch case

·      while

·      do... while

·      break

·      continue

·      return

·      goto

diğer sintaxlar

·      ; (semicolon)

·      {} (curly braces)

·      // (single line comment)

·      /* */ (multi-line comment)

·      #define

·      #include

Arithmetic Operators

·      = (assignment operator)

·       (addition)

·      - (subtraction)

·      * (multiplication)

·      / (division)

·      % (modulo)

Karşılaştırma deyimleri

·      == (equal to)

·      != (not equal to)

·      < (less than)

·      > (greater than)

·      <= (less than or equal to)

·      >= (greater than or equal to)

Mantık operatörleri

·      && (and)

·      || (or)

·      ! (not)

Pointer (işaretçi) operatörleri

·      * dereference operator

·      & reference operator

Bit Operatörleri

·      & (bitwise and)

·      | (bitwise or)

·      ^ (bitwise xor)

·      ~ (bitwise not)

·      << (bitshift left)

·      >> (bitshift right)

Birleşik matematik operatörleri

·      ++ (increment)

·      -- (decrement)

·      += (compound addition)

·      -= (compound subtraction)

·      *= (compound multiplication)

·      /= (compound division)

·      %= (compound modulo)

·      &= (compound bitwise and)

·      |= (compound bitwise or)

DEĞİŞKENLER

Sabitler

·      HIGH | LOW

·      INPUT | OUTPUT | INPUT_PULLUP

·      LED_BUILTIN

·      true | false

·      integer constants

·      floating point constants

Veri tipleri

·      void

·      boolean

·      char

·      unsigned char

·      byte

·      int

·      unsigned int

·      word

·      long

·      unsigned long

·      short

·      float

·      double

·      string - char array

·      String - object

·      array

Dönüştürücüler

·      char()

·      byte()

·      int()

·      word()

·      long()

·      float()

değişken işaretleri

·      variable scope

·      static

·      volatile

·      const

Yardımcı metod ve değişken

·      sizeof()

·      PROGMEM

Fonksiyonlar

Dijital girdi/çıktı I/O

·      pinMode()

·      digitalWrite()

·      digitalRead()

Analog girdi/çıktı I/O

·      analogReference()

·      analogRead()

·      analogWrite() - PWM

Due & Zero only

·      analogReadResolution()

·      analogWriteResolution()

ileri girdi çıktı I/O

·      tone()

·      noTone()

·      shiftOut()

·      shiftIn()

·      pulseIn()

zaman

·      millis()

·      micros()

·      delay()

·      delayMicroseconds()

Matematik

·      min()

·      max()

·      abs()

·      constrain()

·      map()

·      pow()

·      sqrt()

Trigonometri

·      sin()

·      cos()

·      tan()

Karekterler

·      isAlphaNumeric()

·      isAlpha()

·      isAscii()

·      isWhitespace()

·      isControl()

·      isDigit()

·      isGraph()

·      isLowerCase()

·      isPrintable()

·      isPunct()

·      isSpace()

·      isUpperCase()

·      isHexadecimalDigit()

Tesadüfi sayılar

·      randomSeed()

·      random()

Bit ve baytlar

·      lowByte()

·      highByte()

·      bitRead()

·      bitWrite()

·      bitSet()

·      bitClear()

·      bit()

dış durdurma

·      attachInterrupt()

·      detachInterrupt()

durdurma

·      interrupts()

·      noInterrupts()

iletişim

·      Serial

·      Stream

USB (32u4 temelli devreler ve Due/Zero için)

·      Keyboard

·      Mouse

C/C++ temelli arduino programlama kodlarının detayları için

Editör programında ARDUINO DUE kartı otomatik olarak gelmemektedir. Bu kartı kütüphaneden programa yüklememiz gerekir.

Yüklememiz gereken Arduino SAM Boards(32-Bits ARM Cortex-M3) kartıdır.

İlk programımız monitor1

Bu programda sin(t/10) fonksiyonu (metodu) oluşturulmuştur. Fonksiyondaki t zamandır. Void loop() fonksiyonu(metodu) içersinde tanımlanan delay(1000) sonsuz döngünün 1000 mikrosaniye(1 saniye ) beklemesine sebep olmaktadır. Her seferinde de t değeri 1(saniye) arttırılmakta ve seri porta Serial.println metodu üzerinden f(t) fonksiyonu yazdırılmaktadır. Yazılan bu fonksiyonu editörün kendi Seri port çıktı penceresinden izleyebiliriz.

 

Buna paralel olarak çıktıyı grafik ekranında da görebiliriz.

Biz bunu javaya aktararak görmek istiyoruz. Seri kanal iletişimi açmak için önce bir küçük iletişim kanal açma programı oluşturalım. Bu program grafik ekranda arduino ile iletişim kuracak seri kanalı açacaktır.

import java.awt.BorderLayout;

import java.awt.Container;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.ItemEvent;

import java.awt.event.ItemListener;

import java.util.Enumeration;

import java.util.HashMap;

import gnu.io.CommPort;

import gnu.io.CommPortIdentifier;

import gnu.io.SerialPort;

import javax.swing.JButton;

import javax.swing.JComboBox;

import javax.swing.JDialog;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

 

/**

 * Choose a port, any port!

 *

 * Java Communications is a "standard extention" and must be downloaded and

 * installed separately from the JDK before you can even compile this program.

 *

 * @author Ian F. Darwin, http://www.darwinsys.com/

 * @version $Id: PortChooser.java,v 1.9 2004/04/11 23:50:40 ian Exp $

 * methods added by M. Turhan Coban 18.11.2011

*/

 

public class PortChooser extends JDialog implements ItemListener {

  /** A mapping from names to CommPortIdentifiers. */

  protected HashMap map = new HashMap();

 

  /** The name of the choice the user made. */

  protected String selectedPortName;

 

  /** The CommPortIdentifier the user chose. */

  protected CommPortIdentifier selectedPortIdentifier;

 

  /** The JComboBox for serial ports */

  protected JComboBox serialPortsChoice;

 

  /** The JComboBox for parallel ports */

  protected JComboBox parallelPortsChoice;

 

  /** The JComboBox for anything else */

  protected JComboBox other;

 

  /** The SerialPort object */

  protected SerialPort ttya;

 

  /** To display the chosen */

  protected JLabel choice;

 

  /** Padding in the GUI */

  protected final int PAD = 5;

 

  /**

   * This will be called from either of the JComboBoxen when the user selects

   * any given item.

   */

  public void itemStateChanged(ItemEvent e) {

    // Get the name

    selectedPortName = (String) ((JComboBox) e.getSource())

        .getSelectedItem();

    // Get the given CommPortIdentifier

    selectedPortIdentifier = (CommPortIdentifier) map.get(selectedPortName);

    // Display the name.

    choice.setText(selectedPortName);

  }

 

  /* The public "getter" to retrieve the chosen port by name. */

  public String getSelectedName() {

    return selectedPortName;

  }

 

  /* The public "getter" to retrieve the selection by CommPortIdentifier. */

  public CommPortIdentifier getSelectedIdentifier() {

    return selectedPortIdentifier;

  }

 

  /** A test program to show up this chooser. */

  public static void main(String[] ap) {

    PortChooser c = new PortChooser(null);

    c.setVisible(true); // blocking wait

    System.out.println("Seçtiğiniz kanal " + c.getSelectedName() + " (known by "

        + c.getSelectedIdentifier() + ").");

    System.exit(0);

  }

 

  public static CommPortIdentifier select_port(JFrame parent) {

    PortChooser c = new PortChooser(parent);

    c.setVisible(true); // blocking wait

    return c.getSelectedIdentifier();

  }

  /**

   * Construct a PortChooser --make the GUI and populate the ComboBoxes.

   */

  public PortChooser(JFrame parent) {

    super(parent, "Datalogger bağlantısı kanal seçici ", true);

    makeGUI();

    populate();

    finishGUI();

  }

 

  /**

   * Build the GUI. You can ignore this for now if you have not yet worked

   * through the GUI chapter. Your mileage may vary.

   */

  protected void makeGUI() {

    Container cp = getContentPane();

 

    JPanel centerPanel = new JPanel();

    cp.add(BorderLayout.CENTER, centerPanel);

 

    centerPanel.setLayout(new GridLayout(0, 2, PAD, PAD));

 

    centerPanel.add(new JLabel("seri bağlantılar ", JLabel.RIGHT));

    serialPortsChoice = new JComboBox();

    centerPanel.add(serialPortsChoice);

    serialPortsChoice.setEnabled(false);

 

    centerPanel.add(new JLabel("paralel bağlantılar ", JLabel.RIGHT));

    parallelPortsChoice = new JComboBox();

    centerPanel.add(parallelPortsChoice);

    parallelPortsChoice.setEnabled(false);

 

    centerPanel.add(new JLabel("Bilinmiyen bağlantılar", JLabel.RIGHT));

    other = new JComboBox();

    centerPanel.add(other);

    other.setEnabled(false);

 

    centerPanel.add(new JLabel("Sizin seçiminiz :", JLabel.RIGHT));

    centerPanel.add(choice = new JLabel());

 

    JButton okButton;

    cp.add(BorderLayout.SOUTH, okButton = new JButton("SEÇTİKTEN SONRA BASINIZ"));

    okButton.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        PortChooser.this.dispose();

      }

    });

 

  }

 

  /**

   * Populate the ComboBoxes by asking the Java Communications API what ports

   * it has. Since the initial information comes from a Properties file, it

   * may not exactly reflect your hardware.

   */

  protected void populate() {

    // get list of ports available on this particular computer,

    // by calling static method in CommPortIdentifier.

    Enumeration pList = CommPortIdentifier.getPortIdentifiers();

 

    // Process the list, putting serial and parallel into ComboBoxes

    while (pList.hasMoreElements()) {

      CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement();

      // System.out.println("Port " + cpi.getName());

      map.put(cpi.getName(), cpi);

      if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) {

        serialPortsChoice.setEnabled(true);

        serialPortsChoice.addItem(cpi.getName());

      } else if (cpi.getPortType() == CommPortIdentifier.PORT_PARALLEL) {

        parallelPortsChoice.setEnabled(true);

        parallelPortsChoice.addItem(cpi.getName());

      } else {

        other.setEnabled(true);

        other.addItem(cpi.getName());

      }

    }

    serialPortsChoice.setSelectedIndex(-1);

    parallelPortsChoice.setSelectedIndex(-1);

  }

 

  protected void finishGUI() {

    serialPortsChoice.addItemListener(this);

    parallelPortsChoice.addItemListener(this);

    other.addItemListener(this);

    pack();

    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

  }

}

 

Bunun ardından da ilk java Monitor programı ile ARDUINO’nun gönderdiği seri iletişimi okuyarak yazdıralım. Bu tür iletişim programları gerçek zaman programlarıdır. İletişim hızı olarak 19200 baud, veri olarak 8 bit iletişim,  durdurma biti olarak 1 değeri(STOPBITS_1) ve PARITY_NONE (PARITY_NONE PARITY_EVEN veya PARITY_ODD olabilir) değerleri direk olarak programın içinde atanmıştır.

 import java.io.*;

import java.util.*;

import gnu.io.CommPort;

import gnu.io.CommPortIdentifier;

import gnu.io.SerialPort;

import java.io.FileDescriptor;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.awt.*;

 

public class Monitor1 implements Runnable

{   private static final long serialVersionUID = 8257386587L;

                        public String s2="[\\x00-\\x20]*[+-]?(((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*";

    public Thread readThread;             // zaman içinde çal??ma de?i?keni

    public  CommPortIdentifier portId;    // seri baglant? kanal? numaras?

    public  SerialPort serialPort;        // seri kanal

    public  OutputStream outputStream;    // ç?kt? kanal?

    public  InputStream inputStream;      // girdi kanal?

    public  int sleep1;                   // readThread bekleme zaman? milisaniye

    //kontrol parametresi

   

    public Monitor1(String s)

    { portId=portId(s);

    System.out.println("portID is read");

      try { serialPort = (SerialPort)

            portId.open(s, 1000);

                    } catch (gnu.io.PortInUseException e) {}

                    try {

                        outputStream = serialPort.getOutputStream();

                        inputStream = serialPort.getInputStream();

                    } catch (IOException e) {}

                    try {

                        serialPort.setSerialPortParams(19200,

                            SerialPort.DATABITS_8,

                            SerialPort.STOPBITS_1,

                            SerialPort.PARITY_NONE);

                    } catch (gnu.io.UnsupportedCommOperationException e) {}

    }

    //seri iletişim kanalı açılması

    public  CommPortIdentifier portId(String s)

    {    portId = PortChooser.select_port(null);           

                    try {

                        serialPort = (SerialPort)

                            portId.open(s, 2000);

                    } catch (gnu.io.PortInUseException e) {}

    return portId;

    }

    public  void start()

    {readThread = new Thread(this);

    readThread.start();

    }

    public void run()

     { 

      int k=0;

                          while(true)

                          {                    

      try{

                          k++;                                  

      Thread.sleep(1000);

      try {     

                    byte[] readBuffer = new byte[30];

                    long[] readBuffer1 = new long[30];

                    byte numBytes = (byte)inputStream.read(readBuffer);

                    String s= new String(readBuffer);

                    s=s.trim();

                    double T1,T1old=0;

                    if(s.matches(s2))

                                        { 

                                                            T1=Double.parseDouble(s);

                                                            T1old=T1; 

                                                           }

                                        else

                                        {T1=T1old;}

                    int i=0;

                    for(i=0;i<numBytes;i++)

                    {  readBuffer1[i]=readBuffer[i]&0xFF;

                                      }

      //System.out.print(s);

      System.out.println("T1="+T1);

      } catch (IOException e) {}

      } catch (InterruptedException e) {System.out.println("InterruptedException 1");}

      }

      }

      public static void main(String arg[])

      { Monitor1 m=new Monitor1("ARDUNIO");

      m.start();}

}

 

 

---------- Capture Output ----------

> "D:\co\java\bin\javaw.exe" Monitor1

portID is read

T1=0.0

T1=0.2

T1=0.3

T1=0.39

T1=0.48

T1=0.56

T1=0.64

T1=0.72

T1=0.78

T1=0.84

T1=0.89

T1=0.93

T1=0.96

T1=0.99

T1=1.0

T1=1.0

T1=0.99

T1=0.97

T1=0.95

T1=0.91

T1=0.86

T1=0.81

T1=0.75

> Terminated with exit code 1.

 

Görüldüğü gibi burada da veri java programı üzerinden aktarılmaktadır. Programda girdi ve çıktı için 2 kanal açılmıştır.

                        outputStream = serialPort.getOutputStream();

                        inputStream = serialPort.getInputStream();

 

Programın sonsuz döngüsü while(true) deyimiyle sağlanmakta ve 1000 mikrosaniyelik bekleme süresi      Thread.sleep(1000); deyimiyle oluşturulmaktadır. Veri T1 değişkenine aktarıldıktan sonra System.out.println metodu ile yazdırılmaktadır.

 

Şimdi aynı ARDUINO verisinin çıktısını javada grafik formatında alalım. Bunun için ek olarak bir grafik programına ihtiyacımız olacak. Bu programın kodları da EKLER bölümünde verilmiştir (Grafik program kodları biraz uzun olduğundan)

Java program kodumuz:

import java.io.*;

import java.util.*;

import gnu.io.CommPort;

import gnu.io.CommPortIdentifier;

import gnu.io.SerialPort;

import java.io.FileDescriptor;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.awt.*;

//import java.sql.Connection;

//import java.sql.DriverManager;

//import java.sql.ResultSet;

//import java.sql.SQLException;

//import java.sql.Statement;

 

public class Monitor1A implements Runnable

{   String s2="[\\x00-\\x20]*[+-]?(((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*";             

                private static final long serialVersionUID = 8257386587L;

                public Thread readThread;             // zaman içinde çalışma değişkeni

    public  CommPortIdentifier portId;    // seri bağlantı kanalı numarası

    public  SerialPort serialPort;        // seri kanal

    public  OutputStream outputStream;    // çıktı kanalı

    public  InputStream inputStream;      // girdi kanalı

    public  int sleep1;                   // readThread bekleme zamanı milisaniye

    public tplot2D d3;

    //public dials d1;

    double T1,T1old;

    double ymin,ymax;

    //kontrol parametresi

    public String veritabani;

    public String veritablosu[];

    //public  Connection connection = null;

    //public  Statement statement;

        String zamanold,zamannew;

    //SQLite_Table tt;

    public  String veri[][];              // String formunda ç?kt? de?i?kenleri

    public Monitor1A(String s,String veritabanii,String veritablosui[],double ymini,double ymaxi)

    {  ymin=ymini;

       ymax=ymaxi;

                    veritabani=veritabanii;

        veritablosu=veritablosui;

                    portId=portId(s);

    System.out.println("portID is read");

      try { serialPort = (SerialPort)

            portId.open(s, 2000);

                    } catch ( gnu.io.PortInUseException e) {}

                    try {

                        outputStream = serialPort.getOutputStream();

                    } catch (IOException e) {}

                    try {

                        serialPort.setSerialPortParams(19200,

                            SerialPort.DATABITS_8,

                            SerialPort.STOPBITS_1,

                            SerialPort.PARITY_NONE);

                    } catch ( gnu.io.UnsupportedCommOperationException e) {}

 

                    timeplot();

}

 

    //seri ileti?im kanal? aç?lmas?

    public  CommPortIdentifier portId(String s)

    {    portId = PortChooser.select_port(null);           

                    try {

                        serialPort = (SerialPort)

                            portId.open(s, 2000);

                    } catch ( gnu.io.PortInUseException e) {}

    return portId;

    }

   

    public  void start()

    {readThread = new Thread(this);

    readThread.start();

    }

    public void run()

     {  int ix=0;

     int n=1;

      int k=0;

                  while(true)

                  {             

      try{

                  k++;                      

      Thread.sleep(1000);

      try {

      inputStream = serialPort.getInputStream();

                    byte[] readBuffer = new byte[30];

                    long[] readBuffer1 = new long[30];

                    byte numBytes = (byte)inputStream.read(readBuffer);

                    String s= new String(readBuffer, "US-ASCII");

                                if(s.matches(s2))

                                {T1=Double.parseDouble(s);}

                                else

                                {T1=T1old;}

                                double T2[]={T1};

                                //d1.setData(T2);

                                T1old=T1;

                                veri=new String[n][T2.length+4];

           veri[ix][0]=""+k;

           String zaman[]=zaman();

           veri[ix][1]=zaman[0];

           veri[ix][2]=zaman[1];

           double tt=zaman1(zaman[1]);

           zamannew=zaman[1];

           int cihaz_adresi[]={0};

           veri[ix][3]=""+cihaz_adresi[ix];

           veri[ix][4]=""+T2[0];

         zamanold=zamannew;

                      d3.setXY(tt,T2,ymin,ymax);         

                     System.out.print("T1="+T1);

      } catch (IOException e) {}

      } catch (InterruptedException e) {System.out.println("InterruptedException 1");}

      }

      }

      public double zaman1(String ss)

    {

     StringTokenizer token=new StringTokenizer(ss,":");

     int m=token.countTokens();

     String s1[]=new String[m];

     int j=0;          

     while(token.hasMoreTokens())

     { s1[j]=token.nextToken();j++;}

     double tt=Double.parseDouble(s1[0])*3600+Double.parseDouble(s1[1])*60+Double.parseDouble(s1[2]);

     return tt;

    }

 

    public  String[] zaman()

    {

                GregorianCalendar calendar;

                Date date=new Date();

                String[] ids = TimeZone.getAvailableIDs(+3 * 60 * 60 * 1000);

    SimpleTimeZone pdt = new SimpleTimeZone(+3 * 60 * 60 * 1000, ids[0]);

    calendar=new GregorianCalendar(pdt);

    calendar.setTime(date);

    String dt=""+calendar.get(Calendar.DATE);

    if (dt.length()==1) dt="0"+dt;

    String mo=""+(calendar.get(Calendar.MONTH)+1);

    if (mo.length()==1) mo="0"+mo;

    String Sdate=dt+"/"+mo+"/"+calendar.get(Calendar.YEAR);

    String ho=""+(calendar.get(Calendar.AM_PM)*12+calendar.get(Calendar.HOUR));

    if (ho.length()==1) ho="0"+ho;    

    String min=""+calendar.get(Calendar.MINUTE);

     if (min.length()==1) min="0"+min;

    String sec=""+calendar.get(Calendar.SECOND);

    if (sec.length()==1) sec="0"+sec;   

    String Stime=ho+":"+min+":"+sec+" ";

    String z[]={Sdate,Stime};

    return z;

                }

                                 //Database programs

                 public void createTable(int ix) throws ClassNotFoundException

                 { //  sqlite-JDBC sürücüsünü yükle

       //Class.forName("org.sqlite.JDBC");  

       //Connection connection = null;

       int kanalsayisi=1;  //just one channel reading

      

      }

    

public void dials()

{ double n1=Math.PI/2;

double n2=3.0*n1;

String st[]={" sine curve "};

double td[]={0};

double tmin=-1.0;

double tmax=1.0;

double tetamax=600;

double teta1_rad=Math.PI/4;

double teta2_rad=3.0*Math.PI/2.0+teta1_rad;

//d1=new dials("Arduino analog read","y=sin(t)",st,td,tmin,tmax,teta1_rad,teta2_rad);

//FrameGraphic.plot("ARDUINO Voltmetre ",d1);

}

//zamana bağlı grafik 

public void timeplot()

{ int nyi=1;

  int nquei=1200;

  String pl="ARDUINO time function plot";

  String xl="time second";

  String yl="y=f(t)";

  int xnt=10;

  int ynt=30;

  int xgr=0;

  int ygr=0;

  int ipti[]={5};

  Color ibg=Color.cyan;

  Color ifg[]={Color.black,Color.blue,Color.red,Color.black,Color.green,Color.cyan,Color.yellow,Color.black};

  d3=new tplot2D(nyi,nquei,pl,xl,yl,xnt,ynt,xgr,ygr,ipti,ibg,ifg);

  FrameGraphic.plot("Zaman Grafiği ",d3,1300,800);

}      

      public static void main(String arg[]) throws ClassNotFoundException

      { String veritabani="VT";

        String veritablosu[]={"VT1"};

        double ymin=-1.0;

        double ymax=1.0;

                      Monitor1A m=new Monitor1A("ARDUNIO",veritabani,veritablosu,ymin,ymax);

                      m.createTable(0);

       m.start();

       }

}

 

Program çıktısı:

 

Okuma değerlerinde bazı hatalar oluştuğunu da not edelim.

Bir sonraki programımızda okuduğumuz değerleri veri tabanı programına kaydediyoruz. Veri tabanı program dili olarak SQLite kullanacağız. Program kodu altta verilmiştir. Program SQLite_Table isimli ikinci bir program kullanmaktadır. Bu programın kodu da ekte verilmiştir.

 

import java.io.*;

import java.util.*;

import gnu.io.CommPort;

import gnu.io.CommPortIdentifier;

import gnu.io.SerialPort;

import java.io.FileDescriptor;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.awt.*;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

 

public class Monitor1B implements Runnable

{   String s2="[\\x00-\\x20]*[+-]?(((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*";             

                        private static final long serialVersionUID = 8257386587L;

                        public Thread readThread;             // zaman içinde çalışma değişkeni

    public  CommPortIdentifier portId;    // seri bağlantı kanalı numarası

    public  SerialPort serialPort;        // seri kanal

    public  OutputStream outputStream;    // çıktı kanalı

    public  InputStream inputStream;      // girdi kanalı

    public  int sleep1;                   // readThread bekleme zamanı milisaniye

    //public tplot2D d3;

    //public dials d1;

    double T1,T1old;

    double ymin,ymax;

    //kontrol parametresi

    public String veritabani;

    public String veritablosu[];

    public  Connection connection = null;

    public  Statement statement;

        String zamanold,zamannew;

    SQLite_Table tt;

    public  String veri[][];              // String formunda ç?kt? de?i?kenleri

    public Monitor1B(String s,String veritabanii,String veritablosui[],double ymini,double ymaxi)

    {  ymin=ymini;

       ymax=ymaxi;

                            veritabani=veritabanii;

        veritablosu=veritablosui;

                            portId=portId(s);

    System.out.println("portID is read");

      try { serialPort = (SerialPort)

            portId.open(s, 2000);

                    } catch ( gnu.io.PortInUseException e) {}

                    try {

                        outputStream = serialPort.getOutputStream();

                    } catch (IOException e) {}

                    try {

                        serialPort.setSerialPortParams(19200,

                            SerialPort.DATABITS_8,

                            SerialPort.STOPBITS_1,

                            SerialPort.PARITY_NONE);

                    } catch ( gnu.io.UnsupportedCommOperationException e) {}

 

                    dials();

                    listTable(0);

                    timeplot();

}

 

    //seri ileti?im kanal? aç?lmas?

    public  CommPortIdentifier portId(String s)

    {    portId = PortChooser.select_port(null);           

                    try {

                        serialPort = (SerialPort)

                            portId.open(s, 2000);

                    } catch ( gnu.io.PortInUseException e) {}

    return portId;

    }

   

    public  void start()

    {readThread = new Thread(this);

    readThread.start();

    }

    public void run()

     {  int ix=0;

     int n=1;

      int k=0;

                          while(true)

                          {                    

      try{

                          k++;                                  

      Thread.sleep(1000);

      try {

      inputStream = serialPort.getInputStream();

                    byte[] readBuffer = new byte[30];

                    long[] readBuffer1 = new long[30];

                    byte numBytes = (byte)inputStream.read(readBuffer);

                    String s= new String(readBuffer, "US-ASCII");

                                        if(s.matches(s2))

                                        {T1=Double.parseDouble(s);}

                                        else

                                        {T1=T1old;}

                                        double T2[]={T1};

                                        //d1.setData(T2);

                                        T1old=T1;

                                        veri=new String[n][T2.length+4];

           veri[ix][0]=""+k;

           String zaman[]=zaman();

           veri[ix][1]=zaman[0];

           veri[ix][2]=zaman[1];

           double tt=zaman1(zaman[1]);

           zamannew=zaman[1];

           int cihaz_adresi[]={0};

           veri[ix][3]=""+cihaz_adresi[ix];

           veri[ix][4]=""+T2[0];

           //System.out.print("k=   "+k+" "+zaman[0]+" "+zaman[1]+"cihaz = "+cihaz_adresi[ix]+" ");

           //for(int ii=0;i<T2.length;ii++)

           //     {System.out.print(" T["+ix+"]["+ii+"] ="+T2[ii]+" ");veri[ix][ii+4]=""+T2[ii];}

           //d1.setData(T2);

           String ss1="";   

           ss1+="insert into "+veritablosu[ix]+" values(";

           int ii=0;

           for(ii=0;ii<veri[ix].length-1;ii++) {ss1+="'"+veri[ix][ii]+"',";}

           ss1+="'"+veri[ix][ii]+"');";

           System.out.println(ss1);

           try{ writeTable(ss1);

              } catch(ClassNotFoundException e4) {System.out.println("Class not found");}

         zamanold=zamannew;

                              //d3.setXY(tt,T2,ymin,ymax);         

                                        

                                        //System.out.print("T1="+T1);

      } catch (IOException e) {}

      } catch (InterruptedException e) {System.out.println("InterruptedException 1");}

      }

      }

      public double zaman1(String ss)

    {

     StringTokenizer token=new StringTokenizer(ss,":");

     int m=token.countTokens();

     String s1[]=new String[m];

     int j=0;          

     while(token.hasMoreTokens())

     { s1[j]=token.nextToken();j++;}

     double tt=Double.parseDouble(s1[0])*3600+Double.parseDouble(s1[1])*60+Double.parseDouble(s1[2]);

     return tt;

    }

 

    public  String[] zaman()

    {

                        GregorianCalendar calendar;

                        Date date=new Date();

                        String[] ids = TimeZone.getAvailableIDs(+3 * 60 * 60 * 1000);

    SimpleTimeZone pdt = new SimpleTimeZone(+3 * 60 * 60 * 1000, ids[0]);

    calendar=new GregorianCalendar(pdt);

    calendar.setTime(date);

    String dt=""+calendar.get(Calendar.DATE);

    if (dt.length()==1) dt="0"+dt;

    String mo=""+(calendar.get(Calendar.MONTH)+1);

    if (mo.length()==1) mo="0"+mo;

    String Sdate=dt+"/"+mo+"/"+calendar.get(Calendar.YEAR);

    String ho=""+(calendar.get(Calendar.AM_PM)*12+calendar.get(Calendar.HOUR));

    if (ho.length()==1) ho="0"+ho;    

    String min=""+calendar.get(Calendar.MINUTE);

     if (min.length()==1) min="0"+min;

    String sec=""+calendar.get(Calendar.SECOND);

    if (sec.length()==1) sec="0"+sec;   

    String Stime=ho+":"+min+":"+sec+" ";

    String z[]={Sdate,Stime};

    return z;

                        }

                                              //Database programs

                         public void createTable(int ix) throws ClassNotFoundException

                         { //  sqlite-JDBC sürücüsünü yükle

       Class.forName("org.sqlite.JDBC");  

       Connection connection = null;

       int kanalsayisi=1;  //just one channel reading

       try

       {

      // veritaban? ile ba?lant? kur.

      connection = DriverManager.getConnection("jdbc:sqlite:"+veritabani+".db");

      statement = connection.createStatement();

      statement.setQueryTimeout(30);  // set timeout to 30 sec.     

      statement.executeUpdate("drop table if exists "+veritablosu[ix]+";");

      String ss="create table "+veritablosu[ix]+"(no String,tarih String,saat String,kanal String,";

      int i;

      for(i=0;i<kanalsayisi-1;i++) ss+="ch"+i+" String, ";

      ss+="ch"+i+" String);";

      statement.executeUpdate(ss);

      System.out.println("veritablosu = "+veritablosu[ix]);

      String ss1="select * from "+veritablosu[ix];

      //tt.setQuerry(ss1);

      }

      catch(SQLException e)

      {

      // if the error message is "out of memory",

      // it probably means no database file is found

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

    }

    finally

    {

      try

      {

        if(connection != null)

          connection.close();

      }

      catch(SQLException e)

      {

        // connection close failed.

        System.err.println(e);

      }

      }

      }

     public void writeTable(String querry) throws ClassNotFoundException

                         { //  sqlite-JDBC sürücüsünü yükle

       Class.forName("org.sqlite.JDBC");  

       Connection connection = null;

       try

       {

      // veritabanı ile bağlantı kur.

      connection = DriverManager.getConnection("jdbc:sqlite:"+veritabani+".db");

      Statement statement = connection.createStatement();

      statement.setQueryTimeout(30);  // set timeout to 30 sec.     

      statement.executeUpdate(querry);

      }

      catch(SQLException e)

      {

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

    }

    finally

    {

      try

      {

        if(connection != null)

          connection.close();

      }

      catch(SQLException e)

      {

        // connection close failed.

        System.err.println(e);

      }

      }

      }

      public void listTable(int ix)

      {

      try

      { tt=new SQLite_Table(veritablosu[ix]);tt.setVisible(true);

      } catch(ClassNotFoundException e)

      { // "out of memory" mesajı veri tabanının bulunamadığı anlamına gelir

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

      }}

public void dials()

{ double n1=Math.PI/2;

double n2=3.0*n1;

String st[]={" sine curve "};

double td[]={0};

double tmin=-1.0;

double tmax=1.0;

double tetamax=100;

double teta1_rad=Math.PI/4;

double teta2_rad=3.0*Math.PI/2.0+teta1_rad;

//d1=new dials("Arduino analog read","y=sin(t)",st,td,tmin,tmax,teta1_rad,teta2_rad);

//FrameGraphic.plot("ARDUINO Voltmetre ",d1);

}

//zamana bağlı grafik 

public void timeplot()

{ int nyi=1;

  int nquei=800;

  String pl="ARDUINO Voltage plot";

  String xl="time second";

  String yl="Voltage V";

  int xnt=10;

  int ynt=30;

  int xgr=0;

  int ygr=0;

  int ipti[]={5};

  Color ibg=Color.cyan;

  Color ifg[]={Color.black,Color.blue,Color.red,Color.black,Color.green,Color.cyan,Color.yellow,Color.black};

  //d3=new tplot2D(nyi,nquei,pl,xl,yl,xnt,ynt,xgr,ygr,ipti,ibg,ifg);

  //FrameGraphic.plot("Zaman Grafiği ",d3,1300,800);

}      

      public static void main(String arg[]) throws ClassNotFoundException

      { String veritabani="VT";

        String veritablosu[]={"VT1"};

        double ymin=-1.0;

        double ymax=1.0;

                              Monitor1B m=new Monitor1B("ARDUNIO",veritabani,veritablosu,ymin,ymax);

                              m.createTable(0);

       m.start();

       }

}

 

 

Veri tabanı sistemi önemli bir ek programlama tekniği olduğundan ekte ayrıca bu konuda detaylı bilgi sunulmuştur.

 

 

Bir sonraki programımızda veri çıktısı grafik saat formunda gösterilmektedir. Bu programın ek programları olan grafik saat programları da ekte verilmektedir.

import java.io.*;

import java.util.*;

import gnu.io.CommPort;

import gnu.io.CommPortIdentifier;

import gnu.io.SerialPort;

import java.io.FileDescriptor;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.awt.*;

 

 

public class Monitor1C implements Runnable

{   String s2="[\\x00-\\x20]*[+-]?(((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*";             

                        private static final long serialVersionUID = 8257386587L;

                        public Thread readThread;             // zaman içinde çalışma değişkeni

    public  CommPortIdentifier portId;    // seri bağlantı kanalı numarası

    public  SerialPort serialPort;        // seri kanal

    public  OutputStream outputStream;    // çıktı kanalı

    public  InputStream inputStream;      // girdi kanalı

    public  int sleep1;                   // readThread bekleme zamanı milisaniye

    //public tplot2D d3;

     public dials d1;

    double T1,T1old;

    double ymin,ymax;

    //kontrol parametresi

    public String veritabani;

    public String veritablosu[];

        String zamanold,zamannew;

    public  String veri[][];              // String formunda ç?kt? de?i?kenleri

    public Monitor1C(String s,String veritabanii,String veritablosui[],double ymini,double ymaxi)

    {  ymin=ymini;

       ymax=ymaxi;

                            veritabani=veritabanii;

        veritablosu=veritablosui;

                            portId=portId(s);

    System.out.println("portID is read");

      try { serialPort = (SerialPort)

            portId.open(s, 2000);

                    } catch ( gnu.io.PortInUseException e) {}

                    try {

                        outputStream = serialPort.getOutputStream();

                    } catch (IOException e) {}

                    try {

                        serialPort.setSerialPortParams(19200,

                            SerialPort.DATABITS_8,

                            SerialPort.STOPBITS_1,

                            SerialPort.PARITY_NONE);

                    } catch ( gnu.io.UnsupportedCommOperationException e) {}

 

                    dials();

               

}

 

    //seri ileti?im kanal? aç?lmas?

    public  CommPortIdentifier portId(String s)

    {    portId = PortChooser.select_port(null);           

                    try {

                        serialPort = (SerialPort)

                            portId.open(s, 2000);

                    } catch ( gnu.io.PortInUseException e) {}

    return portId;

    }

   

    public  void start()

    {readThread = new Thread(this);

    readThread.start();

    }

    public void run()

     {  int ix=0;

     int n=1;

      int k=0;

                          while(true)

                          {                    

      try{

                          k++;                                  

      Thread.sleep(1000);

      try {

      inputStream = serialPort.getInputStream();

                    byte[] readBuffer = new byte[30];

                    long[] readBuffer1 = new long[30];

                    byte numBytes = (byte)inputStream.read(readBuffer);

                    String s= new String(readBuffer, "US-ASCII");

                                        if(s.matches(s2))

                                        {T1=Double.parseDouble(s);}

                                        else

                                        {T1=T1old;}

                                        double T2[]={T1};

                                        d1.setData(T2);

                                        T1old=T1;

                                        veri=new String[n][T2.length+4];

           veri[ix][0]=""+k;

           String zaman[]=zaman();

           veri[ix][1]=zaman[0];

           veri[ix][2]=zaman[1];

           double tt=zaman1(zaman[1]);

           zamannew=zaman[1];

           int cihaz_adresi[]={0};

           veri[ix][3]=""+cihaz_adresi[ix];

           veri[ix][4]=""+T2[0];

           d1.setData(T2);

         zamanold=zamannew;

                              //d3.setXY(tt,T2,ymin,ymax);         

                                       

                                        //System.out.print("T1="+T1);

      } catch (IOException e) {}

      } catch (InterruptedException e) {System.out.println("InterruptedException 1");}

      }

      }

      public double zaman1(String ss)

    {

     StringTokenizer token=new StringTokenizer(ss,":");

     int m=token.countTokens();

     String s1[]=new String[m];

     int j=0;          

     while(token.hasMoreTokens())

     { s1[j]=token.nextToken();j++;}

     double tt=Double.parseDouble(s1[0])*3600+Double.parseDouble(s1[1])*60+Double.parseDouble(s1[2]);

     return tt;

    }

 

    public  String[] zaman()

    {

                        GregorianCalendar calendar;

                        Date date=new Date();

                        String[] ids = TimeZone.getAvailableIDs(+3 * 60 * 60 * 1000);

    SimpleTimeZone pdt = new SimpleTimeZone(+3 * 60 * 60 * 1000, ids[0]);

    calendar=new GregorianCalendar(pdt);

    calendar.setTime(date);

    String dt=""+calendar.get(Calendar.DATE);

    if (dt.length()==1) dt="0"+dt;

    String mo=""+(calendar.get(Calendar.MONTH)+1);

    if (mo.length()==1) mo="0"+mo;

    String Sdate=dt+"/"+mo+"/"+calendar.get(Calendar.YEAR);

    String ho=""+(calendar.get(Calendar.AM_PM)*12+calendar.get(Calendar.HOUR));

    if (ho.length()==1) ho="0"+ho;    

    String min=""+calendar.get(Calendar.MINUTE);

     if (min.length()==1) min="0"+min;

    String sec=""+calendar.get(Calendar.SECOND);

    if (sec.length()==1) sec="0"+sec;   

    String Stime=ho+":"+min+":"+sec+" ";

    String z[]={Sdate,Stime};

    return z;

                        }

 

public void dials()

{ double n1=Math.PI/2;

double n2=3.0*n1;

String st[]={" sine curve "};

double td[]={0};

double tmin=-1.0;

double tmax=1.0;

double tetamax=100;

double teta1_rad=Math.PI/4;

double teta2_rad=3.0*Math.PI/2.0+teta1_rad;

d1=new dials("Arduino analog read","y=sin(t)",st,td,tmin,tmax,teta1_rad,teta2_rad);

FrameGraphic.plot("ARDUINO Voltmetre ",d1);

}

//zamana bağlı grafik 

public void timeplot()

{ int nyi=1;

  int nquei=800;

  String pl="ARDUINO Voltage plot";

  String xl="time second";

  String yl="Voltage V";

  int xnt=10;

  int ynt=30;

  int xgr=0;

  int ygr=0;

  int ipti[]={5};

  Color ibg=Color.cyan;

  Color ifg[]={Color.black,Color.blue,Color.red,Color.black,Color.green,Color.cyan,Color.yellow,Color.black};

  //d3=new tplot2D(nyi,nquei,pl,xl,yl,xnt,ynt,xgr,ygr,ipti,ibg,ifg);

  //FrameGraphic.plot("Zaman Grafiği ",d3,1300,800);

}      

      public static void main(String arg[]) throws ClassNotFoundException

      { String veritabani="VT";

        String veritablosu[]={"VT1"};

        double ymin=-1.0;

        double ymax=1.0;

                              Monitor1C m=new Monitor1C("ARDUNIO",veritabani,veritablosu,ymin,ymax);

                             // m.createTable(0);

       m.start();

       }

}

 

 

 

Bir sonraki ARDUINO Due programımızda hem okuma hem de yazma yapacağız. Temel birimimiz1 adet LED olacaktır. LED’leri 3.3 V luk beslemeyle yakmak için 220 Ohm direnç kullanacağız. ARDUINO programımız:

int incomingByte = 0;

void setup() {

  Serial.begin(19200);

  pinMode(10, OUTPUT);

}

void loop()

{ if(Serial.available() > 0)

  { incomingByte = Serial.read();

   if(incomingByte==1)

   { digitalWrite(10, HIGH);

     delay(2);

   }

   else

   {digitalWrite(10, LOW);

    delay(2);

   }

   }

}

 

Bu program java programında sinyal almaktadır. Sinyal 1 olduğunda LED yanar diğer sinyallerde söner. Java programı

import java.io.*;

import java.util.*;

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.sql.SQLException;

import java.sql.Statement;

import java.awt.*;

import javax.swing.*;

import java.awt.Graphics;

import java.awt.*;

import java.awt.event.*;

public class Monitor8 implements Runnable

{   String s2="[\\x00-\\x20]*[+-]?(((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*";             

                        private static final long serialVersionUID = 8257386587L;

                        public Thread readThread;             // zaman içinde çal??ma de?i?keni

    public  CommPortIdentifier portId;    // seri ba?lant? kanal? numaras?

    public  SerialPort serialPort;        // seri kanal

    public  OutputStream outputStream;    // ç?kt? kanal?

    public  InputStream inputStream;      // girdi kanal?

    public  int sleep1;                   // readThread bekleme zaman? milisaniye

    public buttonP d1;

    public Monitor8(String s)

    { portId=portId(s);

    System.out.println("portID is read");

      try { serialPort = (SerialPort)

            portId.open(s, 2000);

                    } catch (gnu.io.PortInUseException e) {}

                    try {

                        outputStream = serialPort.getOutputStream();

                    } catch (IOException e) {}

                    try {

                        serialPort.setSerialPortParams(19200,

                            SerialPort.DATABITS_8,

                            SerialPort.STOPBITS_1,

                            SerialPort.PARITY_NONE);

                    } catch (gnu.io.UnsupportedCommOperationException e) {}

                    button();                   }

 

    //seri iletişim kanalı açılmas?

    public  CommPortIdentifier portId(String s)

    {    portId = PortChooser.select_port(null);           

                    try {

                        serialPort = (SerialPort)

                            portId.open(s, 2000);

                    } catch (gnu.io.PortInUseException e) {}

    return portId;

    }

    public  void start()

    {readThread = new Thread(this);

    readThread.start();

    }

    public void run()

     { 

      int k=0;

                          while(true)

                          {                    

      try{

                          k++;                                  

      Thread.sleep(100);

      try {

                                        if(d1.signal==1)

                                            {outputStream.write(d1.signal); d1.setBackground(Color.yellow);d1.jtf.setText("ışık  yanıyor");}

                                        else

                                           {outputStream.write(d1.signal);d1.setBackground(Color.blue);d1.jtf.setText("ışık  söndü");  }

      } catch (IOException e) {}

      } catch (InterruptedException e) {System.out.println("InterruptedException 1");}

      }

      }

public void button()

{d1=new buttonP();

 FrameGraphic.plot("ARDUINO relay sensor",d1);

}

      public static void main(String arg[])

      { Monitor8 m=new Monitor8("ARDUNIO");

       m.start();

       }

}

 

 

Bir sonraki ARDUINO Due programımızda hem okuma hem de yazma yapacağız.  Temel birimimiz 3 adet LED olacaktır. LED’leri 3.3 V luk beslemeyle yakmak için 220 Ohm direnç kullanacağız. ARDUINO programı

 

int incomingByte = 0;

void setup() {

  Serial.begin(19200);

  pinMode(10, OUTPUT);

  pinMode(11, OUTPUT);

  pinMode(12, OUTPUT);

}

void loop()

{ if(Serial.available() > 0)

  { incomingByte = Serial.read();

   if(incomingByte==1)

   { digitalWrite(10, HIGH);

     delay(100);

   }

   else if(incomingByte==2)

   {digitalWrite(10, LOW);

    delay(100);

   }

   else if(incomingByte==3)

   { digitalWrite(11, HIGH);

     delay(100);

   }

   else if(incomingByte==4)

   {digitalWrite(11, LOW);

    delay(100);

   }

   else if(incomingByte==5)

   { digitalWrite(12, HIGH);

     delay(100);

   }

   else if(incomingByte==6)

   {digitalWrite(12, LOW);

    delay(100);

   }

   }

}

 

Alternatif arduino program (kodu daha kısa yazmak için)

int incomingByte = 0;

int i=10;

void setup() {

  Serial.begin(19200);

  for(int j=0;j<3;j++)

  {pinMode(i+j, OUTPUT);}

}

void loop()

{ if(Serial.available() > 0)

  { incomingByte = Serial.read();

  for(int j=0;j<3;j++)

  {if(incomingByte==(2*j+1)) { digitalWrite(i+j, HIGH);}

   else if(incomingByte==(2*j+2)){digitalWrite(i+j, LOW);}

  delay(10);

  }

  }

}

 

Java Programı:

 import java.io.*;

import java.util.*;

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.sql.SQLException;

import java.sql.Statement;

import java.awt.*;

import javax.swing.*;

import java.awt.Graphics;

import java.awt.*;

import java.awt.event.*;

public class Monitor10 implements Runnable

{   String s2="[\\x00-\\x20]*[+-]?(((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*";             

                        private static final long serialVersionUID = 8257386587L;

                        public Thread readThread;             // zaman içinde çal??ma de?i?keni

    public  CommPortIdentifier portId;    // seri ba?lant? kanal? numaras?

    public  Se

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     rialPort serialPort;        // seri kanal

    public  OutputStream outputStream;    // ç?kt? kanal?

    public  InputStream inputStream;      // girdi kanal?

    public  int sleep1;                   // readThread bekleme zaman? milisaniye

    public buttonP2 d1;

    public Monitor10(String s)

    { portId=portId(s);

    System.out.println("portID is read");

      try { serialPort = (SerialPort)

            portId.open(s, 2000);

                    } catch (gnu.io.PortInUseException e) {}

                    try {

                        outputStream = serialPort.getOutputStream();

                    } catch (IOException e) {}

                    try {

                        serialPort.setSerialPortParams(19200,

                            SerialPort.DATABITS_8,

                            SerialPort.STOPBITS_1,

                            SerialPort.PARITY_NONE);

                    } catch (gnu.io.UnsupportedCommOperationException e) {}

                    button();                   }

 

    //seri iletişim kanalı açılmas?

    public  CommPortIdentifier portId(String s)

    {    portId = PortChooser.select_port(null);           

                    try {

                        serialPort = (SerialPort)

                            portId.open(s, 2000);

                    } catch (gnu.io.PortInUseException e) {}

    return portId;

    }

    public  void start()

    {readThread = new Thread(this);

    readThread.start();

    }

    public void run()

     { 

      int k=0;

                          while(true)

                          {                    

      try{

                          k++;                                  

      Thread.sleep(100);

      try { outputStream.write(d1.signal);

      } catch (IOException e) {}

      } catch (InterruptedException e) {System.out.println("InterruptedException 1");}

      }

      }

public void button()

{d1=new buttonP2();

 FrameGraphic.plot("ARDUINO 3 LED control",d1,200,200);

}

      public static void main(String arg[])

      { Monitor10 m=new Monitor10("ARDUNIO");

       m.start();

       }

}

 

import java.awt.Graphics;

 import java.util.*;

 import java.text.*;

 import java.util.Locale;

 import java.awt.image.*;

 import javax.swing.*;

import java.awt.Graphics;

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.*;

import java.awt.font.*;

 

// ============

public class buttonP2 extends JPanel implements ActionListener

{ private static final long serialVersionUID =47897468764L;

     JButton jb1,jb2,jb3;

     JTextField jtf1,jtf2,jtf3;

     JPanel jp;

     int signal1,signal2,signal3,signal;

     public buttonP2()

     { jp=new JPanel();

                         jp.setLayout(new GridLayout(2,3));

                         setLayout(new BorderLayout());

     jb1=new JButton("LED 1");

     jb1.setBackground(Color.blue);

     jtf1=new JTextField("LED 1 off");

     jb2=new JButton("LED 2");

     jb2.setBackground(Color.blue);

     jtf2=new JTextField("LED 2 off");

     jb3=new JButton("LED 3");

     jb3.setBackground(Color.blue);

     jtf3=new JTextField("LED 3 off");

     signal1=2;

     signal2=4;

     signal3=6;

     signal=2;

     jb1.addActionListener(this);

     jb2.addActionListener(this);

     jb3.addActionListener(this);

     jp.add(jb1);

     jp.add(jb2);

     jp.add(jb3);

     jp.add(jtf1);

     jp.add(jtf2);

     jp.add(jtf3);

     add(jp,BorderLayout.NORTH);

     }

     public void actionPerformed( ActionEvent e)

    {   if(e.getSource()==jb1)

        {   if(signal1==1) {signal1=2;signal=2;jb1.setBackground(Color.blue);jtf1.setText("LED1 off signal = "+signal);}

            else if(signal1==2) {signal1=1;signal=1;jb1.setBackground(Color.yellow);jtf1.setText("LED1 on signal = "+signal);}

            }

        else if(e.getSource()==jb2)

        {   if(signal2==3) {signal2=4;signal=4;jb2.setBackground(Color.blue);jtf2.setText("LED2 off signal = "+signal);}

            else if(signal2==4) {signal2=3;signal=3;jb2.setBackground(Color.yellow);jtf2.setText("LED2 on signal = "+signal);}

        }

        else if(e.getSource()==jb3)

        {   if(signal3==5) {signal3=6;signal=6;jb3.setBackground(Color.blue);jtf3.setText("LED3 off signal = "+signal);}

            else if(signal3==6) {signal3=5;signal=5;jb3.setBackground(Color.yellow);jtf3.setText("LED3 on signal = "+signal);}

        }

     }

}

 

 

 

Şimdi de aynı programı kullanarak 2 arduinoyu aynı zamanda kontrol edelim. Bunun için yukarıda verilen arduino programını 2 ayrı program olarak COM12 ve com 13 olarak çalıştıralım.

 

 

 

Program kodumuzda küçük değişiklikler yaptık, bu yüzden tekrar veriyoruz:

 

import java.io.*;

import java.util.*;

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.sql.SQLException;

import java.sql.Statement;

import java.awt.*;

import javax.swing.*;

import java.awt.Graphics;

import java.awt.*;

import java.awt.event.*;

public class Monitor10A implements Runnable

{   String s2="[\\x00-\\x20]*[+-]?(((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*";             

                        private static final long serialVersionUID = 8257386587L;

                        public Thread readThread;             // zaman içinde çal??ma de?i?keni

    public  CommPortIdentifier portId;    // seri ba?lant? kanal? numaras?

    public  SerialPort serialPort;        // seri kanalpublic  OutputStream outputStream;    // ç?kt? kanal?

    public  InputStream inputStream;      // girdi kanal?

    public  OutputStream outputStream;

    public  int sleep1;                   // readThread bekleme zaman? milisaniye

    public buttonP2 d1;

    public String ss;

    public Monitor10A(String s)

    {   ss=s;

                            portId=portId(ss);

    System.out.println("portID is read");

      try { serialPort = (SerialPort)

            portId.open(s, 2000);

                    } catch (gnu.io.PortInUseException e) {}

                    try {

                        outputStream = serialPort.getOutputStream();

                    } catch (IOException e) {}

                    try {

                        serialPort.setSerialPortParams(19200,

                            SerialPort.DATABITS_8,

                            SerialPort.STOPBITS_1,

                            SerialPort.PARITY_NONE);

                    } catch (gnu.io.UnsupportedCommOperationException e) {}

                    button();                   }

 

    //seri iletişim kanalı açılmas?

    public  CommPortIdentifier portId(String s)

    {    portId = PortChooser.select_port(null);           

                    try {

                        serialPort = (SerialPort)

                            portId.open(s, 2000);

                    } catch (gnu.io.PortInUseException e) {}

    return portId;

    }

    public  void start()

    {readThread = new Thread(this);

    readThread.start();

    }

    public void run()

     { 

      int k=0;

                          while(true)

                          {                    

      try{

                          k++;                                  

      Thread.sleep(100);

      try { outputStream.write(d1.signal);

      } catch (IOException e) {}

      } catch (InterruptedException e) {System.out.println("InterruptedException 1");}

      }

      }

public void button()

{d1=new buttonP2();

 FrameGraphic.plot(ss,d1,200,200);

}

      public static void main(String arg[])

      { Monitor10A m1=new Monitor10A("ARDUNIO COM 12");

        Monitor10A m2=new Monitor10A("ARDUNIO com 13");

        m1.start();

        m2.start();

       }

}

 

Programın bu versiyonunda 2 adet thread bir arada çalıştırılmıştır.

 

EKLER

 

EK 1 Gerçek zaman grafik programı tplot2D ve PlotShapesSW

//=======================================================//

//  veritabanından veriyi okuyup basit bir grafik çıktısı                              //

//  olarak gösteren bir program                                                                     //

//  tplot2D                                                                                                          //

//  M. Turhan Coban                                                                                         //

//=======================================================//

 

import java.io.*;

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.*;

import javax.swing.*;

import java.awt.print.PrinterJob;

import java.util.*;

import java.awt.print.*;

 

public class tplot2D extends JPanel

{   private static final long serialVersionUID = 832595695263L;

                        public Graphics2D g;

    final static Color bg = Color.white;

    final static Color fg = Color.black;

    final static Color red = Color.red;

    final static Color white = Color.white;

    final static BasicStroke stroke = new BasicStroke(1.0f);

    final static BasicStroke boldStroke = new BasicStroke(2.0f);

    PlotShapesSW ps;

    public double xx[],yy[][];

    public double xmin,xmax,ymin,ymax;

    int ny;  //number of data in the plot window

    int nque;

    ArrayDeque<Double> timeque;

    ArrayDeque<Double>[] xque;

    String label;

    String xlabel;

    String ylabel;

    int xntic;

    int yntic;

    int xgridon;

    int ygridon;

    int nplot[];

    Color fgcolor[];

    Color bgColor;

    // ny : number of data set

    // label : plot label

    // xlabel : xaxis label

    // ylabel : y axis label

    // xntic  : number of x axis tic

    // yntic  : number of y axis tic

    // nplot  : plot line type

  

    public tplot2D(int nyi,int nquei,

    String pl,String xl,String yl,int xnt,int ynt,int xgr,int ygr,int ipt[],Color bg,Color fg[])

    { ny=nyi;

      nque=nquei;

      label=pl;

      xlabel=xl;

      ylabel=yl;

      xntic=xnt;

      yntic=ynt;

      xgridon=xgr;

      ygridon=ygr;

      bgColor=bg;

      fgcolor=new Color[ny];

      nplot=new int[ny];

      xx=new double[nque];

      yy=new double[ny][nque];

      xmin=9.99e50;

      xmax=-9.99e50;

      ymin=9.99e50;

      ymax=-9.99e50;

      for(int i=0;i<ny;i++)

      {fgcolor[i]=fg[i];

       nplot[i]=ipt[i];

      }

    setBackground(bgColor);

    setForeground(Color.black);

    timeque=new ArrayDeque<Double>(nque);

    xque=new ArrayDeque[ny];

 

    for(int i=0;i<ny;i++)

    {xque[i]=new ArrayDeque<Double>(nque);}

                        }

                                       

    public void setXY(double itime,double iyy[])

    {

                          xmin=9.99e50;

      xmax=-9.99e50;

      ymin=9.99e50;

      ymax=-9.99e50;

    timeque.addLast(new Double(itime));

    if(timeque.size()>nque) timeque.removeFirst();

                        for(int i=0;i<ny;i++)

      { xque[i].addLast(new Double(iyy[i]));

        if(xque[i].size()>nque) xque[i].removeFirst();

      }

    Object[] a=timeque.toArray();

    Double da;

 

    for(int j=0;j<a.length;j++)

    {da=(Double)a[j];xx[j]=da.doubleValue();

    if(xx[j]<xmin) xmin=xx[j];

    if(xx[j]>xmax) xmax=xx[j]; 

    }

   

    Object[] b;

    for(int i=0;i<ny;i++)

    {

                        b=xque[i].toArray();

    Double db;

    for(int j=0;j<b.length;j++)

    {db=(Double)b[j];yy[i][j]=db.doubleValue();

     if(yy[i][j]<ymin) ymin=yy[i][j];

     if(yy[i][j]>ymax) ymax=yy[i][j];

     if(ymin==ymax) {ymin=yy[i][j]-0.1;ymax=yy[i][j]+0.1;}

    }               

    }}

    public void setXY(double itime,double iyy[],double ymini,double ymaxi)

    {

                          xmin=9.99e50;

      xmax=-9.99e50;

      ymin=ymini;

      ymax=ymaxi;

    timeque.addLast(new Double(itime));

    if(timeque.size()>nque) timeque.removeFirst();

                        for(int i=0;i<ny;i++)

      { xque[i].addLast(new Double(iyy[i]));

        if(xque[i].size()>nque) xque[i].removeFirst();

      }

    Object[] a=timeque.toArray();

    Double da;

 

    for(int j=0;j<a.length;j++)

    {da=(Double)a[j];xx[j]=da.doubleValue();

    if(xx[j]<xmin) xmin=xx[j];

    if(xx[j]>xmax) xmax=xx[j]; 

    }

   

    Object[] b;

    for(int i=0;i<ny;i++)

    {

                        b=xque[i].toArray();

    Double db;

    for(int j=0;j<b.length;j++)

    {db=(Double)b[j];

    yy[i][j]=db.doubleValue();

    if(yy[i][j]<ymin) yy[i][j]=ymin;

    if(yy[i][j]>ymax) yy[i][j]=ymax;

     //if(yy[i][j]<ymin) ymin=yy[i][j];

     //if(yy[i][j]>ymax) ymax=yy[i][j];

     //if(ymin==ymax) {ymin=yy[i][j]-0.1;ymax=yy[i][j]+0.1;}

    }               

    }}      

    public void drawShapes(Graphics2D g2)

    {

        g=g2;

                            //draw Plot

        Dimension d=getSize();

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

        RenderingHints.VALUE_ANTIALIAS_ON);

        int gridWidth = d.width;

        int gridHeight = d.height;

        int rowspacing=(int)(d.width/100.0);

        int columnspacing=(int)(d.height/50.0);

        int rectWidth=gridWidth-columnspacing;

        int rectHeight=gridHeight-rowspacing;

        int xabsmin=(int)(0.25*rectWidth);

        int yabsmin=(int)(0.2*rectHeight);

        int abswidth=(int)(0.65*rectWidth);

        int absheight=(int)(0.7*rectHeight);

        int xlog=0;

        int ylog=0;

        char ch='+';

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g2.setStroke(stroke);

        //g2.setPaint(fgcolor);

        g2.drawRect(xabsmin,yabsmin,abswidth,absheight);

        ps=new PlotShapesSW(g2,xabsmin,yabsmin,

        absheight,abswidth,xmin,xmax,ymin,ymax,xlog,ylog);

        if(xgridon!=0) ps.drawXGrid(xntic);

        if(ygridon!=0) ps.drawYGrid(yntic);

        int i,j;

        for(i=0;i<ny;i++)

           {

           //  Select plot colors

           g2.setPaint(fgcolor[i]);

          

           ps.drawPlotLine(nplot[i],xx,yy[i]);

           }//end of for(i=0                   

        g2.setPaint(fg);

        ps.drawXTic(xntic,(ymax-ymin)/80.0,0);

        ps.drawYTic(yntic,(xmax-xmin)/80.0,0);

        ps.drawXString(xntic);

        //ps.drawXNumbers(xntic);

        ps.drawYNumbers(yntic);

        ps.drawLabel(label);

        ps.drawXLabel(xlabel);

        ps.drawYLabel(ylabel);

    }      

    public void paintComponent(Graphics g)

    {

        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g;

        drawShapes(g2);

        repaint();     

    }

}

 

//======================================================

// Numerical Analysis package in java

// PlotShapes class

// This class convert graphic draw methods to

// plot coordinates and gives additional plotting methods

// Dr. Turhan Coban

// =====================================================

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.*;

import javax.swing.*;

import java.awt.font.*;

import java.io.*;

import java.util.Locale;

 

public class PlotShapesSW

{

public Graphics2D g;

int xabsmin,yabsmin;

int absheight,abswidth;

double xmin,xmax,ymin,ymax;

public int xlog,ylog;

double xminmaxlog,yminmaxlog;

Font f;

final static float dash1[] = {10.0f};

final static float dash2[] = {10.0f,3.0f,3.0f};

final static float dash3[] = {10.0f,3.0f,3.0f};

final static float dash4[] = {5.0f,5.0f,5.0f};

 

final static BasicStroke d1 = new BasicStroke(1.0f,BasicStroke.CAP_BUTT,

                                                      BasicStroke.JOIN_MITER,

                                                      3.0f, dash1, 2.0f);

final static BasicStroke d2 = new BasicStroke(1.0f,BasicStroke.CAP_BUTT,

                                                      BasicStroke.JOIN_MITER,

                                                      3.0f, dash2, 2.0f);

final static BasicStroke d3 = new BasicStroke(1.0f,BasicStroke.CAP_BUTT,

                                                      BasicStroke.JOIN_MITER,

                                                      3.0f, dash3, 2.0f);

final static BasicStroke d4 = new BasicStroke(1.0f,BasicStroke.CAP_BUTT,

                                                      BasicStroke.JOIN_MITER,

                                                      3.0f, dash4, 2.0f);

final static BasicStroke d5 = new BasicStroke(2.0f,BasicStroke.CAP_BUTT,

                                                      BasicStroke.JOIN_MITER,

                                                      3.0f, dash1, 2.0f);

final static BasicStroke d6 = new BasicStroke(2.0f,BasicStroke.CAP_BUTT,

                                                      BasicStroke.JOIN_MITER,

                                                      3.0f, dash2, 2.0f);

final static BasicStroke d7 = new BasicStroke(2.0f,BasicStroke.CAP_BUTT,

                                                      BasicStroke.JOIN_MITER,

                                                      3.0f, dash3, 2.0f);

final static BasicStroke d8 = new BasicStroke(2.0f,BasicStroke.CAP_BUTT,

                                                      BasicStroke.JOIN_MITER,

                                                      3.0f, dash4, 2.0f);

 

 

public PlotShapesSW(Graphics2D gi,int xabsmini  ,int yabsmini,

                              int absheighti,int abswidthi,

                            double xmini,double xmaxi,

                            double ymini,double ymaxi, int xlogi,int ylogi)

{

// xabsmin   : absolute(pixel) starting point x axis

// yabsmin   : absolute(pixel) starting point y axis

// absheight : absolute(pixel) height of plotting window

// abswidth  : absolute(pixel) width of plotting window

// xmin      : minimum x value (real number)

// xmax      : maximum x value (real number)

// ymin      : minimum y value (real number)

// ymax      : maximum y value (real number)

// g         : graphic object that actual drawing is done through

g=gi;

//Font fonts[]=GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();

//f=fonts[2].deriveFont(Font.BOLD,14);//You can change Fony from here

//g.setFont(f);

xabsmin=xabsmini;

yabsmin=yabsmini;

absheight=absheighti;

abswidth=abswidthi;

xmin=xmini;

xmax=xmaxi;

ymin=ymini;

ymax=ymaxi;

xlog=xlogi;

ylog=ylogi;

if(xlog!=0) {xminmaxlog=Math.log10(xmax-xmin+10.0)-1.0;}

if(ylog!=0) {yminmaxlog=Math.log10(ymax-ymin+10.0)-1.0;}

}

 

public void drawLine(int plottype,double x1,double y1,double x2,double y2)

{

// draw a line from (x1,y1) to (x2,y2)

        int xx1,xx2,yy1,yy2;

        if(xlog!=0)

        {

        xx1=(int)(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth));

        xx2=(int)(xabsmin+((Math.log10(x2-xmin+10.0)-1.0)/xminmaxlog*abswidth));

                            }

        else

        {

                            xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth);

        xx2=(int)(xabsmin+(x2-xmin)/(xmax-xmin)*abswidth);

                            }

        if(ylog!=0)

        {

        yy1=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight));

        yy2=(int)(yabsmin+absheight-((Math.log10(y2-ymin+10.0)-1.0)/yminmaxlog*absheight));

                            }

        else

        {

                            yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight);

        yy2=(int)(yabsmin+absheight-(y2-ymin)/(ymax-ymin)*absheight);

                            }       

        g.draw(new Line2D.Double( xx1,yy1,xx2,yy2));

}  //end of drawLine

 

 

public void drawPolyline(int plottype,double x1[],double y1[])

{

// draw a line from (x1,y1) to (x2,y2)

        int points=y1.length;

        int xPoints[]=new int[points];

        int yPoints[]=new int[points];

        int xx1,yy1;                   

        for(int i=0;i<points;i++)

        {

                               if(xlog!=0)

           {xx1=(int)(xabsmin+(Math.log10(x1[i]-xmin+10.0)-1.0)/xminmaxlog*abswidth);}

           else

           {xx1=(int)(xabsmin+(x1[i]-xmin)/(xmax-xmin)*abswidth);}

           if(ylog!=0)

           {yy1=(int)(yabsmin+absheight-(Math.log10(y1[i]-ymin+10.0)-1.0)/yminmaxlog*absheight);}

           else

           {yy1=(int)(yabsmin+absheight-(y1[i]-ymin)/(ymax-ymin)*absheight);}   

        xPoints[i]=xx1;

        yPoints[i]=yy1;

                            }

        g.drawPolyline(xPoints,yPoints,points);

}  //end of drawPolyLine

 

public  void drawChar(char ch,double x1,double y1)

{

    // draws a single character at (x1,y1)

        char ch1[]=new char[1];

        ch1[0]=ch;

        int h=g.getFontMetrics().getHeight();

        int w=h-2;

        int xx1,yy1;

           if(xlog!=0)

           {xx1=(int)(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth-abswidth/200.0));}

           else

           {xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth);}//-abswidth/200.0);}

           if(ylog!=0)

           {yy1=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight))+h/2;}

           else

           {yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight);}//+h/2;}   

        g.drawChars(ch1,0,1,xx1,yy1);

}  //end of PlotShapes.drawChar

 

public void drawChars(char ch[],int firstspace,int numberofchars,

                                double x1,double y1)

{

        int h=g.getFontMetrics().getHeight();

        int w=h-2;

        int xx1,yy1;

        if(xlog!=0)

           {xx1=(int)(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth-abswidth/80.0));}

        else

           {xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth);}//-abswidth/80.0);}

        if(ylog!=0)

           {yy1=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight));}

        else

           {yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight);}  

        g.drawChars(ch,firstspace,numberofchars,xx1,yy1);

}  //end of PlotShapes.drawChars

 

public void drawString(String s,double x1,double y1)

{

    //draws a String at (x1,y1)

        int h=g.getFontMetrics().getHeight();

        int w=h-2;

           int xx1,yy1;

           if(xlog!=0)

           {xx1=(int)(xabsmin+((Math.log10(x1-xmin+1.0)-1.0)/xminmaxlog*abswidth));}

           else

           {xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth);}

           if(ylog!=0)

           {yy1=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight));}

           else

           {yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight);}  

        g.drawString(s,xx1,yy1);

 

}  //end of PlotShapes.drawString

 

public void drawString(String s[],double x1,double y1,double dy)

{

    // draws a serial of Strings starting at (x1,y1)

    // increasing with dy each time

 

        int h=g.getFontMetrics().getHeight();

        int w=h-2;

        double xx1,yy1;

        int n=s.length;

        xx1=x1;

        for(int i=0;i<n;i++)

        {   yy1=y1-i*dy;

                                if(s[i]!="") drawString(s[i],xx1,yy1);

            else break;

                            }

}  //end of PlotShapes.drawStrings

 

public void drawString(String s[],int plottypes[],double x1,double y1,double dx,double dy)

{

    // draws a serial of plot characters and then Strings starting at (x1,y1)

    // increasing with dy each time

        double x[]=new double[2];

        double y[]=new double[2];

        int h=g.getFontMetrics().getHeight();

        int w=h-2;

        int xx1,yy1;

        int n=s.length;

        double xx2=x1+2*dx;

        double y2=y[0];

        double yy2=0;

        for(int i=0;i<n;i++)

        {  if(s[i]!="")

           {

                               x[0]=x1;

           x[1]=x1+dx;

           y[0]=y1-i*dy;

           y[1]=y1-i*dy;

           yy2=y[0]-(xmax-xmin)/50.0;

           //drawPlotLine(int plottypei,double xi[],double yi[])

           drawPlotLine(plottypes[i],x,y);

           drawString(s[i],xx2,yy2);

           }

           else break;

       }

}  //end of PlotShapes.drawStrings

 

public void drawRect(double x1,double y1,int rectwidth,int rectheight)

{

// draw a rectangle starting at (x1,y1)

// with dimensions of (rectwidth,rectheight)

           int xx1,yy1;

           if(xlog!=0)

           {xx1=(int)(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth-rectwidth/2));}

           else

           {xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth-rectwidth/2);}

           if(ylog!=0)

           {yy1=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight-rectheight/2));}

           else

           {yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight-rectheight/2);}

             

        g.draw(new Rectangle2D.Double(xx1,yy1,rectwidth,rectheight));

 

}//end of drawRect

 

public void drawBar(double x1,double y1)

{

// draw a rectangle starting at (x1,y1)

// with dimensions of (rectwidth,rectheight)

           int xx1,yy1;

           double barheight;

           double barwidth=abswidth/300;

           if(xlog!=0)

           {xx1=(int)(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth-barwidth/2.0));}

           else

           {xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth-barwidth/2.0);

           }

           if(ylog!=0)

           {yy1=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight));

           barheight =(int)((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight);

           }

           else

           {yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight);

           barheight =(int)((y1-ymin)/(ymax-ymin)*absheight);}

           g.draw(new Rectangle2D.Double(xx1,yy1,barwidth,barheight));

}//end of drawBar

 

public void fillBar(double x1,double y1)

{

          int xx1,yy1;

           double barheight;

           double barwidth=abswidth/300;

           if(xlog!=0)

           {xx1=(int)(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth-barwidth/2.0));}

           else

           {xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth-barwidth/2.0);

           }

           if(ylog!=0)

           {yy1=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight));

           barheight =(int)((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight);

           }

           else

           {yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight);

           barheight =(int)((y1-ymin)/(ymax-ymin)*absheight);}

           g.fill(new Rectangle2D.Double(xx1,yy1,barwidth,barheight));

}//end of fillBar

 

public void fillRect(double x1,double y1,int rectwidth,int rectheight)

{

// draw a rectangle starting at (x1,y1)

// with dimensions of (rectwidth,rectheight)

// draw a rectangle starting at (x1,y1)

// with dimensions of (rectwidth,rectheight)

           int xx1,yy1;

           if(xlog!=0)

           {xx1=(int)(xabsmin+(Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth-rectwidth/2);}

           else

           {xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth-rectwidth/2);}

           if(ylog!=0)

           {yy1=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight-rectheight/2));}

           else

           {yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight-rectheight/2);}             

        g.fill(new Rectangle2D.Double(xx1,yy1,rectwidth,rectheight));

}

 

public void drawEllipse(double x1,double y1,int width,int height)

{

//      draw an oval with the centre of (x1,y1)

//      with dimension of (width,height)

           int xx1,yy1;

           if(xlog!=0)

           {xx1=(int)(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth-width/2));}

           else

           {xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth-width/2);}

           if(ylog!=0)

           {yy1=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight-height/2));}

           else

           {yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight-height/2);}        

        g.draw(new Ellipse2D.Double(xx1,yy1,width,height));     

}//end of drawRect

 

public void fillEllipse(double x1,double y1,int width,int height)

{

//      draw an oval with the centre of (x1,y1)

//      with dimension of (width,height)

           int xx1,yy1;

           if(xlog!=0)

           {xx1=(int)(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth-width/2));}

           else

           {xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth-width/2);}

           if(ylog!=0)

           {yy1=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight-height/2));}

           else

           {yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight-height/2);}        

        g.fill(new Ellipse2D.Double(xx1,yy1,width,height));

}//end of drawRect

 

public void drawPolygon(double x1,double y1,int radius,int side)

{

//draw a polygon of n sides n=3(trinagle),n=4(dimond)....

        double Pi=Math.PI;

        int xvalues[]=new int[side+1];

        int yvalues[]=new int[side+1];

        GeneralPath polygon=new GeneralPath(GeneralPath.WIND_EVEN_ODD,

        xvalues.length);

        double angle_increase;

        double angle;

        angle_increase=2.0*Pi/side;

        angle=Pi/2.0;

        for(int i=0;i<=side;i++)

        {

                               if(xlog!=0)

           {xvalues[i]=(int)(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth+radius*Math.cos(angle)));}

           else

           {xvalues[i]=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth+radius*Math.cos(angle));}

           if(ylog!=0)

           {yvalues[i]=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight-radius*Math.sin(angle)));}

           else

           {yvalues[i]=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight-radius*Math.sin(angle));}         

          angle+=angle_increase;

          if(i==0)

          {

          xvalues[side]=xvalues[i];yvalues[side]=yvalues[i];

          polygon.moveTo(xvalues[0],yvalues[0]);

          }

          else

          {

           polygon.lineTo(xvalues[i],yvalues[i]);

          }         

        }

        g.draw(polygon);

}//end of drawPolygon

 

public void fillPolygon(double x1,double y1,int radius,int side)

{

//draw a polygon of n sides n=3(trinagle),n=4(dimond)....

//draw a polygon of n sides n=3(trinagle),n=4(dimond)....

        double Pi=Math.PI;

        int xvalues[]=new int[side+1];

        int yvalues[]=new int[side+1];

        GeneralPath polygon=new GeneralPath(GeneralPath.WIND_EVEN_ODD,

        xvalues.length);

        double angle_increase;

        double angle;

        angle_increase=2.0*Pi/side;

        angle=Pi/2.0;

        for(int i=0;i<=side;i++)

        {

                               if(xlog!=0)

           {xvalues[i]=(int)(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth+radius*Math.cos(angle)));}

           else

           {xvalues[i]=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth+radius*Math.cos(angle));}

           if(ylog!=0)

           {yvalues[i]=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight-radius*Math.sin(angle)));}

           else

           {yvalues[i]=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight-radius*Math.sin(angle));}         

          angle+=angle_increase;

          if(i==0)

          {

          xvalues[side]=xvalues[i];yvalues[side]=yvalues[i];

          polygon.moveTo(xvalues[0],yvalues[0]);

          }

          else

          {

           polygon.lineTo(xvalues[i],yvalues[i]);

          }         

        }

        g.fill(polygon);

}//end of fillPolygon

 

public void drawStar(double x1,double y1,int radius,int side)

{

   double teta=2.0*Math.PI/side;

   double R=radius;

   double r=radius*0.35;

   int xvalues[]=new int[2*side+2];

   int yvalues[]=new int[2*side+2];

   GeneralPath polygon=new GeneralPath(GeneralPath.WIND_EVEN_ODD,

   xvalues.length);

   double teta1,teta2;

   for(int i=0;i<=side;i++)

   {

     teta1=teta*i+Math.PI/2.0;

     teta2=teta/2.0+teta1;

     if(xlog!=0)

     {

     xvalues[2*i]= (int)(Math.floor(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/

          xminmaxlog*abswidth+R*Math.cos(teta1))));

     xvalues[2*i+1]= (int)(Math.floor(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/

          xminmaxlog*abswidth+r*Math.cos(teta2))));

     }

     else

     {

     xvalues[2*i]= (int)(Math.floor(xabsmin+(x1-xmin)/

          (xmax-xmin)*abswidth+R*Math.cos(teta1)));

     xvalues[2*i+1]= (int)(Math.floor(xabsmin+(x1-xmin)/

          (xmax-xmin)*abswidth+r*Math.cos(teta2)));

     }

     if(ylog!=0)

     {

     yvalues[2*i]= (int)(Math.floor(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/

          yminmaxlog*absheight-R*Math.sin(teta1))));

      yvalues[2*i+1]= (int)(Math.floor(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/

          yminmaxlog*absheight-r*Math.sin(teta2))));

     } 

     else

     {

     yvalues[2*i]= (int)(Math.floor(yabsmin+absheight-(y1-ymin)/

          (ymax-ymin)*absheight-R*Math.sin(teta1)));

     yvalues[2*i+1]= (int)(Math.floor(yabsmin+absheight-(y1-ymin)/

          (ymax-ymin)*absheight-r*Math.sin(teta2)));

     }

           

     if(i==side)

     {

     xvalues[2*i]=xvalues[0];

     yvalues[2*i]=yvalues[0];    

     }

   }

 

   for(int i=0;i<=2*side;i++)

   {

          if(i==0)

          {

          polygon.moveTo(xvalues[0],yvalues[0]);

          }

          else

          {

           polygon.lineTo(xvalues[i],yvalues[i]);

          }

   }

   g.draw(polygon);

 

}//end of drawStar

 

public void fillStar(double x1,double y1,int radius,int side)

{

   double teta=2.0*Math.PI/side;

   double R=radius;

   double r=radius*0.35;

   int xvalues[]=new int[2*side+2];

   int yvalues[]=new int[2*side+2];

   GeneralPath polygon=new GeneralPath(GeneralPath.WIND_EVEN_ODD,

   xvalues.length);

   double teta1,teta2;

   for(int i=0;i<=side;i++)

   {

     teta1=teta*i+Math.PI/2.0;

     teta2=teta/2.0+teta1;

     if(xlog!=0)

     {

     xvalues[2*i]= (int)(Math.floor(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/

          xminmaxlog*abswidth+R*Math.cos(teta1))));

     xvalues[2*i+1]= (int)(Math.floor(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/

          xminmaxlog*abswidth+r*Math.cos(teta2))));

     }

     else

     {

     xvalues[2*i]= (int)(Math.floor(xabsmin+(x1-xmin)/

          (xmax-xmin)*abswidth+R*Math.cos(teta1)));

     xvalues[2*i+1]= (int)(Math.floor(xabsmin+(x1-xmin)/

          (xmax-xmin)*abswidth+r*Math.cos(teta2)));

     }

     if(ylog!=0)

     {

     yvalues[2*i]= (int)(Math.floor(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/

          yminmaxlog*absheight-R*Math.sin(teta1))));

      yvalues[2*i+1]= (int)(Math.floor(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/

          yminmaxlog*absheight-r*Math.sin(teta2))));

     } 

     else

     {

     yvalues[2*i]= (int)(Math.floor(yabsmin+absheight-(y1-ymin)/

          (ymax-ymin)*absheight-R*Math.sin(teta1)));

     yvalues[2*i+1]= (int)(Math.floor(yabsmin+absheight-(y1-ymin)/

          (ymax-ymin)*absheight-r*Math.sin(teta2)));

     }

           

     if(i==side)

     {

     xvalues[2*i]=xvalues[0];

     yvalues[2*i]=yvalues[0];    

     }

   }

 

   for(int i=0;i<=2*side;i++)

   {

          if(i==0)

          {

          polygon.moveTo(xvalues[0],yvalues[0]);

          }

          else

          {

           polygon.lineTo(xvalues[i],yvalues[i]);

          }

   }

   g.fill(polygon);

}//end of drawStar

 

 

public void drawXTic(int ticNumber,double ticHeight,int ticSide)

{

        //draw a series of x axis tics

        double dtic=(xmax-xmin)/ticNumber;

        double x1=xmin;

        double y1=ymin;

        double dy;

        dy=ticHeight;       

        int xx1,yy1,yy2,yy3;

        for(int i=0;i<=ticNumber;i++)

        {             

                            if(xlog!=0)

        {xx1=(int)(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth));}

        else

        {xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth);}

                            yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight);

                            yy2=(int)(yabsmin+absheight-(y1-dy-ymin)/(ymax-ymin)*absheight);

                            yy3=(int)(yabsmin+absheight-(y1+dy-ymin)/(ymax-ymin)*absheight);

                            if(ticSide==0)

            {g.draw(new Line2D.Double( xx1,yy1,xx1,yy2));}

         else

            {g.draw(new Line2D.Double( xx1,yy1,xx1,yy3));}

            x1=x1+dtic;

        }

}

 

 

public void drawYTic(int ticNumber,double ticWidth,int ticSide)

{

        //draw a series of y axis tics

        double dtic=(ymax-ymin)/ticNumber;

        double x1=xmin;

        double y1=ymin;

        double dx;

        dx=ticWidth;       

        double xx1,xx2,xx3,yy1;

        for(int i=0;i<=ticNumber;i++)

        {if(ylog!=0) {yy1=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight));}

        else

        {yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight);}

                            xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth);

                            xx2=(int)(xabsmin+(x1-dx-xmin)/(xmax-xmin)*abswidth);

                            xx3=(int)(xabsmin+(x1+dx-xmin)/(xmax-xmin)*abswidth);     

                              if(ticSide==0)

          {g.draw(new Line2D.Double( xx1,yy1,xx2,yy1));}

          else

          {g.draw(new Line2D.Double( xx1,yy1,xx3,yy1));}

          y1=y1+dtic;

        }

}

 

public void drawXGrid(int ticNumber)

{

        //draw x gridlies |||||||

        double dtic=(xmax-xmin)/ticNumber;

        double x1=xmin;

        for(int i=0;i<=ticNumber;i++)

        {

          drawLine(0,x1,ymin,x1,ymax);

          x1=x1+dtic;

        }

}

 

public void drawYGrid(int ticNumber)

{

        //draw y gridlines =====

        double dtic=(ymax-ymin)/ticNumber;

        double y1=ymin;

        for(int i=0;i<=ticNumber;i++)

        {

          drawLine(0,xmin,y1,xmax,y1);

          y1=y1+dtic;

        }

}

 

public static String timetoString(double x)

{

int h=(int)x;

String h1="";

if(h<10) h1="0"+h;

else h1=""+h;

double x1=(x-h)*60;

int m=(int)(x1);

String m1="";

if(m<10) m1="0"+m;

else m1=""+m;

int s=(int)((x1-m)*60);

String s1;

if(s<10) s1="0"+s;

else s1=""+s;

String s2=h1+":"+m1+":"+s1;

return s2;                       

}

public void drawXString(int ticNumber)

{

        //draw x numbers

        Locale en=new Locale("US");

        double dtic=(xmax-xmin)/ticNumber;

        double x1=xmin;

        double y1=ymin;

        int xx1,yy1;

 

        String s;

        s="  ";

        for(int i=0;i<=ticNumber;i++)

        {  if(xlog!=0)

           {xx1=(int)(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth-abswidth/40.0));}

           else

           {xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth-abswidth/40.0);}

           if(ylog!=0)

           {yy1=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight)+absheight/20.0);}

           else

           {yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight+absheight/20.0);}

           s=timetoString(x1); //String.format(en,"%7.5g",x1);             

          //AffineTransform origTransform = g.getTransform();

          //g.translate(x1,y1);

           //g.rotate(90*Math.PI/180);

           g.drawString(s,xx1,yy1);

          x1=x1+dtic;

        }

} 

 

public void drawXNumbers(int ticNumber)

{

        //draw x numbers

        Locale en=new Locale("US");

        double dtic=(xmax-xmin)/ticNumber;

        double x1=xmin;

        double y1=ymin;

        int xx1,yy1;

        String s;

        s="  ";

        for(int i=0;i<=ticNumber;i++)

        {  if(xlog!=0)

           {xx1=(int)(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth-abswidth/40.0));}

           else

           {xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth-abswidth/40.0);}

           if(ylog!=0)

           {yy1=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight)+absheight/20.0);}

           else

           {yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight+absheight/20.0);}

           s=String.format(en,"%7.5g",x1);             

          g.drawString(s,xx1,yy1);

          x1=x1+dtic;

        }

}

 

 

public void drawYNumbers(int ticNumber)

{

        // draw y  numbers

        Locale en=new Locale("US");

        double dtic=(ymax-ymin)/ticNumber;

        double x1=xmin;

        double y1=ymin;

         int xx1,yy1;

        String s;

        s="  ";

        for(int i=0;i<=ticNumber;i++)

        {

          if(xlog!=0)

           {xx1=(int)(xabsmin+((Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth-abswidth/200.0)-abswidth/10.0);}

           else

           {xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth/200.0-abswidth/10.0);}

           if(ylog!=0)

           {yy1=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight));}

           else

           {yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight)+5;}

           s=String.format(en,"%6.4g",y1);          

           g.drawString(s,xx1,yy1);

          y1=y1+dtic;

        }

}

 

public void drawXLabel(String xLabel)

{

    // draw x labels

    double x1=xmin+(xmax-xmin)/2.0;

    double y1=ymin;

     int xx1,yy1;

    

    if(xlog!=0)

           {xx1=(int)(xabsmin+(Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth);}

           else

           {xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth);}

           if(ylog!=0)

           {yy1=(int)(yabsmin+absheight-(Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight+abswidth/12.0);}

           else

           {yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight+abswidth/12.0);}

    g.drawString(xLabel,xx1,yy1);

}

 

public void drawYLabel(String yLabel)

{

    // draw y labels

     AffineTransform origTransform = g.getTransform();

    double x1;

    double y1=ymax-(ymax-ymin)/2.0;

     int xx1,yy1;

           if(xlog!=0)

           {x1=xmin-2.7;xx1=(int)(xabsmin+(Math.log10(x1-xmin+10.0)-1.0)/xminmaxlog*abswidth);}

           else

           {x1=xmin-(xmax-xmin)/6.0;xx1=(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth);}

           if(ylog!=0)

           {yy1=(int)(yabsmin+absheight-((Math.log10(y1-ymin+10.0)-1.0)/yminmaxlog*absheight));}

           else

           {yy1=(int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight);}

           g.translate(xx1,yy1);

           g.rotate(3.0*Math.PI/2.0);

           g.drawString(yLabel,0,0);

           g.setTransform(origTransform);

}

 

public void drawLabel(String Label)

{

    //draw graphic label

    double x1=xmin+(xmax-xmin)/2.0;

    double y1=ymax;

    g.drawString(Label,(int)(xabsmin+(x1-xmin)/(xmax-xmin)*abswidth),

            (int)(yabsmin+absheight-(y1-ymin)/(ymax-ymin)*absheight)-(int)(abswidth/40.0));

}

 

public void drawAdditionalLabel(String s,double x1,double y1)

{

    //draw Additional graphic label

   drawString(s,x1,y1);

}

 

    public void drawMouseTic(double xi[],double yi[],int xn)

    {

                            for(int i=0;i<xn;i++)

                            {

                                               if((xi[i]>=xmin && xi[i]<=xmax) && (yi[i]>=ymin && yi[i]<=ymax)) { drawStar(xi[i],yi[i],(int)(abswidth/80.0),5); }

        }         

    }

public void drawPlotLine(int plottypei,double xi[],double yi[],char ch[])

{

int i=0;

int plottype[]=new int[1];

plottype[0]=plottypei;

int ni=xi.length;

int n[]=new int[1];

n[0]=ni;

double x[][]=new double[1][ni];

double y[][]=new double[1][ni];

for(int j=0;j<ni;j++)

{x[0][j]=xi[j];y[0][j]=yi[j];}

drawPlotLines(i,plottype,x,y,n,ch);             

}

 

public void drawPlotLine(int plottypei,double xi[],double yi[])

{

char ch[]=new char[1];

ch[0]='+';

int i=0;

int plottype[]=new int[1];

plottype[0]=plottypei;

int ni=xi.length;

int n[]=new int[1];

n[0]=ni;

double x[][]=new double[1][ni];

double y[][]=new double[1][ni];

for(int j=0;j<ni;j++)

{x[0][j]=xi[j];y[0][j]=yi[j];}

drawPlotLines(i,plottype,x,y,n,ch);             

}

   

public void drawPlotLines(int i,int plottype[],double x[][],double y[][],int n[],char ch[])

{

    int j;

//draw lines

    if((plottype[i] >= 0) && (plottype[i] < 10) )

    {     

                           switch ( plottype[i] )

       {

        case 0 : g.setStroke(new BasicStroke(1.0f));break;

        case 1 : g.setStroke(d1);break;

                            case 2 : g.setStroke(d2);break;

        case 3 : g.setStroke(d3);break;

        case 4 : g.setStroke(d4);break;

        case 5 : g.setStroke(new BasicStroke(2.0f));break;

        case 6 : g.setStroke(d5);break;

        case 7 : g.setStroke(d6);break;

        case 8 : g.setStroke(d7);break;

        case 9 : g.setStroke(d8);break;

        };

      for(j=0;j<n[i]-1;j++)

        {

        if((x[i][j]>=xmin && x[i][j]<=xmax )

          && (y[i][j]>=ymin && y[i][j]<=ymax))

        {

        if((x[i][j+1]>=xmin && x[i][j+1]<=xmax) &&

           (y[i][j+1]>=ymin && y[i][j+1]<=ymax))

           {

           drawLine(0,x[i][j],y[i][j],x[i][j+1],y[i][j+1]);

           }

        else if(x[i][j+1]>xmax)

           {

              double b=(y[i][j+1]-y[i][j])/(x[i][j+1]-x[i][j]);

              double  a=y[i][j]-b*x[i][j];

              drawLine(0,x[i][j],y[i][j],xmax,(a+b*xmax));

           }

        else if(y[i][j+1]>ymax)

           {

              double b=(y[i][j+1]-y[i][j])/(x[i][j+1]-x[i][j]);

              double a=y[i][j]-b*x[i][j];

              drawLine(0,x[i][j],y[i][j],(ymax-a)/b,ymax);

           }

        else if(x[i][j+1]>xmax && y[i][j+1]>ymax)

           {

              double b=(y[i][j+1]-y[i][j])/(x[i][j+1]-x[i][j]);

              double a=y[i][j]-b*x[i][j];

              drawLine(0,x[i][j],y[i][j],(ymax-a)/b,(a+b*xmax));

           }

        }

        else if((x[i][j+1]>=xmin && x[i][j+1]<=xmax )

          && (y[i][j+1]>=ymin && y[i][j+1]<=ymax))

        {

           if(x[i][j]<xmin)

           {

              double b=(y[i][j+1]-y[i][j])/(x[i][j+1]-x[i][j]);

              double  a=y[i][j+1]-b*x[i][j+1];

              drawLine(0,xmin,(a+b*xmin),x[i][j+1],y[i][j+1]);

           }

           if(y[i][j]<ymin)

           {

              double b=(y[i][j+1]-y[i][j])/(x[i][j+1]-x[i][j]);

              double  a=y[i][j+1]-b*x[i][j+1];

              drawLine(0,(ymin-a)/b,ymin,x[i][j+1],y[i][j+1]);

           }

        }

        }//end of for(j=0

      g.setStroke(new BasicStroke(1.0f));

      }//end of if(plottype

//draw characters

    else if(plottype[i]>=10 && plottype[i]<=19)

      {

        for(j=0;j<n[i];j++)

        {

          if((x[i][j]>=xmin && x[i][j]<=xmax )

          && (y[i][j]>=ymin && y[i][j]<=ymax))

             { drawChar(ch[i],x[i][j],y[i][j]); }

        }//end of for(j=0;

      }//end else if(plottype[i]==10..19)

//draw rectangles

    else if(plottype[i]==20)

      {

        for(j=0;j<n[i];j++)

        {

          if((x[i][j]>=xmin && x[i][j]<=xmax )

          && (y[i][j]>=ymin && y[i][j]<=ymax))

              { drawRect(x[i][j],y[i][j],abswidth/100,absheight/80); }

        }//end of for(j=0;

      }//end else if(plottype[i]==20)

      else if(plottype[i]==21)

      {

        for(j=0;j<n[i];j++)

        {

          if((x[i][j]>=xmin && x[i][j]<=xmax )

          && (y[i][j]>=ymin && y[i][j]<=ymax))

              { fillRect(x[i][j],y[i][j],abswidth/100,abswidth/80); }

        }//end of for(j=0;

      }//end else if(plottype[i]==20)

//draw circle

    else if(plottype[i]==22)

      {

        for(j=0;j<n[i];j++)

        {

          if((x[i][j]>=xmin && x[i][j]<=xmax )

          && (y[i][j]>=ymin && y[i][j]<=ymax))

            { drawEllipse(x[i][j],y[i][j],abswidth/100,absheight/80); }

        }//end of for(j=0;

      }//end else if(plottype[i]==22)

    else if(plottype[i]==23)

      {

        for(j=0;j<n[i];j++)

        {

          if((x[i][j]>=xmin && x[i][j]<=xmax )

          && (y[i][j]>=ymin && y[i][j]<=ymax))

            { fillEllipse(x[i][j],y[i][j],abswidth/100,absheight/80); }

        }//end of for(j=0;

      }//end else if(plottype[i]==21) 

    else if(plottype[i]>=24 && plottype[i]<=27)

      {

                           

        for(j=0;j<n[i];j++)

        { if((x[i][j]>=xmin && x[i][j]<=xmax )

          && (y[i][j]>=ymin && y[i][j]<=ymax))

             {

                                  drawPolygon(x[i][j],y[i][j],abswidth/100,(plottype[i]-21));

             }

        }//end of for(j=0;

      }//end else if(plottype[i]==24..27)

      else if(plottype[i]>=28 && plottype[i]<=31)

      {

                           

        for(j=0;j<n[i];j++)

        { if((x[i][j]>=xmin && x[i][j]<=xmax )

          && (y[i][j]>=ymin && y[i][j]<=ymax))

             {

                                  fillPolygon(x[i][j],y[i][j],abswidth/100,(plottype[i]-25));

             }

        }//end of for(j=0;

      }//end else if(plottype[i]==24..27)  

   else if(plottype[i]>=32 && plottype[i]<=35)

      {

                           

        for(j=0;j<n[i];j++)

        { if((x[i][j]>=xmin && x[i][j]<=xmax )

          && (y[i][j]>=ymin && y[i][j]<=ymax))

             {

                                  drawStar(x[i][j],y[i][j],abswidth/100,(plottype[i]-29));

             }

        }//end of for(j=0;

      }  

   else if(plottype[i]>=36 && plottype[i]<=39)

      {

                           

        for(j=0;j<n[i];j++)

        { if((x[i][j]>=xmin && x[i][j]<=xmax )

          && (y[i][j]>=ymin && y[i][j]<=ymax))

             {

                                  fillStar(x[i][j],y[i][j],abswidth/100,(plottype[i]-33));

             }

        }//end of for(j=0;

      }    

   else if(plottype[i]==40)

      {

                            

        for(j=0;j<n[i];j++)

        { if((x[i][j]>=xmin && x[i][j]<=xmax )

          && (y[i][j]>=ymin && y[i][j]<=ymax))

             {

                                  drawBar(x[i][j],y[i][j]);

             }

        }//end of for(j=0;

      }           

   else if(plottype[i]==41)

      {

                           

        for(j=0;j<n[i];j++)

        { if((x[i][j]>=xmin && x[i][j]<=xmax )

          && (y[i][j]>=ymin && y[i][j]<=ymax))

             {

                                  fillBar(x[i][j],y[i][j]);

             }

        }//end of for(j=0;

      }                  

}

 

}

 

EK 2 SQLite_Table.java programı ve veri tabanı programlama notları

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.table.*;

import java.sql.*;

public class SQLite_Table extends JFrame

{ JTextField hostField;

  JTextField tableField;

  JTextArea queryField;

  QueryTableModel qtm;

  String s="jdbc:sqlite:";

  static final long serialVersionUID = 8597941330711875390L;

  public SQLite_Table(String table_name) throws ClassNotFoundException

  {      super("SQLite veritabanı SQL tablo sorgusu");

                             Class.forName("org.sqlite.JDBC");

                             Connection connection = null;

    //addWindowListener(new BasicWindowMonitor());

         setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

        setSize(500,300);

    qtm=new QueryTableModel();

    JTable table=new JTable(qtm);

    JScrollPane scrollpane=new JScrollPane(table);

    JPanel p1=new JPanel();

    p1.setLayout(new GridLayout(3,2));

    p1.add(new JLabel(" veritabanı'nın ismini giriniz :"));

    p1.add(hostField=new JTextField("VT.db"));

    p1.add(new JLabel("SQL deyimini giriniz :"));

    p1.add(queryField=new JTextArea("select * from "+table_name));

    p1.add(new JLabel("veri tabanını gönderiniz:"));

    JButton jb=new JButton("veri tabanı sorgusunu çalıştırınız");

    jb.addActionListener(new ActionListener()

      {

      public void actionPerformed(ActionEvent e)

        {

        qtm.setHostURL(s+hostField.getText().trim());

        qtm.setQuery(queryField.getText().trim());

        }

      }); // jb.addActionlistener

  p1.add(jb);

  getContentPane().add(p1,BorderLayout.NORTH);

  getContentPane().add(scrollpane,BorderLayout.CENTER);

  } //DatabaseTest()

  public void setQuerry(String s)

  {qtm.setHostURL(s+hostField.getText().trim());

   qtm.setQuery(s.trim());

  }

  public static void main(String args[])

  { String table_name="VT1";

    try

    {

                         SQLite_Table tt=new SQLite_Table(table_name);

     tt.setVisible(true);

    } catch(ClassNotFoundException e)

    {

      // "out of memory" mesaj? veri taban?n?n bulunamad??? anlam?na gelir

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

    }

  }

}

 

SQLite VERİTABANI

SQLite çok çeşitli şekillerde rahatlıkla kullanabileceğimiz bir veri tabanıdır. Veri tabanlarını öğrenmek için de öğrencilere iyi bir başlangıç ortamı sunar. Çeşitli ortamlarda, bilgisayarınızda direk olarak, internet üzerinden kullanılabilir. Veri tabanımız http://www.sqlite.org/download.html adresinden indirilebilir. Bu sitede doküman kütüphaneleri, C ile yazılmış orijinal kodlar ve çeşitli bilgisayar sistemlerinde çalışan derlenmiş binary kodlar bulunmaktadır.

 

 

Siteden yükleyeceğimiz sqlite-dll-win32-x86-3070800.zip dosyasını açarsak sqlite3.exe dosyasını bulacağız, bu dosyayı dos ortamında çalıştırabiliriz.  SQLite veritabanı programını java’ya iki türlü bağlayabiliriz. İlki wrapper denilen direk olarak java anadil programlamasıyla (C dilinde)  yazılmış programlar aracılığıyla SQLite veri tabanı kullanımını oluşturmaktır.  Bunlara en iyi örnek olarak http://code.google.com/p/sqlite4java adresinde verilen sqlite4java verilebilir. Bu programı bilgisayarınıza yüklemek için önce sqlite4java-282.zip sıkıştırılmış dosyasını yükleyiniz.  Bu dosyayı açıp içindeki  sqlite4java.jar  dosyasını JAVA_HOME/jre/lib/ext  dizinine atınız.  Sıkıştırılmış dosyada bulunan sqlite4java-win32-x64.dll  (Windows 64 bit bilgisayar) veya sqlite4java-win32-x86.dll (Windows 32 bit bilgisayar) dosyasını  JAVA_HOME/jre/bin  dizinine kopyalayınız. Veri tabanı ile bağlantı kurmak içinde import com.almworks.sqlite4java.*;  deyimini kullanınız. Diğer yol ise javanın veri tabanlarına bağlanmak için geliştirdiği Java Data Base Connectivity _JAVA Veri tabanı bağlanma sistemi (JDBC) denilen sınıflar üzerinden yapmaktır. JDBC örneği olarak http://www.xerial.org/maven/repository/artifact/org/xerial/sqlite-jdbc/3.7.2/ sitesinde bulunan sqlite-jdbc-3.7.2.jar dosyasını kullanılarak gerçekleştirilebilir. Bu paketi kullanabilmemiz için jar dosyasını JAVA_HOME/jre/lib/ext dizinine kopyelemeniz yeterli olacaktır.  Bu pakete bağlanmak için standart java ODBC paketi olan import java.sql.Connection;  deyimini kullanmak yeterli olacaktır. Diğer paketlerin kullanımları biraz daha farklıdır, ilgilenenler lütfen internet sitelerine müracat etsinler. Şimdi önce SQLite3 kullanarak dos ortamında SQLite veri tabanını ve çeşitli deyimlerine göz atalım. Oluşturacağımız veri tabanının ismi temp olsun. Oluşturduğumuz veri tabanında yeni veri tabanı tablosu oluşturmamız gerekir. Bunun için create table SQL komutunu kullanıyoruz.

 

 

.separator , komutu verinin virgül (,) ile ayrılacağını belirtti, .import komutu da veriyi veri.txt dosyasından okudu. Burada dosyada verilen alan sayısı ve tiplerinin veri tabanı tablosu tanımında verilenle aynı olması gerektiğini hatırlatalım. Veri dosyası içeriği:

 

 

Veri dosyasından çıktı almak için select * form KAHVE komutunu kullandık. Veriyi dosyadan okuma yerine direk olarak kendimiz de girebiliriz. Bunun için insert into SQL komutunu kullanabiliriz.

 

Select deyiminin en genel yapısı şu şekildedir.

SELECT [DISTINCT|ALL] {*| liste}

FROM    [tablo ismi][, ikinci tablo ismi]….

[WHERE şart deyimi]

[GROUP BY kolon liste]

[HAVING şart deyimi]

[ORDER BY kolon liste]

 

Bu tanımlamada DISTINCT terimi veri tablosunda yinelenen değerler varsa onların tek olarak gelmesini sağlar. Eğer ALL terimi kullanılırsa tüm veri gelir.

Eğer * terimi kullanılmışsa tüm tablo kolonları listelenir. Bunun yerine sadece listelenmesini istediğimiz kolonları verebiliriz.

WHERE deyime java’daki if deyiminin benzeridir.  Bu deyimi kullanarak tablodan seçim yapabiliriz.

Select komutunu kullanırken if yapısına benzer seçim kriterleri kullanabiliyoruz. Örneğin

Select * from KAHVE where fiyat>10 and fiyat<15;

Deyimi fiyatı 10 ila 15 TL arasında olan kahveleri seçer.

 

Where ile kullanılabilen mantıksal seçim deyimleri şunlardır:

AND  ve

OR    veya

NOT  değil

BETWEEN  (genellikle AND deyimi ile birlikte kullanılır  örneğin BETWEEN 20 AND 30 20 ile 30 arasında seçim yapar)

IN içinde

LIKE  (String değişkenleri için eşittir deyimi

 LIKE ‘%ali%’ içinde ali olan tüm deyimleri bulur

NULL : boş

ANY herhangibir değer

ALL hepsi

EXIST mevcutsa

Rakamsal karşılaştırmalarda:

=            : eşittir

<>          : eşit değildir

>            : büyüktür

<            : küçüktür

>=          : büyük veya eşittir

<=          : küçük veya eşittir

 ORDER BY deyimi veriyi sıraya sokar. Eğer ASC kullanıldıysa küçükten büyüğe doğru sıralanır, eğer DESC kullanıldıysa küçükten büyüğe doğru sıraya sokar.

Eğer String türü bir karşılaştırma gerekiyorsa like terimini kullanabiliriz.

Diğer önemli bir SQL komutu hesaplama yapmakta kullandığımız set komutudur. Bu komutla yeni bir hesap yaparak daha önceden tanımlanmış bir kolona veya yeniden oluşturulacak bir kolona veri aktarılabilir. Örneğimizde toplam kolonunun değerleri hesaplanmıştır.

Bir tabloyu silmek için drop table komutu kullanırız.

Tüm veri tabanını silmek içinse drop database terimini kullanırız.

Şimdi SQLite programlamayı java ortamında yapmak için örneklere bakalım. Başlangıç bölümünde java için SQLite kurulumundan bahsetmiştik. Burada tekrar yinelemeye gerek görmüyoruz. İlk örnek olarak üsteki eksersizin benzerini java ortamında gerçekleştirelim. Bu ilk java programımızda temel olarak Java Data Base Connectivity _JAVA Veri tabanı bağlanma sistemi (JDBC) kullanılacaktır.

 

Program 12.1-1 KAHVEjava

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

 

 

public class KAHVE

{

  public static void main(String[] args) throws ClassNotFoundException

  {

    //  sqlite-JDBC sürücüsünü yükle

    Class.forName("org.sqlite.JDBC");  

    Connection connection = null;

    try

    {

      // veritabanı ile bağlantı kur.

      connection = DriverManager.getConnection("jdbc:sqlite:temp.db");

      Statement statement = connection.createStatement();

      statement.setQueryTimeout(30);  // set timeout to 30 sec.

     

      statement.executeUpdate("drop table if exists KAHVE");

      statement.executeUpdate("create table KAHVE(isim String, kot int, fiyat double, miktar int,toplam double)");

      statement.executeUpdate("insert into KAHVE values('Espresso',150,9.99,110,0);");

      statement.executeUpdate("insert into KAHVE values('Venezuella',173,12.99,57,0);");

      statement.executeUpdate("insert into KAHVE values('Brezilya',123,12.99,30,0);");

      statement.executeUpdate("insert into KAHVE values('Kolombia',111,15.99,20,0);");

      statement.executeUpdate("update KAHVE set toplam=fiyat*miktar;");    

      ResultSet rs = statement.executeQuery("select * from KAHVE");

      while(rs.next())

      {

        // read the result set

        System.out.print("KAHVE İSMİ = " + rs.getString("isim"));

        System.out.print(" KOT = " + rs.getInt("kot"));

        System.out.print(" FİYAT = " + rs.getDouble("fiyat"));

        System.out.print(" MİKTAR = " + rs.getInt("miktar"));

        System.out.println(" TOPLAM = " + rs.getDouble("toplam"));

      }

    }

    catch(SQLException e)

    {

      // if the error message is "out of memory",

      // it probably means no database file is found

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

    }

    finally

    {

      try

      {

        if(connection != null)

          connection.close();

      }

      catch(SQLException e)

      {

        // connection close failed.

        System.err.println(e);

      }

    }

  }

}

 

---------- Capture Output ----------

> "D:\java\bin\javaw.exe" KAHVE

KAHVE İSMİ = Espresso KOT = 150 FİYAT = 9.99 MİKTAR = 110 TOPLAM = 1098.9

KAHVE İSMİ = Venezuella KOT = 173 FİYAT = 12.99 MİKTAR = 57 TOPLAM = 740.43

KAHVE İSMİ = Brezilya KOT = 123 FİYAT = 12.99 MİKTAR = 30 TOPLAM = 389.7

KAHVE İSMİ = Kolombia KOT = 111 FİYAT = 15.99 MİKTAR = 20 TOPLAM = 319.8

 

> Terminated with exit code 0.

 

Programdan da görüldüğü gibi SQLite veritabanı programına JDBC olarak      

Class.forName("org.sqlite.JDBC");   deyimiyle bağlanıldı. Veri tabanı temp.db ye bağlanmak için:

Connection connection == DriverManager.getConnection("jdbc:sqlite:temp.db"); terimi kullanıldı. Veri tabanımızın ismi temp.db’dir. veri tabanı tablomuzun ismi de KAHVE olarak tanımlandı.

 

İkinci örneğimizde KAHVE.java programında JDBC olarak verilen kodun SQLite4 wrapper paketi için yazılmış eşdeğeri verilmektedir.

Program 12.1-2 KAHVE1.java (SQLite wrapper program using SQlite4)

 import com.almworks.sqlite4java.*;

import java.io.*;

 

public class KAHVE1

{

public static void main(String arg[]) throws SQLiteException

{

SQLiteConnection db = new SQLiteConnection(new File("/temp"));

db.open(true);

db.exec("drop table if exists KAHVE");

db.exec("create table KAHVE(isim String, kot int, fiyat double, miktar int,toplam double)");

db.exec("drop table if exists KAHVE");

db.exec("create table KAHVE(isim String, kot int, fiyat double, miktar int,toplam double)");

db.exec("insert into KAHVE values('Espresso',150,9.99,110,0);");

db.exec("insert into KAHVE values('Venezuella',173,12.99,57,0);");

db.exec("insert into KAHVE values('Brezilya',123,12.99,30,0);");

db.exec("insert into KAHVE values('Kolombia',111,15.99,20,0);");

db.exec("update KAHVE set toplam=fiyat*miktar;");

SQLiteStatement statement = db.prepare("select * from KAHVE");

String isim;

int kot;

double fiyat;

int miktar;

double toplam;

try {

      while (statement.step()) {

        isim=statement.columnString(statement.getBindParameterIndex("isim"));

        kot=statement.columnInt(statement.getBindParameterIndex("kot"));

        fiyat=statement.columnDouble(statement.getBindParameterIndex("fiyat"));

        miktar=statement.columnInt(statement.getBindParameterIndex("miktar"));

        toplam=statement.columnDouble(statement.getBindParameterIndex("toplam"));

        System.out.print("KAHVE İSMİ = " + isim);

        System.out.print(" KOT = " + kot);

        System.out.print(" FİYAT = " + fiyat);

        System.out.print(" MİKTAR = " + miktar);

        System.out.println(" TOPLAM = " + toplam);

      }

    } finally {

      statement.dispose();

    }

 

}

 

---------- Capture Output ----------

> "D:\java\bin\javaw.exe" KAHVE1

Oca 21, 2013 12:12:12 PM com.almworks.sqlite4java.Internal log

INFO: [sqlite] DB[1]: instantiated [\temp]

Oca 21, 2013 12:12:12 PM com.almworks.sqlite4java.Internal log

INFO: [sqlite] Internal: loaded sqlite4java-win32-x86 from system path

Oca 21, 2013 12:12:12 PM com.almworks.sqlite4java.Internal log

INFO: [sqlite] Internal: loaded sqlite 3.7.10, wrapper 0.2

Oca 21, 2013 12:12:12 PM com.almworks.sqlite4java.Internal log

INFO: [sqlite] DB[1]: opened

KAHVE İSMİ = Espresso KOT = 150 FİYAT = 9.99 MİKTAR = 110 TOPLAM = 1098.9

KAHVE İSMİ = Venezuella KOT = 173 FİYAT = 12.99 MİKTAR = 57 TOPLAM = 740.4300000000001

KAHVE İSMİ = Brezilya KOT = 123 FİYAT = 12.99 MİKTAR = 30 TOPLAM = 389.7

KAHVE İSMİ = Kolombia KOT = 111 FİYAT = 15.99 MİKTAR = 20 TOPLAM = 319.8

 

> Terminated with exit code 0.

 

Programdan da görüleceği gibi, burada veri tabanı sistemine bağlanmak için

import com.almworks.sqlite4java.*; komutu kullanılmıştır. Veri tabanını açmak ve SQL deyimlerini çalıştırmak için SQLiteConnection sınıfı kullanıldı. Veri tabanından verileri java’ya aktarmak için ise SQLiteStatement sınıfından yararlanıldı. Görüldüğü gibi temel komutlar farklı olmakla beraber veriye bağlanma ve çağırma prosesi oldukça benzerdir.

 

EK 3 Analog saat çıktı göstergesi programları

//=======================================================//

//JAVA-ARDUINO veri sistem entagrasyonu                                                       //

// analog yuvarlak çıktı göstergesi                                                                           //

// analogDialP                                                                                                         //

// M. Turhan Coban                                                                                                //

//=======================================================//

// Girdi Değişken listesi

// String name : gösterge ismi

// String unit : gösterge birim

// double minx: gösterge minimum rakam

// double maxx: gösterge maksimum rakam

// double minteta : gösterge minimum rakam açısı (radyan)

// double maxtetai: gösterge maksimum rakam açısı (radyan)

// int ni : rakamların da gösterildiği büyük skala bölüm sayısı

// int n1i: küçük skala bölüm sayısı

import javax.swing.*;

import java.awt.Graphics;

import java.awt.*;

 import java.awt.event.*;

 import java.awt.geom.*;

 import javax.swing.*;

 import java.net.*;

 import java.io.*;

 import java.awt.Graphics;

 import java.util.*;

 import java.text.*;

 import java.util.Locale;

 import java.awt.image.*;

 

 import java.awt.Font;

import java.awt.Graphics2D;

import java.awt.RenderingHints;

 

 

import java.awt.geom.*;

import java.awt.font.*;

 

// ============

public class analogDialP extends JPanel

{ private static final long serialVersionUID = 756764376L;

  double x,minx,maxx;

  double minteta,maxteta;

  int n;

  int n1;

  polar p;

  double angle1,angle2,angle3;

  String name;

  String unit;

  public analogDialP(String namei,String uniti,double minxi,double maxxi,double mintetai,double maxtetai,int ni,int n1i)

  {

                         

   name=namei;

   unit=uniti;                   

   minx=minxi;

   maxx=maxxi;

   minteta=mintetai;

   maxteta=maxtetai;

   x=minx;

   n=ni;

   n1=n1i;

   angle1=minteta;

   angle2=maxteta;

  

  }

 

  public void setx(double xi)

  {x=xi;}

 

public  void drawPlotLabel(Graphics g2,String s, int xi,int yi,int R1i)

{Graphics2D g=(Graphics2D)g2;

 int x1,y1;

 int R1=R1i;

 x1=xi+R1;

 y1=yi+R1;

 g.drawString(s,x1,y1);

 //AffineTransform origTransform = g.getTransform();

 //g.translate(x1,y1);

 //g.rotate(90*Math.PI/180);

 //g.drawString(s,0,0);

 //g.setTransform(origTransform);

 //g.drawString("xxxxxxxxxxxxx",0,0);

}

 

public  void drawLabel1(Graphics g2,int xi,int yi,int R1i)

{

   double angle;

   Graphics2D g=(Graphics2D)g2;

   double R1=R1i;

   polar P1=new polar();

   int x[]=new int[n];

   int y[]=new int[n];

   GeneralPath polygon=new GeneralPath(GeneralPath.WIND_EVEN_ODD,

   x.length);

   int x1,y1;

   double teta=(maxteta-minteta)/n;

   double dx=(maxx-minx)/n;

 

   for(double xx=minx;xx<=maxx;xx+=dx)

   { angle=(xx-minx)/(maxx-minx)*(maxteta-minteta)+minteta;

     double teta1=-angle+Math.PI*3.0/2.0;

     //System.out.println("xx="+xx+"angle="+angle+"teta1="+teta1);

     P1.polar_input(R1+20,teta1);

     x1=(xi+(int)P1.xi());

     y1=(yi+(int)P1.xj());

    

    

     if(teta1>Math.PI/2.0 && teta1<3.0*Math.PI/2.0)

     {  x1=(xi+(int)P1.xi())-40;

     }

     else

     {

        x1=(xi+(int)P1.xi());

     }

     if(teta1>Math.PI && teta1<2.0*Math.PI)

     { y1=(yi-(int)P1.xj())+10;}

     else

       { y1=(yi-(int)P1.xj());}

    

    g.setFont(new Font("Serif",Font.BOLD,18));

    g.drawString(toString(xx,6,3),x1,y1);

   }

 

}

public  void drawLabel(Graphics g2,int xi,int yi,int R1i)

{

   double angle;

   Graphics2D g=(Graphics2D)g2;

   double R1=R1i;

   polar P1=new polar();

   polar P2=new polar();

   int x[]=new int[n];

   int y[]=new int[n];

   int x1,y1;

   double teta=(maxteta-minteta)/n;

   double teta2;

   double dx=(maxx-minx)/n;

   g.setFont(new Font("Serif",Font.BOLD,18));

   AffineTransform at;

   AffineTransform origTransform = g.getTransform();

   for(double xx=minx;xx<=maxx;xx+=dx)

   { angle=(xx-minx)/(maxx-minx)*(maxteta-minteta)+minteta;

     double teta1=-angle+Math.PI*3.0/2.0;

     teta2=angle+Math.PI/2.0-Math.PI/40.0;

     // dik yazı istersek

     // teta2=angle+Math.PI/2.0+Math.PI/80.0;

     P1.polar_input(R1,teta2);

     x1=(xi+(int)P1.xi());

     y1=(yi+(int)P1.xj());

     g.translate(x1,y1);

     g.rotate(teta2+Math.PI/2.0);

     // dik yazı istersek

     // g.rotate(teta2);

     g.drawString(toString(xx,4,1),0,0);

     g.setTransform(origTransform);

     //TextLayout t=new TextLayout(toString(xx,5,1),g.getFont(),g.getFontRenderContext());

     //at=AffineTransform.getRotateInstance(teta1,x1,y1);

     //g.setTransform(at);

     //t.draw(g,x1,y1);

     //at=AffineTransform.getRotateInstance(0,0,0);

     //g.setTransform(at);

     //g.translate(x1,y1);

     //g.rotate(angle);

     //t.draw(g,x1,y1);

     //g.setTransform(origTransform);

     //g.drawText(toString(xx,5,1));

     /*

     if(teta1>Math.PI/2.0 && teta1<3.0*Math.PI/2.0)

     {  x1=(xi+(int)P1.xi())-40;

     }

     else

     {

        x1=(xi+(int)P1.xi());

     }

     if(teta1>Math.PI && teta1<2.0*Math.PI)

     { y1=(yi-(int)P1.xj())+10;}

     else

       { y1=(yi-(int)P1.xj());}

     */

 

     //g.drawString(toString(xx,5,1),x1,y1);

   }

 

} //drawAkrep metodu sonu

 

public static String toString(double left, int w, int d)

// converts a double to a string with given width and decimals.

{

                        NumberFormat df=NumberFormat.getInstance(Locale.US);

                        df.setMaximumFractionDigits(d);

    df.setMinimumFractionDigits(d);

    df.setGroupingUsed(false);

    String s = df.format(left);

    while (s.length() < w)

      s = " " + s;

    if (s.length() > w)

    {

        s = "";

        for (int i=0; i<w; i++)

          s = s + "-";

    }

    return s;

}   

public  void drawLine(Graphics g2,int xi,int yi,int R1i,int R2i,int ni)

{

   double angle;

   Graphics2D g=(Graphics2D)g2;

   double R1=R1i;

   double R2=R2i;

   polar P1=new polar();

   polar P2=new polar();

   int x[]=new int[ni];

   int y[]=new int[ni];

   GeneralPath polygon=new GeneralPath(GeneralPath.WIND_EVEN_ODD,

   x.length);

   double teta=(maxteta-minteta)/ni;

   double dx=(maxx-minx)/ni;

   for(double xx=minx;xx<=maxx;xx+=dx)

   { angle=(xx-minx)/(maxx-minx)*(maxteta-minteta)+minteta;

     double teta1=-angle+Math.PI*3.0/2.0;

     P1.polar_input(R1,teta1);

     P2.polar_input(R2,teta1);

     polygon.moveTo((xi+(int)P1.xi()),(yi-(int)P1.xj()));

     polygon.lineTo((xi+(int)P2.xi()),(yi-(int)P2.xj()));

   }

   g.draw(polygon);

} //drawAkrep metodu sonu

 

 

   

public  void drawAkrep(Graphics g2,int xi,int yi,int Ri)

{

   double angle=(x-minx)/(maxx-minx)*(maxteta-minteta)+minteta;

   Graphics2D g=(Graphics2D)g2;

   double R=Ri;

   double r=Ri*0.3;

   polar P1=new polar();

   polar P2=new polar();

   polar P3=new polar();

   int x[]=new int[5];

   int y[]=new int[5];

   GeneralPath polygon=new GeneralPath(GeneralPath.WIND_EVEN_ODD,

   x.length);

   x[0]=xi;

   y[0]=yi;

   x[4]=xi;

   y[4]=yi;

   double teta=Math.PI/10.0;

     double teta1=-angle+Math.PI*3.0/2.0;

     double teta2=teta1+teta/2.0;

     double teta3=teta1-teta/2+Math.PI*2;

     P1.polar_input(R,teta1);

     P2.polar_input(r,teta2);

     P3.polar_input(r,teta3);

     x[1]=xi+(int)P3.xi();

     y[1]=yi-(int)P3.xj();

     x[2]=xi+(int)P1.xi();

     y[2]=yi-(int)P1.xj();

     x[3]=xi+(int)P2.xi();

     y[3]=yi-(int)P2.xj();

   for(int i=0;i<5;i++)

   {

          if(i==0)

          {

          polygon.moveTo(x[0],y[0]);

          }

          else

          {

           polygon.lineTo(x[i],y[i]);

          }

   }

   g.draw(polygon);

 

} //drawAkrep metodu sonu

public  void fillAkrep(Graphics g2,int xi,int yi,int Ri)

{

   double angle=(x-minx)/(maxx-minx)*(maxteta-minteta)+minteta;

   Graphics2D g=(Graphics2D)g2;

   double R=Ri;

   double r=Ri*0.3;

   polar P1=new polar();

   polar P2=new polar();

   polar P3=new polar();

   int x[]=new int[5];

   int y[]=new int[5];

   GeneralPath polygon=new GeneralPath(GeneralPath.WIND_EVEN_ODD,

   x.length);

   x[0]=xi;

   y[0]=yi;

   x[4]=xi;

   y[4]=yi;

   double teta=Math.PI/10.0;

     double teta1=-angle+Math.PI*3.0/2.0;

     double teta2=teta1+teta/2.0;

     double teta3=teta1-teta/2+Math.PI*2;

     P1.polar_input(R,teta1);

     P2.polar_input(r,teta2);

     P3.polar_input(r,teta3);

     x[1]=xi+(int)P3.xi();

     y[1]=yi-(int)P3.xj();

     x[2]=xi+(int)P1.xi();

     y[2]=yi-(int)P1.xj();

     x[3]=xi+(int)P2.xi();

     y[3]=yi-(int)P2.xj();

   for(int i=0;i<5;i++)

   {

          if(i==0)

          {

          polygon.moveTo(x[0],y[0]);

          }

          else

          {

           polygon.lineTo(x[i],y[i]);

          }

   }

   g.fill(polygon);

 

} //drawAkrep metodu sonu

 

 

public static void drawDaire(Graphics g2, int xi,int yi, int R)

{

   Graphics2D g=(Graphics2D)g2;

   g.draw(new Ellipse2D.Double((xi-R),(yi-R),2*R,2*R));

}

 

public static void fillDaire(Graphics g2, int xi,int yi, int R)

{

   Graphics2D g=(Graphics2D)g2;

   g.fill(new Ellipse2D.Double((xi-R),(yi-R),2*R,2*R));

}

     public TexturePaint getImageTexture(String imageFile,int xi,int yi, int R)

    {

    URL url = getClass().getResource(imageFile);

    Image img = getToolkit().getImage(url);

    try {

      MediaTracker tracker = new MediaTracker(this);

      tracker.addImage(img, 0);

      tracker.waitForID(0);

    } catch (Exception e) {}

    int width = 2*R;

    int height = 2*R;

    BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    Graphics g = buffImg.getGraphics();

    g.drawImage(img,-30,-20, this);

    Rectangle2D rect = new Rectangle((xi-R),(yi-R), width, height);

    return new TexturePaint(buffImg, rect);

    }

 

  public void paintComponent(Graphics g)

  {

  final Graphics2D g2 = (Graphics2D) g;

  g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

  RenderingHints.VALUE_ANTIALIAS_ON); 

  try{

                         final BasicStroke s1 = new BasicStroke(1);

                         final BasicStroke s2 = new BasicStroke (2);

     final BasicStroke s10 = new BasicStroke (10);

     FontMetrics metrics=g.getFontMetrics();

     //System.out.println(metrics.getAscent());

     //System.out.println(metrics.getDescent());

     //System.out.println(metrics.getHeight());

     int xi=150;

     int yi=120;

     int R1=85;

     int R2=80;

     int R3=75;

     g2.setColor(Color.yellow);    

     TexturePaint tp = getImageTexture("arduino.jpg",xi,yi,R1);

     g2.setPaint(tp);   

     star.fillDaire(g2,xi,yi,R1);

     g2.setColor(Color.red);

     fillAkrep(g2,xi,yi,R2);

     g2.setColor(Color.black);

 

     g2.setStroke (s2);

     g2.setPaint (Color.black);

     drawDaire(g2,xi,yi,R1);