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


Tema destacado: Introducción a Git (Primera Parte)


  Mostrar Temas
Páginas: 1 ... 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 [31] 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 ... 68
301  Programación / Programación Visual Basic / Encontrar error de código. en: 27 Marzo 2015, 12:40 pm
Hola:

Al programar con VB 6 bajo Winwdows 7 de 64 bits, he hecho esto.


Quiero seleccionar el puerto serie que me detecta automáticamente el comboBox. Algo no tengo bien qu em e da error y al pulsar depurar me indica este error.

Código
  1. Private Sub Command_Led_8_OFF_Click()
  2. MSComm1.Output = "Led_8_OFF"
  3. End Sub
  4.  
  5. Private Sub Command_Led_8_ON_Click()
  6. MSComm1.Output = "Led_8_ON"
  7. End Sub
  8.  
  9. Private Sub Form_Load()
  10.    Form1.ComboBoxCOM.Clear
  11.       MSComm1.CommPort = ComboBoxCOM
  12. MSComm1.PortOpen = True   ' Habilitar el puerto serie.
  13. Timer1.Interval = 1       ' Correr el timer a 1 mls.
  14.    Set WMIObjectSet = GetObject("winmgmts:\\.\root\CIMV2").ExecQuery("SELECT * FROM Win32_PnPEntity") 'Win32_SerialPort")
  15.    For Each wmiobject In WMIObjectSet
  16.        If InStr(wmiobject.Name, "COM") Then   '
  17.          Form1.ComboBoxCOM.AddItem wmiobject.Name
  18.        End If
  19.         Next
  20.    Set WMIObjectSet = Nothing
  21. End Sub

El error dice:
No coincide los tipos.
302  Programación / Programación Visual Basic / Resgistar control RicgtTextBox de VB 6 para usarlo. en: 26 Marzo 2015, 08:38 am
Hola:

He encontrado 6 cmd.exe en Windows 7 de 64 bits.



Ver zoom.

Lo ejecuto como administrador.



Ejecuto comando como indica abajo.



Me sale este mensaje.



Contento y emocionado, intento agregar el componente.



Le doy aplicar o aceptar y me aparece este mensaje.



Me pregunto. ¿Qué es lo que falla realmente?

Saludos.
303  Programación / Programación Visual Basic / Error que no encuentro en Visual Basic 6 con el puerto serie en: 8 Marzo 2015, 02:13 am
Hola:

He hecho esto con el puerto serie pero me da error al pulsar CONECTAR.


Código
  1. Private Sub cmdcon_Click()
  2.    If cmdcon.Caption = "CONECTAR" Then
  3.        puerto.CommPort = Val(cmbsel.ListIndex + 1)
  4.        puerto.PortOpen = True
  5.        cmdenviar.Visible = True
  6.        Timer1.Enabled = True
  7.        cmdcon.Caption = "DESCONECTAR"
  8. Else
  9.    If cmdcon.Caption = "DESCONECTAR" Then
  10.        Timer1.Enabled = False
  11.        cmdenviar.Visible = False
  12.        puerto.PortOpen = False
  13.        cmdcon.Caption = "CONECTAR"
  14.    End If
  15. End If
  16. End Sub
  17.  
  18. Private Sub cmdenviar_Click()
  19. textout = txtenviar.Text
  20. puerto.Output = textout
  21. End Sub
  22.  
  23. Private Sub Timer1_Timer()
  24. textin = puerto.Input
  25. If textin <> "" Then
  26. puerto.Output = textout
  27. End Sub
  28.  


Uso Windows 7 de 64 bits. He seguido este vídeo.

El error que me aparece es este.



Mi idea principal es enviar tramas de bytes o texto y también recibirlas por el puerto serie.

¿Alguna idea?
304  Programación / Programación Visual Basic / Conseguir VB 6 en: 7 Marzo 2015, 02:39 am
Hola:

Tengo un tutorial que no he acabado aún sobre Java y Visual Studio en general, en esta ocasión centrado en VB 6.



Vídeo.
https://www.youtube.com/watch?v=g7XPhDL6auA

Quiero conseguir la versión de VB 6 para poder empezar.

Cualquier información para lograrlo en bienvenido.

El que quiera ver el tutorial en pdf sobre Visual Studio con C#, C++, VB .net esta lo tengo terminado. Si lo quieres lo puedo enviar por correo. Ocupa más de 15 MB, tiene muchas fotos. El manual completo lo entregaré.

Saludos.
305  Programación / Java / Leer puerto serie y mostrar texto en cuadro de texto en: 6 Marzo 2015, 21:33 pm
Hola:

Uso Windows 7 de 64 bits con Java de 32 para que me funcione el famoso RXTX.



He hecho una aplicación sencilla que se puede encender un Led y apagarlo con NetBeans 8 como puedes ver en la imagen de arriba.

1) Cuando el Form o formulario o ventana está abierta o ejecuto Java, me aparece arriba a la izquierda. ¿Cómo se pone en el centro cuando ejecutes a apliación?

2) Ahora quiero hacer un cuadro de texto para que muestre los textos que te entran en el puerto serie.

¿Alguna idea?

Su código para encender y apagar un Led es este.
Código
  1. import gnu.io.CommPortIdentifier;
  2. import gnu.io.SerialPort;
  3. import java.io.OutputStream;
  4. import java.util.Enumeration;
  5. import javax.swing.JOptionPane;
  6.  
  7. /*
  8.  * To change this license header, choose License Headers in Project Properties.
  9.  * To change this template file, choose Tools | Templates
  10.  * and open the template in the editor.
  11.  */
  12.  
  13. /**
  14.  *
  15.  * @author Meta
  16.  */
  17. public class JAVADUINO_Frame extends javax.swing.JFrame {
  18.  
  19.    /**
  20.      * Creates new form JAVADUINO_Frame
  21.      */
  22.  
  23.    private static final String L8on = "Led_8_ON";
  24.    private static final String L8off = "Led_8_OFF";
  25.  
  26.    // Variables de conexión.
  27.    private OutputStream output = null;
  28.    SerialPort serialPort;
  29.    private final String PUERTO = "COM4";
  30.  
  31.    private static final int TIMEOUT = 2000; // 2 segundos.
  32.  
  33.    private static final int DATA_RATE = 115200; // Baudios.
  34.  
  35.    public JAVADUINO_Frame() {
  36.        initComponents();
  37.        inicializarConexion();
  38.    }
  39.  
  40.    public void inicializarConexion(){
  41.        CommPortIdentifier puertoID = null;
  42.        Enumeration puertoEnum = CommPortIdentifier.getPortIdentifiers();
  43.  
  44.        while (puertoEnum.hasMoreElements()){
  45.            CommPortIdentifier actualPuertoID = (CommPortIdentifier) puertoEnum.nextElement();
  46.            if (PUERTO.equals(actualPuertoID.getName())){
  47.                puertoID = actualPuertoID;
  48.                break;
  49.            }
  50.        }
  51.  
  52.        if (puertoID == null){
  53.            mostrarError("No se puede conectar al puerto");
  54.            System.exit(ERROR);
  55.        }
  56.  
  57.        try{
  58.            serialPort = (SerialPort) puertoID.open(this.getClass().getName(), TIMEOUT);
  59.            // Parámatros puerto serie.
  60.  
  61.            serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
  62.  
  63.            output = serialPort.getOutputStream();
  64.        } catch (Exception e){
  65.            mostrarError(e.getMessage());
  66.            System.exit(ERROR);
  67.        }
  68.    }
  69.  
  70.    private void enviarDatos(String datos){
  71.        try{
  72.            output.write(datos.getBytes());
  73.        } catch (Exception e){
  74.            mostrarError("ERROR");
  75.            System.exit(ERROR);
  76.        }
  77.    }
  78.  
  79.    public void mostrarError(String mensaje){
  80.        JOptionPane.showMessageDialog(this, mensaje, "ERROR", JOptionPane.ERROR_MESSAGE);    
  81.    }
  82.    /**
  83.      * This method is called from within the constructor to initialize the form.
  84.      * WARNING: Do NOT modify this code. The content of this method is always
  85.      * regenerated by the Form Editor.
  86.      */
  87.    @SuppressWarnings("unchecked")
  88.    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  89.    private void initComponents() {
  90.  
  91.        jButton1 = new javax.swing.JButton();
  92.        jButton2 = new javax.swing.JButton();
  93.        jLabel1 = new javax.swing.JLabel();
  94.        jScrollPane1 = new javax.swing.JScrollPane();
  95.        jTextArea1 = new javax.swing.JTextArea();
  96.  
  97.        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  98.        setTitle("JAVA y más Java");
  99.  
  100.        jButton1.setText("ON");
  101.        jButton1.addActionListener(new java.awt.event.ActionListener() {
  102.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  103.                jButton1ActionPerformed(evt);
  104.            }
  105.        });
  106.  
  107.        jButton2.setText("OFF");
  108.        jButton2.addActionListener(new java.awt.event.ActionListener() {
  109.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  110.                jButton2ActionPerformed(evt);
  111.            }
  112.        });
  113.  
  114.        jLabel1.setText("Mensaje desde el puerto serie:");
  115.  
  116.        jTextArea1.setColumns(20);
  117.        jTextArea1.setRows(5);
  118.        jScrollPane1.setViewportView(jTextArea1);
  119.  
  120.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  121.        getContentPane().setLayout(layout);
  122.        layout.setHorizontalGroup(
  123.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  124.            .addGroup(layout.createSequentialGroup()
  125.                .addContainerGap()
  126.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  127.                    .addGroup(layout.createSequentialGroup()
  128.                        .addComponent(jButton1)
  129.                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  130.                        .addComponent(jButton2))
  131.                    .addGroup(layout.createSequentialGroup()
  132.                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  133.                        .addGap(0, 0, Short.MAX_VALUE)))
  134.                .addContainerGap())
  135.            .addGroup(layout.createSequentialGroup()
  136.                .addComponent(jLabel1)
  137.                .addGap(0, 0, Short.MAX_VALUE))
  138.        );
  139.        layout.setVerticalGroup(
  140.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  141.            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  142.                .addGap(26, 26, 26)
  143.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  144.                    .addComponent(jButton1)
  145.                    .addComponent(jButton2))
  146.                .addGap(31, 31, 31)
  147.                .addComponent(jLabel1)
  148.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  149.                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  150.                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
  151.        );
  152.  
  153.        pack();
  154.    }// </editor-fold>                        
  155.  
  156.    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  157.        // TODO add your handling code here:
  158.        enviarDatos(L8on);
  159.    }                                        
  160.  
  161.    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  162.        // TODO add your handling code here:
  163.        enviarDatos(L8off);
  164.    }                                        
  165.  
  166.    /**
  167.      * @param args the command line arguments
  168.      */
  169.    public static void main(String args[]) {
  170.        /* Set the Nimbus look and feel */
  171.        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  172.        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  173.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  174.          */
  175.        try {
  176.            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  177.                if ("Nimbus".equals(info.getName())) {
  178.                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
  179.                    break;
  180.                }
  181.            }
  182.        } catch (ClassNotFoundException ex) {
  183.            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  184.        } catch (InstantiationException ex) {
  185.            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  186.        } catch (IllegalAccessException ex) {
  187.            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  188.        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  189.            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  190.        }
  191.        //</editor-fold>
  192.  
  193.        /* Create and display the form */
  194.        java.awt.EventQueue.invokeLater(new Runnable() {
  195.            public void run() {
  196.                new JAVADUINO_Frame().setVisible(true);
  197.            }
  198.        });
  199.    }
  200.  
  201.    // Variables declaration - do not modify                    
  202.    private javax.swing.JButton jButton1;
  203.    private javax.swing.JButton jButton2;
  204.    private javax.swing.JLabel jLabel1;
  205.    private javax.swing.JScrollPane jScrollPane1;
  206.    private javax.swing.JTextArea jTextArea1;
  207.    // End of variables declaration                  
  208. }
  209.  

Saludos.
306  Programación / Java / Encontrar motivos de fallos sobre código Java. en: 6 Marzo 2015, 06:25 am
Hola:

Tengo un código medio hecho en el cual no se el motivo de los fallos. Se trata de encender y apagar un Led con Netbeans 8 en mi caso y Arduino.

Código
  1. import gnu.io.CommPortIdentifier;
  2. import gnu.io.SerialPort;
  3. import java.io.OutputStream;
  4. import java.util.Enumeration;
  5. import javax.swing.JOptionPane;
  6.  
  7. /*
  8.  * To change this license header, choose License Headers in Project Properties.
  9.  * To change this template file, choose Tools | Templates
  10.  * and open the template in the editor.
  11.  */
  12.  
  13. /**
  14.  *
  15.  * @author Meta
  16.  */
  17. public class JAVADUINO_JFrame extends javax.swing.JFrame {
  18.  
  19.    /**
  20.      * Creates new form JAVADUINO_JFrame
  21.      */
  22.  
  23.    private static final String L8ON = "Led_8_ON";
  24.    private static final String L8OFF = "Led_8_OFF";
  25.  
  26.    // Variables de conexión.
  27.    private final OutputStream output = null;
  28.    SerialPort serialPort;
  29.    private final String PUERTO = "COM4";
  30.  
  31.    private static final int TIMEOUT = 2000;
  32.  
  33.    private static final int DATA_RATE = 115200;
  34.  
  35.    public JAVADUINO_JFrame() {
  36.        initComponents();
  37.        inicializarConexion();
  38.    }
  39.  
  40.    public final void inicializarConexion(){
  41.        CommPortIdentifier puertoID = null;
  42.        Enumeration puertoEnum = CommPortIdentifier.getPortIdentifiers();
  43.  
  44.        while(puertoEnum.hasMoreElements()){
  45.            CommPortIdentifier actualPuertoID = (CommPortIdentifier) puertoEnum.nextElement();
  46.            if (PUERTO.equals(actualPuertoID.getName())){
  47.                puertoID = actualPuertoID;
  48.                break;
  49.            }
  50.        }
  51.    }
  52.  
  53.    if (puertoID == null){
  54.    mostrarError("No se puede conectar al puerto.");
  55.    System.exit(ERROR);
  56. }
  57.  
  58.    try{
  59.        serialPort = (SerialPort) puertoID.open(this.getClass().getName(), TIMEOUT);
  60.        // Parámetros puerto serie.
  61.        serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
  62.        output = serialPort.getOutputStream();
  63. }
  64.    catch (Exception e){
  65.    mostrarError(e.getMessage());
  66.    System.exit(ERROR);
  67. }
  68.  
  69.    private void enviarDatos(String datos){
  70.        try{
  71.            output.write(datos.getBytes());
  72.        }
  73.        catch(Exception e){
  74.            mostrarError("ERROR");
  75.            System.exit(ERROR);
  76.        }
  77.    }
  78.  
  79.    public void mostrarError(String mensaje){
  80.        JOptionPane.showMessageDialog(this, mensaje, "ERROR", JOptionPane.ERROR_MESSAGE);
  81.  
  82.    }
  83.    /**
  84.      * This method is called from within the constructor to initialize the form.
  85.      * WARNING: Do NOT modify this code. The content of this method is always
  86.      * regenerated by the Form Editor.
  87.      */
  88.    @SuppressWarnings("unchecked")
  89.    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  90.    private void initComponents() {
  91.  
  92.        jButton1 = new javax.swing.JButton();
  93.        jButton2 = new javax.swing.JButton();
  94.  
  95.        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  96.  
  97.        jButton1.setText("ON");
  98.  
  99.        jButton2.setText("OFF");
  100.  
  101.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  102.        getContentPane().setLayout(layout);
  103.        layout.setHorizontalGroup(
  104.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  105.            .addGroup(layout.createSequentialGroup()
  106.                .addGap(21, 21, 21)
  107.                .addComponent(jButton1)
  108.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 101, Short.MAX_VALUE)
  109.                .addComponent(jButton2)
  110.                .addGap(45, 45, 45))
  111.        );
  112.        layout.setVerticalGroup(
  113.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  114.            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  115.                .addContainerGap(250, Short.MAX_VALUE)
  116.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  117.                    .addComponent(jButton1)
  118.                    .addComponent(jButton2))
  119.                .addGap(27, 27, 27))
  120.        );
  121.  
  122.        pack();
  123.    }// </editor-fold>                        
  124.  
  125.    /**
  126.      * @param args the command line arguments
  127.      */
  128.    public static void main(String args[]) {
  129.        /* Set the Nimbus look and feel */
  130.        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  131.        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  132.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  133.          */
  134.        try {
  135.            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  136.                if ("Nimbus".equals(info.getName())) {
  137.                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
  138.                    break;
  139.                }
  140.            }
  141.        } catch (ClassNotFoundException ex) {
  142.            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  143.        } catch (InstantiationException ex) {
  144.            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  145.        } catch (IllegalAccessException ex) {
  146.            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  147.        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  148.            java.util.logging.Logger.getLogger(JAVADUINO_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  149.        }
  150.        //</editor-fold>
  151.  
  152.        /* Create and display the form */
  153.        java.awt.EventQueue.invokeLater(new Runnable() {
  154.            public void run() {
  155.                new JAVADUINO_JFrame().setVisible(true);
  156.            }
  157.        });
  158.    }
  159.  
  160.    // Variables declaration - do not modify                    
  161.    private javax.swing.JButton jButton1;
  162.    private javax.swing.JButton jButton2;
  163.    // End of variables declaration                  
  164.  
  165.    private void mostrarError(String no_se_puede_conectar_al_puerto) {
  166.        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  167.    }
  168. }
  169.  

Todavía no he programado los botones, hay que acabar con los fallos primero. Los mensajes que me dan son estos.
Citar
run:
java.lang.ClassFormatError: Duplicate field name&signature in class file JAVADUINO_JFrame
   at java.lang.ClassLoader.defineClass1(Native Method)
   at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
   at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
   at java.net.URLClassLoader.defineClass(URLClassLoader.java:455)
   at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
   at java.net.URLClassLoader$1.run(URLClassLoader.java:367)
   at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
   at java.security.AccessController.doPrivileged(Native Method)
   at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
   at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
   at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:495)
Exception in thread "main" Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

He segudio los tutoriales hasta el minuto 37':30" de este vídeo.
https://www.youtube.com/watch?v=4Hr_LZ62SdY

¿Alguna idea?

Saludos.
307  Programación / Java / Cargar librería en NetBeans 8 en: 28 Febrero 2015, 03:47 am
Hola a todos y a todas:

Descargué Netbeans 8.01 en español y JDK. Lo tengo instalado. Fui a la web
http://rxtx.qbang.org/wiki/index.php/Download

Y justo este enlace me descargué el rachivo en binario.

Estoy con Arduino y quiero desde Java encender y apagar un Led, que se puede hacer. El codigo de Arduino UNO r3 es este.

Código:
char caracter;
String comando;

void setup() {
  pinMode(8, OUTPUT); // Pin 8 la configuramos como salida.
  pinMode(13, OUTPUT);
  digitalWrite(8, HIGH); // Mantener relés del pin 8 apagado.
  digitalWrite(13, HIGH); // Mantener relés del pin 13 apagado.
  Serial.begin(115200); // Baudios a 115200.
}

void loop()
{
  /* Se lee carácter por carácter por el puerto serie, mientras, se va
  concatenando uno tras otro en una cadena. */
  while (Serial.available() > 0)
  {
    caracter = Serial.read();
    comando.concat(caracter);
    delay(10); // Este retardo muy corto es para no saturar el puerto
    // serie y que la concatenación se haga de forma ordenada.
  }

  if (comando.equals("Led_8_ON") == true) // Si la cadena o comando "Led_8_ON" es verdadero.
  {
    digitalWrite(8, !HIGH); // El Led 8 se enciende.
    Serial.println("Led 8 encendido."); // Envía mensaje por puerto serie.
  }

  if (comando.equals("Led_8_OFF") == true) // Si el comando "Led_8_OFF" es verdadero.
  {
    digitalWrite(8, !LOW); // Se apaga el Led 8.
    Serial.println("Led 8 apagado."); // Envía mensaje por puerto serie.
  }

  if (comando.equals("Led_13_ON") == true)
  {
    digitalWrite(13, !HIGH);
    Serial.println("Led 13 encendido.");
  }

  if (comando.equals("Led_13_OFF") == true)
  {
    digitalWrite(13, !LOW);
    Serial.println("Led 13 apagado.");
  }

  // Limpiamos la cadena para volver a recibir el siguiente comando.
  comando = "";
}

Lo que hace es recibir comandos por el puerto serie. Por ahora solo quiero saber como se prepara esa librería RXTX en el NMetBeans 8.xx, no para la 7.x.

Es de 64 bits el que tengo instalado bajo Windows 7.


Paso 1.
http://www.subeimagenes.com/img/fsdafasdfsad-1239041.png

Paso 2.
http://www.subeimagenes.com/img/fsdafasdfsad-1239044.png

Paso 3.
http://www.subeimagenes.com/img/fsdafasdfsad-1239046.png

Hasta aquí he lelgado y solo me falta cargar la librería RxTx que on se hacerlo y necesito ayuda. He estado viendo por internet con netbeans 7.x y parece ser que no es igual que l a8.



Saludos.
308  Programación / .NET (C#, VB.NET, ASP) / Encontrar la solución de recibir datos. en: 28 Febrero 2015, 02:13 am
Hola:

Tengo este código con WPF C# 2013. Puedo enviar datos pero no recibirlos y se muestre en RichTextBox.
Código
  1.  
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using System.Windows.Data;
  10. using System.Windows.Documents;
  11. using System.Windows.Input;
  12. using System.Windows.Media;
  13. using System.Windows.Media.Imaging;
  14. using System.Windows.Navigation;
  15. using System.Windows.Shapes;
  16.  
  17. using System.IO.Ports; // No olvidar.
  18. using System.Threading;
  19.  
  20. namespace WpfApplication1
  21. {
  22.    /// <summary>
  23.    /// Lógica de interacción para MainWindow.xaml
  24.    /// </summary>
  25.    public partial class MainWindow : Window
  26.    {
  27.        // Utilizaremos un string como buffer de recepción.
  28.        string Recibidos;
  29.  
  30.        SerialPort serialPort1 = new SerialPort();
  31.  
  32.        public MainWindow()
  33.        {
  34.            InitializeComponent();
  35.  
  36.            serialPort1.BaudRate = 115200;
  37.            serialPort1.PortName = "COM4";
  38.            serialPort1.Parity = Parity.None;
  39.            serialPort1.DataBits = 8;
  40.            serialPort1.StopBits = StopBits.Two;
  41.  
  42.            // Abrir puerto mientras se ejecute la aplicación.
  43.            if (!serialPort1.IsOpen)
  44.            {
  45.                try
  46.                {
  47.                    serialPort1.Open();
  48.                }
  49.                catch (System.Exception ex)
  50.                {
  51.                    MessageBox.Show(ex.ToString());
  52.                }
  53.  
  54.            }
  55.  
  56.            // Ejecutar la función REcepción por disparo del Evento ¡DataReived'.
  57.            //serialPort1.DataReceived += new SerialDataReceivedEventHandler(Recepcion);
  58.        }
  59.  
  60.        private void Recepcion(object sender, SerialDataReceivedEventHandler e)
  61.        {
  62.            // Acumular los caracteres recibidos a nuestro 'buffer' (string).
  63.            Recibidos += serialPort1.ReadExisting();
  64.  
  65.            // Invocar o llamar al proceso de tramas.
  66.            //this.Invoke(new EventHandler(Actualizar));
  67.  
  68.        }
  69.  
  70.  
  71.        // Procesar los datos recibidos en el buffer y estraer tramas completas.
  72.        private void Actualizar(object s, EventArgs e)
  73.        {
  74.            // Asignar el valor de la trama al RichTextBox.
  75.            RichTextBox_Mensajes.DataContext = Recibidos;
  76.        }
  77.  
  78.        private void Button_Led_8_ON_Click(object sender, RoutedEventArgs e)
  79.        {
  80.            byte[] mBuffer = Encoding.ASCII.GetBytes("Led_8_ON");
  81.            serialPort1.Write(mBuffer, 0, mBuffer.Length);
  82.        }
  83.  
  84.        private void Button_Led_8_OFF_Click(object sender, RoutedEventArgs e)
  85.        {
  86.            byte[] mBuffer = Encoding.ASCII.GetBytes("Led_8_OFF");
  87.            serialPort1.Write(mBuffer, 0, mBuffer.Length);
  88.            RichTextBox_Mensajes.DataContext = "Hola";
  89.        }
  90.  
  91.    }
  92. }
  93.  

Alguna solución donde está el problema.

Saludos.
309  Programación / .NET (C#, VB.NET, ASP) / Envios y recibos de caracteres VB .net en: 27 Febrero 2015, 08:44 am


1)El programa espera la recepciòn de un ENQ(05 Hex) o STX(02 Hex)

2) Si recibo lo del paso 1 , le envìo un ACK(06 Hex)

3)Luego de enviado el ACK leo todo lo que me manda la maquina externa, si es distinto de cualquier caracter de control, lo muestro.

4) Si recibo un EOT(04 Hex) mando un enter en la pantalla de recepcion para diferenciar las lineas.

5) Si recibo un ETX(03 Hex) le respondo con un ACK.

Supongo que en este caso se podrìa hacer un if o un select preguntando lo recibido, el tema es que no se como leer de manera correcta y poder comparar que es lo que se recibio para poder ejecutar la tarea necesaria segun lo que llega.

Código
  1. Imports System.IO.Ports
  2. Imports System.Text
  3.  
  4. Public Class Form1
  5.    Dim recibidos As String
  6.    Dim stx As String = ASCIIEncoding.ASCII.GetString(New Byte() {2})
  7.    Dim etx As String = ASCIIEncoding.ASCII.GetString(New Byte() {3})
  8.    Dim eot As String = ASCIIEncoding.ASCII.GetString(New Byte() {4})
  9.    Dim enq As String = ASCIIEncoding.ASCII.GetString(New Byte() {5})
  10.    Dim ack As String = ASCIIEncoding.ASCII.GetString(New Byte() {6})
  11.  
  12.  
  13.    Public Sub New()
  14.        InitializeComponent()
  15.        If Not SerialPort1.IsOpen Then
  16.            Try
  17.                SerialPort1.Open()
  18.            Catch ex As Exception
  19.                MessageBox.Show(ex.ToString)
  20.            End Try
  21.        End If
  22.        AddHandler SerialPort1.DataReceived, AddressOf recepcion
  23.    End Sub
  24.  
  25.    Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
  26.        If SerialPort1.IsOpen Then
  27.            SerialPort1.Close()
  28.        End If
  29.    End Sub
  30.  
  31.    Private Sub recepcion(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
  32.  
  33.        recibidos = Chr(SerialPort1.ReadChar)
  34.        If recibidos = stx Or recibidos = enq Then
  35.            SerialPort1.Write(ack)
  36.        Else
  37.            If recibidos <> stx And recibidos <> etx And recibidos <> enq And recibidos <> ack And recibidos <> eot Then
  38.                Me.Invoke(New EventHandler(AddressOf actualizar))
  39.            Else
  40.                If recibidos = eot Then
  41.                    Me.Invoke(New EventHandler(AddressOf actualizarenter))
  42.                Else
  43.                    If recibidos = etx Then
  44.                        SerialPort1.Write(ack)
  45.                    End If
  46.                End If
  47.            End If
  48.        End If
  49.  
  50.  
  51.    End Sub
  52.  
  53.    Private Sub actualizar(ByVal s As Object, ByVal e As EventArgs)
  54.        textbox_visualizar_mensaje.Text = textbox_visualizar_mensaje.Text & recibidos
  55.    End Sub
  56.  
  57.    Private Sub actualizarenter(ByVal s As Object, ByVal e As EventArgs)
  58.        textbox_visualizar_mensaje.Text = textbox_visualizar_mensaje.Text & vbLf
  59.    End Sub
  60.  
  61.    Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
  62.        StatusStrip1.Items(0).Text = DateTime.Now.ToLongTimeString
  63.    End Sub
  64.  
  65.    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  66.        SerialPort1.Encoding = System.Text.Encoding.Default
  67.    End Sub
  68. End Class
310  Programación / .NET (C#, VB.NET, ASP) / Hacer compatible C++ códigos de C#. en: 23 Febrero 2015, 23:17 pm
Hola:
Tengo este código dentro de un button para enviar tramas de bytes hecho con C#.

Código
  1. // Enviar tramas de bytes.
  2.  
  3.            byte[] miBuffer = new byte[9]; // Led_13_ON son 9 byte máximo.
  4.            miBuffer[0] = 0x4C; // ASCII letra "L".
  5.            miBuffer[1] = 0x65; // ASCII letra "e".
  6.            miBuffer[2] = 0x64; // ASCII letra "d".
  7.            miBuffer[3] = 0x5F; // ASCII letra "_".
  8.            miBuffer[4] = 0x31; // ASCII letra "1".
  9.            miBuffer[5] = 0x33; // ASCII letra "3".
  10.            miBuffer[6] = 0x5F; // ASCII letra "_".
  11.            miBuffer[7] = 0x4F; // ASCII letra "O".
  12.            miBuffer[8] = 0x4E; // ASCII letra "N".
  13.            serialPort1.Write(miBuffer, 0, miBuffer.Length); // Envia las tramas de bytes.

Da igual cuantras tramas hay que enviar, en C++ se hace así com indica abajo enviando la letra t.

Código
  1. cli::array&lt;unsigned char&gt; ^uno = gcnew cli::array&lt;unsigned char&gt; (1);
  2. uno[0] = 0x74; // ASCII letra "t".
  3. serialPort1-&gt;Write(uno, 0, 1);

Quiero hacer una cadena escrito más cómodamente como el ejemplo en C# hecho abajo.

Código
  1.            byte[] mBuffer = Encoding.ASCII.GetBytes("Led_8_ON");
  2.            serialPort1.Write(mBuffer, 0, mBuffer.Length);

¿Cómo se hace en Visual C++ 2010?

Gracias.
Páginas: 1 ... 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 [31] 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 ... 68
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines