Control de dispositivos a través del módulo USB del PIC18F45/2550

Meta tengo una duda , como hago que para poder seleccionar el puerto de comunicaciones seriales utilizando un combobox de la siguiente manera:

http://img27.imageshack.us/my.php?image=dudaf.jpg

Lo que yo quisiera hacer es que una vés seleccionado el puerto de comunicaciones, apretemos conectar y nos comuniquemos.

El código fuente del botón Conectar es el siguiente: (En Visual C# 2008)

En si el código es el mismo que vos usas en el manual , pero solo se comunica si apreto conectar en ves de conectarse
cuando se ejecuta el programa.

Código:
 private void Conectar_Click(object sender, EventArgs e)
        {
            // Abrir puerto cuando pulsemos conectar.
            if (!serialPort1.IsOpen) // Si el puerto serial está cerrado...
            {
                try
                {
                    serialPort1.Open(); // Trata de abrirlo.
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString()); // Si hay un error lo muetra en un msgbox.
                }
            }
            // Ejecutar la función Recepción por disparo del evento Datareceived.
            serialPort1.DataReceived += new
            System.IO.Ports.SerialDataReceivedEventHandler(Recepcion);
        }

Espero que me podás dar una mano así termino este programa de ejemplo
 
Investigando, espero por favor...

Voy a tardar un poquito que son varias cosas...
...sorry.


EDIT 1:

Hay códigos que te sobran y debe ser así:
Código:
     private void Conectar_Click(object sender, EventArgs e)
            {
                // Abrir puerto cuando pulsemos conectar.
                if (!serialPort1.IsOpen) // Si el puerto serial está cerrado...
                {
                    try
                    {
                        serialPort1.Open(); // Trata de abrirlo.
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.ToString()); // Si hay un error lo muetra en un msgbox.
                    }
                }
            }

Olvídate del código de arriba, no lo uses para nada. Prueba este método de abajo primero, estoy investigando lo del comboBox que se me resiste:



Código:
private void button1_Click(object sender, EventArgs e)
        {
            serialPort1.Open(); // Abrir puerto.
            byte[] miBuffer = new byte[1];
            miBuffer[0] = 0x62; //ASCII letra "b".
            serialPort1.Write(miBuffer, 0, miBuffer.Length);
            serialPort1.Close(); // Cerrar puerto.
        }

private void button2_Click(object sender, EventArgs e)
        {
            serialPort1.Open(); // Abrir puerto.
            byte[] mBuffer = new byte[1];
            mBuffer[0] = 0x74; //ASCII letra "t".
            serialPort1.Write(mBuffer, 0, mBuffer.Length);
            serialPort1.Close(); // Cerrar puerto.
        }

EDITO 2:


¿Quieres hacer que el botón Conectar se conecte y aparezca el nombre aparezca Desconectado?

He hecho la misma pregunta aquí a ver si lo hacen mejor qu eyo, de momento estoy trabajando en ello.

http://social.msdn.microsoft.com/Forums/es-ES/vcsexes/thread/1fa79253-cacd-42db-b5b3-3d60309ab42d

Saludo.

EDITO 3:

No he hecho todavía lo de cambiar el COM1 y COM2 que estoy investigando, por ahora funciona un método que hice. No se si esto es lo que quieres. Te recuerdo que estoy investigando lo del comboBox. Puedes descargar el arhcivo del ejemplo que estoy haciendo aquí.
 

Adjuntos

  • probando_02_200.zip
    11.3 KB · Visitas: 303
  • dudaf_202.jpg
    dudaf_202.jpg
    29.1 KB · Visitas: 342
Gracias por la ayuda meta, encontre algo muy interesante en internet: Un código en VB.net para poder detectar que puertos series hay disponibles en la PC, entonces elejimos el que esté libre y nos comunicamos con el.

Código:
Public Class Form1
    'Enumerate Serial Ports on Machine
    'Get Serial Port availability

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Just drag & drop combobox from toolbox to form designer
        Me.ComboBox1.DrawMode = DrawMode.OwnerDrawVariable                     'select my own drag mode
        Me.ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList                'aspect when drop down
        Me.ComboBox1.DataSource = My.Computer.Ports.SerialPortNames.ToArray    'enumerate serialports
        Me.ComboBox1.TabIndex = 0                                              'select first tabindex
        AddHandler ComboBox1.DrawItem, AddressOf cmbo_SerialPorts_Status       'draw my personal cmbo
    End Sub
    '
    ' Draw our custom combo
    Private Sub cmbo_SerialPorts_Status( _
        ByVal sender As Object, _
        ByVal CmboItem As System.Windows.Forms.DrawItemEventArgs)

        ' Draw the background of the item.
        CmboItem.DrawBackground()
        '
        'Default Values if port is available
        Dim status As String = "Available"
        Dim brush As New SolidBrush(Color.Green)
        Dim font As System.Drawing.Font = Me.Font
        Dim fontbrush As Brush = Brushes.Black
        Dim rectangle As Rectangle = New  _
            Rectangle(2, CmboItem.Bounds.Top + 2, _
                         CmboItem.Bounds.Height, _
                         CmboItem.Bounds.Height - 4)
        '
        'Check for port availability
        Try
            ' If port open & close with no exception
            ' draw the item with default font and green rectangle
            Dim PortTest As New System.IO.Ports.SerialPort
            PortTest = My.Computer.Ports.OpenSerialPort(My.Computer.Ports.SerialPortNames(CmboItem.Index))
            PortTest.Close()
        Catch ex As Exception
            ' If port is not available
            ' draw the item with italic & strikeout font and red rectangle
            brush = New SolidBrush(Color.Red)
            status = "In Use"
            font = New Font(FontFamily.GenericSansSerif, Me.Font.Size, FontStyle.Italic Xor FontStyle.Strikeout)
            fontbrush = Brushes.DimGray
        End Try

        'fill combo item rectangle
        CmboItem.Graphics.FillRectangle(brush, rectangle)
        'write text with actual port status for this item
        CmboItem.Graphics.DrawString( _
            My.Computer.Ports.SerialPortNames(CmboItem.Index) + " - " + status, _
            font, _
            fontbrush, _
            New  _
                    RectangleF(CmboItem.Bounds.X + rectangle.Width, _
                               CmboItem.Bounds.Y, _
                               CmboItem.Bounds.Width, _
                               CmboItem.Bounds.Height) _
        )
        ' Draw focus rectangle when mouse are over an item.
        CmboItem.DrawFocusRectangle()
    End Sub
End Class

El código es bastante largo y además me gustaria saber como hacerlo en VC#. Igual voy a seguir investigando a ver que encuentro.

Vos cuando encontrés alguna solución avisame..
 
Había encontrado algo http://msmvps.com/blogs/peplluis/ar...onados.aspx?CommentPosted=true#commentmessage

Código:
    * public class Form1
    * {
    *     //Enumerate Serial Ports on Machine
    *     //Get Serial Port availability
    *    
    *     private void // ERROR: Handles clauses are not supported in C# Form1_Load(object sender, System.EventArgs e)
    *     {
    *         //Just drag & drop combobox from toolbox to form designer
    *         this.ComboBox1.DrawMode = DrawMode.OwnerDrawVariable;
    *         //select my own drag mode
    *         this.ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
    *         //aspect when drop down
    *         this.ComboBox1.DataSource = My.Computer.Ports.SerialPortNames.ToArray;
    *         //enumerate serialports
    *         this.ComboBox1.TabIndex = 0;
    *         //select first tabindex
    *         ComboBox1.DrawItem += cmbo_SerialPorts_Status;
    *         //draw my personal cmbo
    *     }
    *     //
    *     // Draw our custom combo
    *     private void cmbo_SerialPorts_Status(object sender, System.Windows.Forms.DrawItemEventArgs CmboItem)
    *     {
    *        
    *         // Draw the background of the item.
    *         CmboItem.DrawBackground();
    *         //
    *         //Default Values if port is available
    *         string status = "Available";
    *         SolidBrush brush = new SolidBrush(Color.Green);
    *         System.Drawing.Font font = this.Font;
    *         Brush fontbrush = Brushes.Black;
    *         Rectangle rectangle = new Rectangle(2, CmboItem.Bounds.Top + 2, CmboItem.Bounds.Height, CmboItem.Bounds.Height - 4);
    *         //
    *         //Check for port availability
    *         try {
    *             // If port open & close with no exception
    *             // draw the item with default font and green rectangle
    *             System.IO.Ports.SerialPort PortTest = new System.IO.Ports.SerialPort();
    *             PortTest = My.Computer.Ports.OpenSerialPort(My.Computer.Ports.SerialPortNames(CmboItem.Index));
    *             PortTest.Close();
    *         }
    *         catch (Exception ex) {
    *             // If port is not available
    *             // draw the item with italic & strikeout font and red rectangle
    *             brush = new SolidBrush(Color.Red);
    *             status = "In Use";
    *             font = new Font(FontFamily.GenericSansSerif, this.Font.Size, FontStyle.Italic ^ FontStyle.Strikeout);
    *             fontbrush = Brushes.DimGray;
    *         }
    *        
    *         //fill combo item rectangle
    *         CmboItem.Graphics.FillRectangle(brush, rectangle);
    *         //write text with actual port status for this item
    *         CmboItem.Graphics.DrawString(My.Computer.Ports.SerialPortNames(CmboItem.Index) + " - " + status, font, fontbrush, new RectangleF(CmboItem.Bounds.X + rectangle.Width, CmboItem.Bounds.Y, CmboItem.Bounds.Width, CmboItem.Bounds.Height));
    *         // Draw focus rectangle when mouse are over an item.
    *         CmboItem.DrawFocusRectangle();
    *     }
    * }

Aquí he estado sacando algo.
http://msmvps.com/blogs/peplluis/archive/tags/Puertos+Serie/default.aspx

Saludo.
 
Del ejemplo que te di antes, sólo he logrado esto, pero sigo investigando. Últimamente estoy aprendiendo a la fuerza bruta.

Código:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace Probando_02
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        // Variables
        string pa = "Puerto abiero.";
        string pc = "Puerto cerrado. Pulse botón 'Conectar'.";
        string des = "Desconectar";
        string con = "Conectar";
        int open = 1;
        int com = 2;

        private void button_on_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] mBuffer = new byte[1];
                mBuffer[0] = 0x74; //ASCII letra "t".
                serialPort1.Write(mBuffer, 0, mBuffer.Length);
                button_on.Enabled = false;
                button_off.Enabled = true;
                label_.Text = "ON";
                label_.ForeColor = Color.Green;
            }
            catch (InvalidOperationException)
            {
                label_mensaje.Text = pc;
            }
        }

        private void button_off_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] miBuffer = new byte[1];
                miBuffer[0] = 0x62; //ASCII letra "b".
                serialPort1.Write(miBuffer, 0, miBuffer.Length);
                button_off.Enabled = false;
                button_on.Enabled = true;
                label_.Text = "OFF";
                label_.ForeColor = Color.Red;
            }
            catch (InvalidOperationException)
            {
                label_mensaje.Text = pc;
            }
        }

        private void button_conectar_Click(object sender, EventArgs e)
        {
            if (open == 1)
            {
                open = 2;
                serialPort1.Close();
                if (comboBox1.Items.Count > 0)
                {
                    comboBox1.SelectedIndex = com;
                }
                serialPort1.Open();
                label_mensaje.Text = pa;
                button_conectar.Text = des;
                
            }
            else
            {
                open = 1;
                serialPort1.Close();
                label_mensaje.Text = pc;
                button_conectar.Text = con;
                button_on.Enabled = true;
                button_off.Enabled = true;
                label_.Text = " ";
            }
        }
    }
}
 
Huu buenisimo , me había olvidado de esa herramienta. Bueno creo que tengo más o menos suficiente como para terminar mi primer ejemplo de control en visual C#.
Cualquier duda te pregunto.
 
Ahora estoy pescando, pero si te sirve de ayuda mientras perdemos tiempo investigando hasta que nos responda alguien del foro, doy estos enlaces.

http://msdn.microsoft.com/es-es/library/system.windows.forms.combobox.selecteditem(VS.80).aspx

http://msdn.microsoft.com/es-es/library/ms750552.aspx

Por si acaso, voy a investigar a ver si me sale esto. Cuando logre hacer lo que pides, la verdad es que lo agregaré en el manual para que la gente lo sepa.
 
Si estaría buenisimo que lo agregaras al manual y cuando a mi salga lo del USB con los diferentes lenguajes... le voy a pedir al administrador del foro que los suba a la parte de tutoriales para que todos lo tengan a mano.
 
Cierto.

Lo del USB y si lo entiendo, hago el pedazo de manual como los que hago así http://electronica-pic.blogspot.com/ mientras de momento lo pones en el foro para que la gente de nuevas ideas.

Me han pedido que hiciera el puerto serie por modo consola o CMD. ¿Esto vale la pena hacerlo? jejejeje, En Linux Logré ya funcionar el puerto serie, por fin, algo es algo y esto si estaba ya planeado para el manual.
 
Hola mire he estado leyendo lo que quieren hacer y creo que es esto no lo he probado del todo pero estoy casi seguro que funciona
cree el boton Conectar el comboBox que lo llame comboBox_selec_com
y en el boton escribo este codigo en mi caso uso el COM14:

private void Conectar_Click(object sender, EventArgs e)
{
int selectedIndex = comboBox_selec_com.SelectedIndex;
Object selectedItem = comboBox_selec_com.SelectedItem;

// Abrir puerto COM14
if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
}
 
ejjejeejje, lo estoy probado...

Espera a ver que pasa.

EDITO:
Si puedes, hay que lograr cambiar esto así mediante programación con el comboBox, pero no me sale. Sigo investigando.
Código:
 serialPort1.PortName = "COM1";
 
En VB .net no tengo idea, sigo machacándome la cabeza con el VC# y haber si responden algo desde aquí.

Si en VB.net lo hiciste funcionar, me lo dices, jejeejeje a ver si aprendo algo de él y gracias.
 
Menuda locura nos hace pasar el comboBox que todavía no he aprendido.

Otra cosa:
Cuando dejo en marcha el PIC por puerto serie, al cerrar la aplicación de Visual C# o el que sea, el PIC sigue activado. Tengo el código necesario para que se desactive el PIC mientras cierra la aplicación. Es bueno saberlo y lo del comboBox más todavía.
 
Creo que lo logré, ajajajaja

Por fin,

Sólo digo creo, voy a encender el Pentiun III que tiene la ventaja de venir dos puertos series COM1 y COM2.

Luego te aviso.
 
Atrás
Arriba