Java + Arduino

Há uma IDE que permite a progrmação em Arduino, e li na internet que é possivel fazer o mesmo pelo java com a biblioteca rxtx, tudo bem consegui conectar e tudo mais, mas como faço os códigos da IDE arduino em Java tipo:

void setup() {                
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);     
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

Como fazer isso acima no java com a RXTX?

[quote=Dario Ribeiro]Há uma IDE que permite a progrmação em Arduino, e li na internet que é possivel fazer o mesmo pelo java com a biblioteca rxtx, tudo bem consegui conectar e tudo mais, mas como faço os códigos da IDE arduino em Java tipo:

void setup() {                
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);     
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

Como fazer isso acima no java com a RXTX?

[/quote]

Onde tu viu isso??

Pelo que sei e faço, é conectar o arduino ao pc e utilizar a biblioteca serial RxTx para enviar comandos via código java pela porta serial para o arduino, ex: acender um led.

Claro Claro ! Mas eu não to entendendo porque meus dados não coincidem, por exemplo, eu mando o arduino captar dados de um sensor de luminosidade LDR, na IDE do arduino mesmo que é programação em C eu acho, então ele me provê valores iguais a 200, 230, 211.

Quando faço isso no java, conecto ao java e tento captar dados do sensor ldr, ele me retorna valores 50, 11, 20, 10, nunca são iguais ao da IDE arduino.

Então penso como vou fazer meu projeto captando informações erradas.

Eu uso windows, dai minha porta serial COM3.

Como eu declaro no java a entrada analogia ou digital que to usando?

Isso tudo é novo pra mim, to entendendo aos poucos e to no estudo ja faz uns 3 dias…Complexo.

olha, normalment eu utilizo mais a onexão no arduino por usb
agora são varias coisas levadas em questão…
qual o modelo da sua placa?
vc execultou o metodo run() ou apenas o inicio em setup()?
instalou corretamente a placa por serial?
configurou ela pra reconhecer programação java como padrão?
tem tudo isso pra ser verificado…

Você já parou para pensar que os bits na java e na linguagem c são diferentes!? litle endian e big endian. Não será isso?

[quote]olha, normalment eu utilizo mais a onexão no arduino por usb
agora são varias coisas levadas em questão…
qual o modelo da sua placa?
vc execultou o metodo run() ou apenas o inicio em setup()?
instalou corretamente a placa por serial?
configurou ela pra reconhecer programação java como padrão?
tem tudo isso pra ser verificado…[/quote]

Modelo UNO da placa arduino.
Não entendi essa do run().
Sim instalei corretamente a placa serial.
Não sei configurar pra ser java a padrao.

Pode ser que seja, mas como vou fazer pra concertar isso?

[quote=Dario Ribeiro][quote]olha, normalment eu utilizo mais a onexão no arduino por usb
agora são varias coisas levadas em questão…
qual o modelo da sua placa?
vc execultou o metodo run() ou apenas o inicio em setup()?
instalou corretamente a placa por serial?
configurou ela pra reconhecer programação java como padrão?
tem tudo isso pra ser verificado…[/quote]

Modelo UNO da placa arduino.
Não entendi essa do run().
Sim instalei corretamente a placa serial.
Não sei configurar pra ser java a padrao.

Pode ser que seja, mas como vou fazer pra concertar isso?[/quote]

Linguagem c possui bytes não sinalizados (0…255)
a java possui bytes sinalizados(-127…128)

o primeiro bit na java é usado como sinal.

você pode mapear um inteiro que possui 4bytes. Assim sendo cabe o byte inteiro do c ali. Agora o problema é dentro da api. então você converterá os valores:

Ento para coincidir dados eu apenas devo pegar os dados recebidos em java tipo 50 e converter?

Isso. Mas não tenho certeza se o seu problema realmente é esse. Dá uma estudada nisso.

Cara, coloca o código que tu fez para o arduino e também em java aqui e resolveremos.

Bom para o Arduino eu criei um Sketch que faz o led piscar, simples:


int led = 13;

void setup() {                
  pinMode(led, OUTPUT);     
}
void loop() {
  digitalWrite(led, HIGH);   
  delay(1000);               
  digitalWrite(led, LOW);   
  delay(1000);            
}

Para o java criei uma classe para fazer a conexão e a partir disso eu não sei mais o que fazer, pois ela retorna valores desiguais… e ainda retorna 2 valores, sendo que so tem 1 led ^^


import javax.swing.JFrame;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

public final class Principal extends JFrame implements SerialPortEventListener {

    private CommPortIdentifier portId = null;
    private SerialPort port = null;
    private InputStream input;
    //private SerialPort serialPort;
    private int valor1, valor2;

    public Principal() {
        initComponents();
        jButton2.setEnabled(false);
        jButton3.setEnabled(false);
    }

    public void abrirPorta() throws NoSuchPortException, PortInUseException,
            UnsupportedCommOperationException {
        portId = CommPortIdentifier.getPortIdentifier("COM3");
        port = (SerialPort) portId.open(this.getClass().getName(), 2000);
        port.setSerialPortParams(9600, SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    }

    public void fecharPorta() throws IOException {
        //input.close();
        port.removeEventListener();
        port.close();
        port = null;
    }

    public void lerDados() throws IOException {
        input = port.getInputStream();
        //while (true) {

        //while (input.available() > 0) {
        valor1 = input.read();
        valor2 = input.read();
        //System.out.println(valor1);
        //}
        //}
        
        jLabel1.setText(String.valueOf(valor1));
        jLabel2.setText(String.valueOf(valor2));
        System.out.println("v1: "+valor1);
        System.out.println("v2: "+valor2);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("jLabel1");

        jButton1.setText("Abrir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Ler");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Fechar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel2.setText("jLabel2");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(128, 128, 128)
                        .addComponent(jButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2)
                        .addGap(27, 27, 27)
                        .addComponent(jButton3))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(45, 45, 45)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))))
                .addContainerGap(60, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(42, 42, 42)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addGap(38, 38, 38)
                .addComponent(jLabel1)
                .addGap(33, 33, 33)
                .addComponent(jLabel2)
                .addContainerGap(136, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            abrirPorta();
        } catch (NoSuchPortException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (PortInUseException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedCommOperationException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
        jButton1.setEnabled(false);
        jButton2.setEnabled(true);
        jButton3.setEnabled(true);
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        if (port != null) {
            try {
                lerDados();
            } catch (IOException ex) {
                Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        if (port != null) {
            try {
                fecharPorta();
            } catch (IOException ex) {
                Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        jButton1.setEnabled(true);
        jButton2.setEnabled(false);
        jButton3.setEnabled(false);
    }                                        
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration                   

    public synchronized void close() {
        if (port != null) {
            port.removeEventListener();
            port.close();
        }
    }

    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                abrirPorta();
                lerDados();
                fecharPorta();
            } catch (Exception e) {
                System.out.println(e.toString());
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }

    public static void main(String[] args) throws NoSuchPortException, PortInUseException, IOException,
            UnsupportedCommOperationException {
        new Principal().setVisible(true);
    }
}

Espero que consigam me ajudar, obrigado desde ja pela atenção !

[quote=Dario Ribeiro]Bom para o Arduino eu criei um Sketch que faz o led piscar, simples:


int led = 13;

void setup() {                
  pinMode(led, OUTPUT);     
}
void loop() {
  digitalWrite(led, HIGH);   
  delay(1000);               
  digitalWrite(led, LOW);   
  delay(1000);            
}

[/quote]

Não está faltando coisa aqui, tu não configurou a conexão serial ainda, e onde você recebe o que vem do Java???
Leia aqui: http://arduino.cc/en/Reference/Serial

[quote=Dario Ribeiro]

Para o java criei uma classe para fazer a conexão e a partir disso eu não sei mais o que fazer, pois ela retorna valores desiguais… e ainda retorna 2 valores, sendo que so tem 1 led ^^


import javax.swing.JFrame;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

public final class Principal extends JFrame implements SerialPortEventListener {

    private CommPortIdentifier portId = null;
    private SerialPort port = null;
    private InputStream input;
    //private SerialPort serialPort;
    private int valor1, valor2;

    public Principal() {
        initComponents();
        jButton2.setEnabled(false);
        jButton3.setEnabled(false);
    }

    public void abrirPorta() throws NoSuchPortException, PortInUseException,
            UnsupportedCommOperationException {
        portId = CommPortIdentifier.getPortIdentifier("COM3");
        port = (SerialPort) portId.open(this.getClass().getName(), 2000);
        port.setSerialPortParams(9600, SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    }

    public void fecharPorta() throws IOException {
        //input.close();
        port.removeEventListener();
        port.close();
        port = null;
    }

    public void lerDados() throws IOException {
        input = port.getInputStream();
        //while (true) {

        //while (input.available() > 0) {
        valor1 = input.read();
        valor2 = input.read();
        //System.out.println(valor1);
        //}
        //}
        
        jLabel1.setText(String.valueOf(valor1));
        jLabel2.setText(String.valueOf(valor2));
        System.out.println("v1: "+valor1);
        System.out.println("v2: "+valor2);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("jLabel1");

        jButton1.setText("Abrir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Ler");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Fechar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel2.setText("jLabel2");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(128, 128, 128)
                        .addComponent(jButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2)
                        .addGap(27, 27, 27)
                        .addComponent(jButton3))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(45, 45, 45)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))))
                .addContainerGap(60, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(42, 42, 42)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addGap(38, 38, 38)
                .addComponent(jLabel1)
                .addGap(33, 33, 33)
                .addComponent(jLabel2)
                .addContainerGap(136, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            abrirPorta();
        } catch (NoSuchPortException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (PortInUseException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedCommOperationException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
        jButton1.setEnabled(false);
        jButton2.setEnabled(true);
        jButton3.setEnabled(true);
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        if (port != null) {
            try {
                lerDados();
            } catch (IOException ex) {
                Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        if (port != null) {
            try {
                fecharPorta();
            } catch (IOException ex) {
                Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        jButton1.setEnabled(true);
        jButton2.setEnabled(false);
        jButton3.setEnabled(false);
    }                                        
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration                   

    public synchronized void close() {
        if (port != null) {
            port.removeEventListener();
            port.close();
        }
    }

    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                abrirPorta();
                lerDados();
                fecharPorta();
            } catch (Exception e) {
                System.out.println(e.toString());
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }

    public static void main(String[] args) throws NoSuchPortException, PortInUseException, IOException,
            UnsupportedCommOperationException {
        new Principal().setVisible(true);
    }

}

Espero que consigam me ajudar, obrigado desde ja pela atenção ![/quote]

No método serialEvent, você não precisa abrir a conexão toda hora, e nem fechar, o evento só vai ocorrer se a conexão já estiver aberta né!? deixe somente a ler dados e teste por enquanto, e coloque os erros aqui também!

Mas não dá erro, apenas não coincide os valores e não consigo acender um led entende?

Não estou conseguindo entender…

aquele código que está no arduino é só aquilo ali ou tem mais, porque você sabe que está faltando né!?

Peguei este codigo dos exemplos da IDE arduino, é isso que quero fazer, porem em java :

[code]int led = 13;

// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}[/code]

[quote=Dario Ribeiro]Peguei este codigo dos exemplos da IDE arduino, é isso que quero fazer, porem em java :

[code]int led = 13;

// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}[/code][/quote]

Colega, não tem como você programar em java para arduino, você programa em C/C++.