elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


+  Foro de elhacker.net
|-+  Informática
| |-+  Electrónica
| | |-+  Comunicando arduino con PC
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Comunicando arduino con PC  (Leído 4,287 veces)
Debci
Wiki

Desconectado Desconectado

Mensajes: 2.021


Actualizate o muere!


Ver Perfil WWW
Comunicando arduino con PC
« en: 31 Mayo 2010, 20:08 pm »

Hola a todos, ya he hecho toda una proeza (para mi :)) en el mundo de la electronica, y es crear mi software, y con este controlar mi arduino, mediante envio de un codigo numerico sencillo, la cosa es que no puedo graduar el fadding, no se que problema puede ser, la cosa es la siguiente, tengo el siguiente codigo en java:

Código
  1. /*
  2.  * PanelControl.java
  3.  *
  4.  * Created on 31-may-2010, 19:33:36
  5.  */
  6.  
  7. package javacom;
  8.  
  9. import app.Com;
  10. import app.Parameters;
  11. import core.SerialPort;
  12. import java.util.List;
  13. import java.util.logging.Level;
  14. import java.util.logging.Logger;
  15.  
  16. /**
  17.  *
  18.  * @author debci
  19.  */
  20. public class PanelControl extends javax.swing.JFrame {
  21.  
  22.    /** Creates new form PanelControl */
  23.    public PanelControl() {
  24.        initComponents();
  25.    }
  26.  
  27.    /** This method is called from within the constructor to
  28.      * initialize the form.
  29.      * WARNING: Do NOT modify this code. The content of this method is
  30.      * always regenerated by the Form Editor.
  31.      */
  32.    @SuppressWarnings("unchecked")
  33.    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  34.    private void initComponents() {
  35.  
  36.        jButton1 = new javax.swing.JButton();
  37.        jButton2 = new javax.swing.JButton();
  38.        jButton3 = new javax.swing.JButton();
  39.        jSlider1 = new javax.swing.JSlider();
  40.        jButton4 = new javax.swing.JButton();
  41.  
  42.        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  43.  
  44.        jButton1.setText("Enciende LED");
  45.        jButton1.addActionListener(new java.awt.event.ActionListener() {
  46.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  47.                jButton1ActionPerformed(evt);
  48.            }
  49.        });
  50.  
  51.        jButton2.setText("Apaga LED");
  52.        jButton2.addActionListener(new java.awt.event.ActionListener() {
  53.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  54.                jButton2ActionPerformed(evt);
  55.            }
  56.        });
  57.  
  58.        jButton3.setText("Fadding");
  59.        jButton3.addActionListener(new java.awt.event.ActionListener() {
  60.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  61.                jButton3ActionPerformed(evt);
  62.            }
  63.        });
  64.  
  65.        jSlider1.setMaximum(254);
  66.        jSlider1.setValue(0);
  67.        jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
  68.            public void stateChanged(javax.swing.event.ChangeEvent evt) {
  69.                jSlider1StateChanged(evt);
  70.            }
  71.        });
  72.  
  73.        jButton4.setText("Inicio FADDING");
  74.        jButton4.addActionListener(new java.awt.event.ActionListener() {
  75.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  76.                jButton4ActionPerformed(evt);
  77.            }
  78.        });
  79.  
  80.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  81.        getContentPane().setLayout(layout);
  82.        layout.setHorizontalGroup(
  83.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  84.            .addGroup(layout.createSequentialGroup()
  85.                .addContainerGap()
  86.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  87.                    .addComponent(jButton1)
  88.                    .addComponent(jButton2)
  89.                    .addComponent(jButton3)
  90.                    .addComponent(jButton4)
  91.                    .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  92.                .addContainerGap(184, Short.MAX_VALUE))
  93.        );
  94.        layout.setVerticalGroup(
  95.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  96.            .addGroup(layout.createSequentialGroup()
  97.                .addContainerGap()
  98.                .addComponent(jButton1)
  99.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  100.                .addComponent(jButton2)
  101.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  102.                .addComponent(jButton3)
  103.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
  104.                .addComponent(jButton4)
  105.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  106.                .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  107.                .addContainerGap(107, Short.MAX_VALUE))
  108.        );
  109.  
  110.        pack();
  111.    }// </editor-fold>//GEN-END:initComponents
  112.  
  113.    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
  114.        Control.EnviaComando(98,0);
  115.    }//GEN-LAST:event_jButton2ActionPerformed
  116.  
  117.    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
  118.        Control.EnviaComando(97,0);
  119.    }//GEN-LAST:event_jButton1ActionPerformed
  120.  
  121.    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
  122.        Control.EnviaComando(99,0);
  123.    }//GEN-LAST:event_jButton3ActionPerformed
  124.  
  125.    private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSlider1StateChanged
  126.  
  127.        Control.EnviaComando(100,jSlider1.getValue());
  128.        System.out.print(jSlider1.getValue());
  129.    }//GEN-LAST:event_jSlider1StateChanged
  130.  
  131.    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
  132.        Control.EnviaComando(100,0);
  133.    }//GEN-LAST:event_jButton4ActionPerformed
  134.  
  135.    /**
  136.     * @param args the command line arguments
  137.     */
  138.    public static void main(String args[]) {
  139.        java.awt.EventQueue.invokeLater(new Runnable() {
  140.            public void run() {
  141.                new PanelControl().setVisible(true);
  142.            }
  143.        });
  144.    }
  145.  
  146.    // Variables declaration - do not modify//GEN-BEGIN:variables
  147.    private javax.swing.JButton jButton1;
  148.    private javax.swing.JButton jButton2;
  149.    private javax.swing.JButton jButton3;
  150.    private javax.swing.JButton jButton4;
  151.    private javax.swing.JSlider jSlider1;
  152.    // End of variables declaration//GEN-END:variables
  153.  
  154. }
  155. class Control
  156. {
  157.    static SerialPort puerto = new SerialPort();
  158.    static List<String> listaPuertos;
  159.    static Com com1;
  160.    public static void EnviaComando(int interrupcion, int argumento)
  161.    {
  162.        try {
  163.            listaPuertos = puerto.getFreeSerialPort();
  164.            String recibido = "";
  165.            String caracter = "";
  166.  
  167.            Parameters settings = new Parameters();
  168.            settings.setPort("COMUSB2");
  169.            settings.setBaudRate("9600");
  170.            com1 = new Com(settings);
  171.            System.out.println(recibido);
  172.            com1.writeDataInt("COMUSB2", interrupcion);
  173.            com1.writeDataInt("COMUSB2", argumento);
  174.        } catch (Exception ex) {
  175.            Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
  176.        }
  177.    }
  178. }
  179.  
Que envia el siguiente codigo numerico:
97 -> Enciende LED
98-> Apaga LED
99-> Fadding Pre-establecido
100 + valorCustom -> Gradua la intensidad del led con el valor custom, ose 100 quiere decir, espera otro valor y ponlo como valor de intensidad.

Y este es el codigo de mi arduino:

Código
  1. // start reading from the first byte (address 0) of the EEPROM
  2. int address = 0;
  3. byte value;
  4. int incomingByte = 0;
  5. const int pinLed = 11;
  6.  
  7. void setup()
  8. {
  9.  Serial.begin(9600);
  10.  pinMode(pinLed, OUTPUT);
  11.  Serial.println("Hola, te has conectado");
  12. }
  13.  
  14. void loop()
  15. {
  16.  if (Serial.available() > 0) {
  17. // read the incoming byte:
  18. incomingByte = Serial.read();
  19.  
  20. // say what you got:
  21. //Serial.print("Orden recivida: ");
  22. //Serial.println(incomingByte, DEC);
  23.                switch(incomingByte)
  24.                {
  25.                case 97:
  26.                  digitalWrite(pinLed, HIGH);
  27.                  Serial.println("Enciendo led...");
  28.                  break;
  29.                case 98:
  30.                  digitalWrite(pinLed, LOW);
  31.                  Serial.println("Apagando led...");
  32.                  break;
  33.                case 99:
  34.                  Serial.println("Iniciando proceso de fadding...");
  35.                  digitalWrite(pinLed, LOW);
  36.                  for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
  37.                    // sets the value (range from 0 to 255):
  38.                    analogWrite(pinLed, fadeValue);        
  39.                    // wait for 30 milliseconds to see the dimming effect    
  40.                    delay(30);                            
  41.                    }
  42.  
  43.                    // fade out from max to min in increments of 5 points:
  44.                    for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
  45.                    // sets the value (range from 0 to 255):
  46.                    analogWrite(pinLed, fadeValue);        
  47.                    // wait for 30 milliseconds to see the dimming effect    
  48.                    delay(30);                            
  49.  
  50.                   }
  51.                   break;
  52.                   case 100:
  53.                   Serial.read();
  54.                    int valorFadding = Serial.read();
  55.                    analogWrite(pinLed, valorFadding);
  56.                    break;
  57.  
  58.          }
  59.  
  60.  
  61.  
  62.  }
  63. }
  64.  
Que en concreto, se puede apreciar que cuando recive el valor 100, vuelve a leer, porque mi programa en java, envia un segundo dato con el valor del fadding, de manera que cuando muevo el slide del programa envia 100, 5 100, 230 y cuando detecta 100 lee lo siguiente y se lo pone, pero no funciona bien, es tocar el slide y que se encienda sin variaciones.

Alguien tiene idea de porque ocurre esto?


Saludos


En línea

@synthesize
Wiki

Desconectado Desconectado

Mensajes: 640


Another Brick in the Wall


Ver Perfil WWW
Re: Comunicando arduino con PC
« Respuesta #1 en: 31 Mayo 2010, 20:54 pm »

Joder, hace unas horas hice o mismo pero en C... Todavía lo estoy desarrollando XD


En línea

Debci
Wiki

Desconectado Desconectado

Mensajes: 2.021


Actualizate o muere!


Ver Perfil WWW
Re: Comunicando arduino con PC
« Respuesta #2 en: 31 Mayo 2010, 21:09 pm »

Con c es mas sencillo, pues es nativo, pero java...
La cosa es que como puedo para que si envio 2 valores que los lea consecutivamente.

Saludos
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Ayuda: Arduino + java
Electrónica
carepapa 1 4,977 Último mensaje 29 Noviembre 2011, 03:59 am
por carepapa
arduino
.NET (C#, VB.NET, ASP)
kokokoko 0 2,628 Último mensaje 2 Marzo 2012, 15:51 pm
por kokokoko
Leonardo, llega a la familia Arduino
Noticias
wolfbcn 0 1,900 Último mensaje 25 Julio 2012, 21:30 pm
por wolfbcn
Iniciarme con arduino 'virtual'
Electrónica
lucaslopez0000 1 4,468 Último mensaje 4 Marzo 2013, 18:12 pm
por m0rf
programar y reprogramar arduino?
Electrónica
bash 2 6,940 Último mensaje 6 Noviembre 2013, 13:01 pm
por bash
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines