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.
Private Sub Command_Led_8_OFF_Click()
MSComm1.Output = "Led_8_OFF"
End Sub
Private Sub Command_Led_8_ON_Click()
MSComm1.Output = "Led_8_ON"
End Sub
Private Sub Form_Load()
Form1.ComboBoxCOM.Clear
MSComm1.CommPort = ComboBoxCOM
MSComm1.PortOpen = True ' Habilitar el puerto serie.
Timer1.Interval = 1 ' Correr el timer a 1 mls.
Set WMIObjectSet = GetObject ("winmgmts:\\.\root\CIMV2" ).ExecQuery("SELECT * FROM Win32_PnPEntity" ) 'Win32_SerialPort")
For Each wmiobject In WMIObjectSet
If InStr(wmiobject.Name, "COM" ) Then '
Form1.ComboBoxCOM.AddItem wmiobject.Name
End If
Next
Set WMIObjectSet = Nothing
End Sub
El error dice:
No coincide los tipos.
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.
Private Sub cmdcon_Click()
If cmdcon.Caption = "CONECTAR" Then
puerto.CommPort = Val(cmbsel.ListIndex + 1)
puerto.PortOpen = True
cmdenviar.Visible = True
Timer1.Enabled = True
cmdcon.Caption = "DESCONECTAR"
Else
If cmdcon.Caption = "DESCONECTAR" Then
Timer1.Enabled = False
cmdenviar.Visible = False
puerto.PortOpen = False
cmdcon.Caption = "CONECTAR"
End If
End If
End Sub
Private Sub cmdenviar_Click()
textout = txtenviar.Text
puerto.Output = textout
End Sub
Private Sub Timer1_Timer()
textin = puerto.Input
If textin <> "" Then
puerto.Output = textout
End Sub
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.
import gnu.io.CommPortIdentifier ;
import gnu.io.SerialPort ;
import java.io.OutputStream ;
import java.util.Enumeration ;
import javax.swing.JOptionPane ;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Meta
*/
public class JAVADUINO_Frame
extends javax.
swing .
JFrame {
/**
* Creates new form JAVADUINO_Frame
*/
private static final String L8on
= "Led_8_ON" ; private static final String L8off
= "Led_8_OFF" ;
// Variables de conexión.
SerialPort serialPort;
private final String PUERTO
= "COM4" ;
private static final int TIMEOUT = 2000 ; // 2 segundos.
private static final int DATA_RATE = 115200 ; // Baudios.
public JAVADUINO_Frame( ) {
initComponents( ) ;
inicializarConexion( ) ;
}
public void inicializarConexion( ) {
CommPortIdentifier puertoID = null ;
Enumeration puertoEnum
= CommPortIdentifier.
getPortIdentifiers ( ) ;
while ( puertoEnum.hasMoreElements ( ) ) {
CommPortIdentifier actualPuertoID = ( CommPortIdentifier) puertoEnum.nextElement ( ) ;
if ( PUERTO.equals ( actualPuertoID.getName ( ) ) ) {
puertoID = actualPuertoID;
break ;
}
}
if ( puertoID == null ) {
mostrarError( "No se puede conectar al puerto" ) ;
}
try {
serialPort = ( SerialPort) puertoID.open ( this .getClass ( ) .getName ( ) , TIMEOUT) ;
// Parámatros puerto serie.
serialPort.setSerialPortParams ( DATA_RATE, SerialPort.DATABITS_8 , SerialPort.STOPBITS_2 , SerialPort.PARITY_NONE ) ;
output = serialPort.getOutputStream ( ) ;
mostrarError( e.getMessage ( ) ) ;
}
}
private void enviarDatos
( String datos
) { try {
output.write ( datos.getBytes ( ) ) ;
mostrarError( "ERROR" ) ;
}
}
public void mostrarError
( String mensaje
) { }
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings( "unchecked" )
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents( ) {
jButton1
= new javax.
swing .
JButton ( ) ; jButton2
= new javax.
swing .
JButton ( ) ; jLabel1
= new javax.
swing .
JLabel ( ) ;
setTitle( "JAVA y más Java" ) ;
jButton1.setText ( "ON" ) ;
public void actionPerformed
( java.
awt .
event .
ActionEvent evt
) { jButton1ActionPerformed( evt) ;
}
} ) ;
jButton2.setText ( "OFF" ) ;
public void actionPerformed
( java.
awt .
event .
ActionEvent evt
) { jButton2ActionPerformed( evt) ;
}
} ) ;
jLabel1.setText ( "Mensaje desde el puerto serie:" ) ;
jTextArea1.setColumns ( 20 ) ;
jTextArea1.setRows ( 5 ) ;
jScrollPane1.setViewportView ( jTextArea1) ;
javax.swing .GroupLayout layout = new javax.swing .GroupLayout ( getContentPane( ) ) ;
getContentPane( ) .setLayout ( layout) ;
layout.setHorizontalGroup (
layout.createParallelGroup ( javax.swing .GroupLayout .Alignment .LEADING )
.addGroup ( layout.createSequentialGroup ( )
.addContainerGap ( )
.addGroup ( layout.createParallelGroup ( javax.swing .GroupLayout .Alignment .LEADING )
.addGroup ( layout.createSequentialGroup ( )
.addComponent ( jButton1)
.
addPreferredGap ( javax.
swing .
LayoutStyle .
ComponentPlacement .
RELATED , javax.
swing .
GroupLayout .
DEFAULT_SIZE ,
Short .
MAX_VALUE ) .addComponent ( jButton2) )
.addGroup ( layout.createSequentialGroup ( )
.addComponent ( jScrollPane1, javax.swing .GroupLayout .PREFERRED_SIZE , javax.swing .GroupLayout .DEFAULT_SIZE , javax.swing .GroupLayout .PREFERRED_SIZE )
.
addGap ( 0 ,
0 ,
Short .
MAX_VALUE ) ) ) .addContainerGap ( ) )
.addGroup ( layout.createSequentialGroup ( )
.addComponent ( jLabel1)
.
addGap ( 0 ,
0 ,
Short .
MAX_VALUE ) ) ) ;
layout.setVerticalGroup (
layout.createParallelGroup ( javax.swing .GroupLayout .Alignment .LEADING )
.addGroup ( javax.swing .GroupLayout .Alignment .TRAILING , layout.createSequentialGroup ( )
.addGap ( 26 , 26 , 26 )
.addGroup ( layout.createParallelGroup ( javax.swing .GroupLayout .Alignment .BASELINE )
.addComponent ( jButton1)
.addComponent ( jButton2) )
.addGap ( 31 , 31 , 31 )
.addComponent ( jLabel1)
.addPreferredGap ( javax.swing .LayoutStyle .ComponentPlacement .RELATED )
.addComponent ( jScrollPane1, javax.swing .GroupLayout .PREFERRED_SIZE , javax.swing .GroupLayout .DEFAULT_SIZE , javax.swing .GroupLayout .PREFERRED_SIZE )
.
addContainerGap ( javax.
swing .
GroupLayout .
DEFAULT_SIZE ,
Short .
MAX_VALUE ) ) ) ;
pack( ) ;
} // </editor-fold>
private void jButton1ActionPerformed
( java.
awt .
event .
ActionEvent evt
) { // TODO add your handling code here:
enviarDatos( L8on) ;
}
private void jButton2ActionPerformed
( java.
awt .
event .
ActionEvent evt
) { // TODO add your handling code here:
enviarDatos( L8off) ;
}
/**
* @param args the command line arguments
*/
public static void main
( String args
[ ] ) { /* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
if ( "Nimbus" .equals ( info.getName ( ) ) ) {
javax.
swing .
UIManager .
setLookAndFeel ( info.
getClassName ( ) ) ; break ;
}
}
java.util .logging .Logger .getLogger ( JAVADUINO_Frame.class .getName ( ) ) .log ( java.util .logging .Level .SEVERE , null , ex) ;
java.util .logging .Logger .getLogger ( JAVADUINO_Frame.class .getName ( ) ) .log ( java.util .logging .Level .SEVERE , null , ex) ;
java.util .logging .Logger .getLogger ( JAVADUINO_Frame.class .getName ( ) ) .log ( java.util .logging .Level .SEVERE , null , ex) ;
java.util .logging .Logger .getLogger ( JAVADUINO_Frame.class .getName ( ) ) .log ( java.util .logging .Level .SEVERE , null , ex) ;
}
//</editor-fold>
/* Create and display the form */
public void run( ) {
new JAVADUINO_Frame( ) .setVisible ( true ) ;
}
} ) ;
}
// Variables declaration - do not modify
private javax.
swing .
JButton jButton1
; private javax.
swing .
JButton jButton2
; private javax.
swing .
JLabel jLabel1
; // End of variables declaration
}
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.
import gnu.io.CommPortIdentifier ;
import gnu.io.SerialPort ;
import java.io.OutputStream ;
import java.util.Enumeration ;
import javax.swing.JOptionPane ;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Meta
*/
public class JAVADUINO_JFrame
extends javax.
swing .
JFrame {
/**
* Creates new form JAVADUINO_JFrame
*/
private static final String L8ON
= "Led_8_ON" ; private static final String L8OFF
= "Led_8_OFF" ;
// Variables de conexión.
SerialPort serialPort;
private final String PUERTO
= "COM4" ;
private static final int TIMEOUT = 2000 ;
private static final int DATA_RATE = 115200 ;
public JAVADUINO_JFrame( ) {
initComponents( ) ;
inicializarConexion( ) ;
}
public final void inicializarConexion( ) {
CommPortIdentifier puertoID = null ;
Enumeration puertoEnum
= CommPortIdentifier.
getPortIdentifiers ( ) ;
while ( puertoEnum.hasMoreElements ( ) ) {
CommPortIdentifier actualPuertoID = ( CommPortIdentifier) puertoEnum.nextElement ( ) ;
if ( PUERTO.equals ( actualPuertoID.getName ( ) ) ) {
puertoID = actualPuertoID;
break ;
}
}
}
if ( puertoID == null ) {
mostrarError( "No se puede conectar al puerto." ) ;
}
try {
serialPort = ( SerialPort) puertoID.open ( this .getClass ( ) .getName ( ) , TIMEOUT) ;
// Parámetros puerto serie.
serialPort.setSerialPortParams ( DATA_RATE, SerialPort.DATABITS_8 , SerialPort.STOPBITS_2 , SerialPort.PARITY_NONE ) ;
output = serialPort.getOutputStream ( ) ;
}
mostrarError( e.getMessage ( ) ) ;
}
private void enviarDatos
( String datos
) { try {
output.write ( datos.getBytes ( ) ) ;
}
mostrarError( "ERROR" ) ;
}
}
public void mostrarError
( String mensaje
) {
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings( "unchecked" )
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents( ) {
jButton1
= new javax.
swing .
JButton ( ) ; jButton2
= new javax.
swing .
JButton ( ) ;
jButton1.setText ( "ON" ) ;
jButton2.setText ( "OFF" ) ;
javax.swing .GroupLayout layout = new javax.swing .GroupLayout ( getContentPane( ) ) ;
getContentPane( ) .setLayout ( layout) ;
layout.setHorizontalGroup (
layout.createParallelGroup ( javax.swing .GroupLayout .Alignment .LEADING )
.addGroup ( layout.createSequentialGroup ( )
.addGap ( 21 , 21 , 21 )
.addComponent ( jButton1)
.
addPreferredGap ( javax.
swing .
LayoutStyle .
ComponentPlacement .
RELATED ,
101 ,
Short .
MAX_VALUE ) .addComponent ( jButton2)
.addGap ( 45 , 45 , 45 ) )
) ;
layout.setVerticalGroup (
layout.createParallelGroup ( javax.swing .GroupLayout .Alignment .LEADING )
.addGroup ( javax.swing .GroupLayout .Alignment .TRAILING , layout.createSequentialGroup ( )
.
addContainerGap ( 250 ,
Short .
MAX_VALUE ) .addGroup ( layout.createParallelGroup ( javax.swing .GroupLayout .Alignment .BASELINE )
.addComponent ( jButton1)
.addComponent ( jButton2) )
.addGap ( 27 , 27 , 27 ) )
) ;
pack( ) ;
} // </editor-fold>
/**
* @param args the command line arguments
*/
public static void main
( String args
[ ] ) { /* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
if ( "Nimbus" .equals ( info.getName ( ) ) ) {
javax.
swing .
UIManager .
setLookAndFeel ( info.
getClassName ( ) ) ; break ;
}
}
java.util .logging .Logger .getLogger ( JAVADUINO_JFrame.class .getName ( ) ) .log ( java.util .logging .Level .SEVERE , null , ex) ;
java.util .logging .Logger .getLogger ( JAVADUINO_JFrame.class .getName ( ) ) .log ( java.util .logging .Level .SEVERE , null , ex) ;
java.util .logging .Logger .getLogger ( JAVADUINO_JFrame.class .getName ( ) ) .log ( java.util .logging .Level .SEVERE , null , ex) ;
java.util .logging .Logger .getLogger ( JAVADUINO_JFrame.class .getName ( ) ) .log ( java.util .logging .Level .SEVERE , null , ex) ;
}
//</editor-fold>
/* Create and display the form */
public void run( ) {
new JAVADUINO_JFrame( ) .setVisible ( true ) ;
}
} ) ;
}
// Variables declaration - do not modify
private javax.
swing .
JButton jButton1
; private javax.
swing .
JButton jButton2
; // End of variables declaration
private void mostrarError
( String no_se_puede_conectar_al_puerto
) { }
}
Todavía no he programado los botones, hay que acabar con los fallos primero. Los mensajes que me dan son estos.
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.
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.
VIDEO 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input ;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports; // No olvidar.
using System.Threading;
namespace WpfApplication1
{
/// <summary>
/// Lógica de interacción para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
// Utilizaremos un string como buffer de recepción.
string Recibidos;
SerialPort serialPort1 = new SerialPort();
public MainWindow()
{
InitializeComponent();
serialPort1.BaudRate = 115200;
serialPort1.PortName = "COM4" ;
serialPort1.Parity = Parity.None;
serialPort1.DataBits = 8;
serialPort1.StopBits = StopBits.Two;
// Abrir puerto mientras se ejecute la aplicación.
if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open ();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
// Ejecutar la función REcepción por disparo del Evento ¡DataReived'.
//serialPort1.DataReceived += new SerialDataReceivedEventHandler(Recepcion);
}
private void Recepcion(object sender, SerialDataReceivedEventHandler e)
{
// Acumular los caracteres recibidos a nuestro 'buffer' (string).
Recibidos += serialPort1.ReadExisting();
// Invocar o llamar al proceso de tramas.
//this.Invoke(new EventHandler(Actualizar));
}
// Procesar los datos recibidos en el buffer y estraer tramas completas.
private void Actualizar(object s, EventArgs e)
{
// Asignar el valor de la trama al RichTextBox.
RichTextBox_Mensajes.DataContext = Recibidos;
}
private void Button_Led_8_ON_Click(object sender, RoutedEventArgs e)
{
byte [] mBuffer = Encoding.ASCII.GetBytes("Led_8_ON" );
serialPort1.Write(mBuffer, 0, mBuffer.Length);
}
private void Button_Led_8_OFF_Click(object sender, RoutedEventArgs e)
{
byte [] mBuffer = Encoding.ASCII.GetBytes("Led_8_OFF" );
serialPort1.Write(mBuffer, 0, mBuffer.Length);
RichTextBox_Mensajes.DataContext = "Hola" ;
}
}
}
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.
Imports System.IO .Ports
Imports System.Text
Public Class Form1
Dim recibidos As String
Dim stx As String = ASCIIEncoding.ASCII .GetString ( New Byte ( ) { 2 } )
Dim etx As String = ASCIIEncoding.ASCII .GetString ( New Byte ( ) { 3 } )
Dim eot As String = ASCIIEncoding.ASCII .GetString ( New Byte ( ) { 4 } )
Dim enq As String = ASCIIEncoding.ASCII .GetString ( New Byte ( ) { 5 } )
Dim ack As String = ASCIIEncoding.ASCII .GetString ( New Byte ( ) { 6 } )
Public Sub New ( )
InitializeComponent( )
If Not SerialPort1.IsOpen Then
Try
SerialPort1.Open ( )
Catch ex As Exception
MessageBox.Show ( ex.ToString )
End Try
End If
AddHandler SerialPort1.DataReceived , AddressOf recepcion
End Sub
Private Sub Form1_FormClosing( sender As Object , e As System.Windows .Forms .FormClosingEventArgs ) Handles Me .FormClosing
If SerialPort1.IsOpen Then
SerialPort1.Close ( )
End If
End Sub
Private Sub recepcion( ByVal sender As Object , ByVal e As System.IO .Ports .SerialDataReceivedEventArgs )
recibidos = Chr ( SerialPort1.ReadChar )
If recibidos = stx Or recibidos = enq Then
SerialPort1.Write ( ack)
Else
If recibidos <> stx And recibidos <> etx And recibidos <> enq And recibidos <> ack And recibidos <> eot Then
Me .Invoke ( New EventHandler( AddressOf actualizar) )
Else
If recibidos = eot Then
Me .Invoke ( New EventHandler( AddressOf actualizarenter) )
Else
If recibidos = etx Then
SerialPort1.Write ( ack)
End If
End If
End If
End If
End Sub
Private Sub actualizar( ByVal s As Object , ByVal e As EventArgs)
textbox_visualizar_mensaje.Text = textbox_visualizar_mensaje.Text & recibidos
End Sub
Private Sub actualizarenter( ByVal s As Object , ByVal e As EventArgs)
textbox_visualizar_mensaje.Text = textbox_visualizar_mensaje.Text & vbLf
End Sub
Private Sub Timer1_Tick( sender As System.Object , e As System.EventArgs ) Handles Timer1.Tick
StatusStrip1.Items ( 0 ) .Text = DateTime.Now .ToLongTimeString
End Sub
Private Sub Form1_Load( sender As System.Object , e As System.EventArgs ) Handles MyBase .Load
SerialPort1.Encoding = System.Text .Encoding .Default
End Sub
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#.
// Enviar tramas de bytes.
byte[ ] miBuffer = new byte[ 9 ] ; // Led_13_ON son 9 byte máximo.
miBuffer[ 0 ] = 0x4C ; // ASCII letra "L".
miBuffer[ 1 ] = 0x65 ; // ASCII letra "e".
miBuffer[ 2 ] = 0x64 ; // ASCII letra "d".
miBuffer[ 3 ] = 0x5F ; // ASCII letra "_".
miBuffer[ 4 ] = 0x31 ; // ASCII letra "1".
miBuffer[ 5 ] = 0x33 ; // ASCII letra "3".
miBuffer[ 6 ] = 0x5F ; // ASCII letra "_".
miBuffer[ 7 ] = 0x4F ; // ASCII letra "O".
miBuffer[ 8 ] = 0x4E ; // ASCII letra "N".
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.
cli:: array & lt; unsigned char & gt; ^ uno = gcnew cli:: array & lt; unsigned char & gt; ( 1 ) ;
uno[ 0 ] = 0x74 ; // ASCII letra "t".
serialPort1- & gt; Write( uno, 0 , 1 ) ;
Quiero hacer una cadena escrito más cómodamente como el ejemplo en C# hecho abajo.
byte[ ] mBuffer = Encoding.ASCII .GetBytes ( "Led_8_ON" ) ;
serialPort1.Write ( mBuffer, 0 , mBuffer.Length ) ;
¿Cómo se hace en Visual C++ 2010?
Gracias.