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

A ver si puedo traducir de VB a C# estos códigos poco a poco.

Código:
'UPGRADE_WARNING: Event Check1.CheckStateChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="vbup2075"'
    Private Sub Check1_CheckStateChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Check1.CheckStateChanged
        Dim send_buf(64) As Byte
        Dim receive_buf(64) As Byte
        
        Dim RecvLength As Integer
        
        OpenMPUSBDevice()
        
        If myOutPipe <> INVALID_HANDLE_VALUE And myInPipe <> INVALID_HANDLE_VALUE Then
            
            RecvLength = 1
            
            
            send_buf(0) = 50 '0x32
            send_buf(1) = 3
            If Check1.CheckState = 1 Then
                send_buf(2) = 1
            ElseIf Check1.CheckState = 0 Then 
                send_buf(2) = 0
            End If
            
            If (SendReceivePacket(send_buf, 3, receive_buf, RecvLength, 1000, 1000) = 1) Then
                
                If (RecvLength <> 1 Or receive_buf(0) <> 50) Then
                    MsgBox("Failed to update LED")
                End If
                
            End If
            
        End If
        
        CloseMPUSBDevice()
        
    End Sub
    
    'UPGRADE_WARNING: Event Check2.CheckStateChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="vbup2075"'
    Private Sub Check2_CheckStateChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Check2.CheckStateChanged
        Dim send_buf(64) As Byte
        Dim receive_buf(64) As Byte
        
        Dim RecvLength As Integer
        
        OpenMPUSBDevice()
        
        If myOutPipe <> INVALID_HANDLE_VALUE And myInPipe <> INVALID_HANDLE_VALUE Then
            
            RecvLength = 1
            
            
            send_buf(0) = 50 '0x32
            send_buf(1) = 4
            If Check2.CheckState = 1 Then
                send_buf(2) = 1
            ElseIf Check2.CheckState = 0 Then 
                send_buf(2) = 0
            End If
            
            If (SendReceivePacket(send_buf, 3, receive_buf, RecvLength, 1000, 1000) = 1) Then
                
                If (RecvLength <> 1 Or receive_buf(0) <> 50) Then
                    
                    MsgBox("Failed to update LED")
                    
                End If
                
            End If
            
        End If
        
        CloseMPUSBDevice()
        
    End Sub
    
    Private Sub Command1_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Command1.Click
        Me.Close()
    End Sub
    
    Private Sub Command2_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Command2.Click
        End
    End Sub
    
    Private Sub Command3_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Command3.Click
        Dim send_buf(64) As Byte
        Dim receive_buf(64) As Byte
        
        Dim RecvLength As Integer
        
        OpenMPUSBDevice()
        
        If myOutPipe <> INVALID_HANDLE_VALUE And myInPipe <> INVALID_HANDLE_VALUE Then
            
            RecvLength = 4
            
            send_buf(0) = 0 '0x0 - READ_VERSION
            send_buf(1) = 2
            
            If (SendReceivePacket(send_buf, 2, receive_buf, RecvLength, 1000, 1000) = 1) Then
                
                If (RecvLength <> 4 Or receive_buf(0) <> 0) Then
                    
                    MsgBox("Failed to obtain version information.")
                Else
                    Text1.Text = "Demo Version  " & Str(receive_buf(3)) & "." & Str(receive_buf(2))
                    
                End If
                
            End If
            
        End If
        
        CloseMPUSBDevice()
        
    End Sub
    
    Private Sub Form1_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
        Initialize()
        
    End Sub
End Class
Voy a probar a ver como queda poco a poco con este enlace.

http://www.developerfusion.com/tools/convert/csharp-to-vb/

Saludo.
EDITO:

Estoy haciendo pruebas y he convertido de VB a C# pero no funciona, al meno se ve el código para empezar a dar un pequeño paso.

Código:
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.Compatibility;
using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
 // ERROR: Not supported in C#: OptionDeclaration
namespace Project1
{
    //======================================================================================
    //        VB.NET Example code MPUSBAPI.DLL
    //        Free to use code supplied by www.comvcon.com
    //        Use this code at you own will and risk
    //        Please do not remove this line: www.comvcon.com
    //======================================================================================

    internal class Form1 : System.Windows.Forms.Form
    {
        #region "Windows Form Designer generated code "
        public Form1() : base()
        {
            Load += Form1_Load;
            if (m_vb6FormDefInstance == null) {
                if (m_InitializingDefInstance) {
                    m_vb6FormDefInstance = this;
                } else {
                    try {
                        //For the start-up form, the first instance created is the default instance.
                        if (object.ReferenceEquals(System.Reflection.Assembly.GetExecutingAssembly().EntryPoint.DeclaringType, this.GetType())) {
                            m_vb6FormDefInstance = this;
                        }
                    } catch {
                    }
                }
            }
            //This call is required by the Windows Form Designer.
            InitializeComponent();
        }
//Form overrides dispose to clean up the component list.
        protected override void Dispose(bool Disposing)
        {
            if (Disposing) {
                if ((components != null)) {
                    components.Dispose();
                }
            }
            base.Dispose(Disposing);
        }
//Required by the Windows Form Designer
        private System.ComponentModel.IContainer components;
        public System.Windows.Forms.ToolTip ToolTip1;
        public System.Windows.Forms.TextBox Text1;
        private System.Windows.Forms.Button withEventsField_Command3;
        public System.Windows.Forms.Button Command3 {
            get { return withEventsField_Command3; }
            set {
                if (withEventsField_Command3 != null) {
                    withEventsField_Command3.Click -= Command3_Click;
                }
                withEventsField_Command3 = value;
                if (withEventsField_Command3 != null) {
                    withEventsField_Command3.Click += Command3_Click;
                }
            }
        }
        private System.Windows.Forms.CheckBox withEventsField_Check2;
        public System.Windows.Forms.CheckBox Check2 {
            get { return withEventsField_Check2; }
            set {
                if (withEventsField_Check2 != null) {
                    withEventsField_Check2.CheckStateChanged -= Check2_CheckStateChanged;
                }
                withEventsField_Check2 = value;
                if (withEventsField_Check2 != null) {
                    withEventsField_Check2.CheckStateChanged += Check2_CheckStateChanged;
                }
            }
        }
        private System.Windows.Forms.CheckBox withEventsField_Check1;
        public System.Windows.Forms.CheckBox Check1 {
            get { return withEventsField_Check1; }
            set {
                if (withEventsField_Check1 != null) {
                    withEventsField_Check1.CheckStateChanged -= Check1_CheckStateChanged;
                }
                withEventsField_Check1 = value;
                if (withEventsField_Check1 != null) {
                    withEventsField_Check1.CheckStateChanged += Check1_CheckStateChanged;
                }
            }
        }
        private System.Windows.Forms.Button withEventsField_Command1;
        public System.Windows.Forms.Button Command1 {
            get { return withEventsField_Command1; }
            set {
                if (withEventsField_Command1 != null) {
                    withEventsField_Command1.Click -= Command1_Click;
                }
                withEventsField_Command1 = value;
                if (withEventsField_Command1 != null) {
                    withEventsField_Command1.Click += Command1_Click;
                }
            }
        }
        private System.Windows.Forms.Button withEventsField_Command2;
        public System.Windows.Forms.Button Command2 {
            get { return withEventsField_Command2; }
            set {
                if (withEventsField_Command2 != null) {
                    withEventsField_Command2.Click -= Command2_Click;
                }
                withEventsField_Command2 = value;
                if (withEventsField_Command2 != null) {
                    withEventsField_Command2.Click += Command2_Click;
                }
            }
        }
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
        [System.Diagnostics.DebuggerStepThrough()]
        private void InitializeComponent()
        {
            System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
            this.components = new System.ComponentModel.Container();
            this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
            this.ToolTip1.Active = true;
            this.Text1 = new System.Windows.Forms.TextBox();
            this.Command3 = new System.Windows.Forms.Button();
            this.Check2 = new System.Windows.Forms.CheckBox();
            this.Check1 = new System.Windows.Forms.CheckBox();
            this.Command1 = new System.Windows.Forms.Button();
            this.Command2 = new System.Windows.Forms.Button();
            this.Text = "VB MPUSBAPI Demo";
            this.ClientSize = new System.Drawing.Size(340, 151);
            this.Location = new System.Drawing.Point(4, 23);
            this.StartPosition = System.Windows.Forms.FormStartPosition.WindowsDefaultLocation;
            this.Font = new System.Drawing.Font("Arial", 8f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.BackColor = System.Drawing.SystemColors.Control;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
            this.ControlBox = true;
            this.Enabled = true;
            this.KeyPreview = false;
            this.MaximizeBox = true;
            this.MinimizeBox = true;
            this.Cursor = System.Windows.Forms.Cursors.Default;
            this.RightToLeft = System.Windows.Forms.RightToLeft.No;
            this.ShowInTaskbar = true;
            this.HelpButton = false;
            this.WindowState = System.Windows.Forms.FormWindowState.Normal;
            this.Name = "Form1";
            this.Text1.AutoSize = false;
            this.Text1.Size = new System.Drawing.Size(257, 25);
            this.Text1.Location = new System.Drawing.Point(24, 104);
            this.Text1.TabIndex = 5;
            this.Text1.Text = "Text1";
            this.Text1.Font = new System.Drawing.Font("Arial", 8f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
            this.Text1.AcceptsReturn = true;
            this.Text1.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
            this.Text1.BackColor = System.Drawing.SystemColors.Window;
            this.Text1.CausesValidation = true;
            this.Text1.Enabled = true;
            this.Text1.ForeColor = System.Drawing.SystemColors.WindowText;
            this.Text1.HideSelection = true;
            this.Text1.ReadOnly = false;
            this.Text1.MaxLength = 0;
            this.Text1.Cursor = System.Windows.Forms.Cursors.IBeam;
            this.Text1.Multiline = false;
            this.Text1.RightToLeft = System.Windows.Forms.RightToLeft.No;
            this.Text1.ScrollBars = System.Windows.Forms.ScrollBars.None;
            this.Text1.TabStop = true;
            this.Text1.Visible = true;
            this.Text1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.Text1.Name = "Text1";
            this.Command3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.Command3.Text = "Get Version";
            this.Command3.Size = new System.Drawing.Size(129, 25);
            this.Command3.Location = new System.Drawing.Point(16, 72);
            this.Command3.TabIndex = 4;
            this.Command3.Font = new System.Drawing.Font("Arial", 8f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
            this.Command3.BackColor = System.Drawing.SystemColors.Control;
            this.Command3.CausesValidation = true;
            this.Command3.Enabled = true;
            this.Command3.ForeColor = System.Drawing.SystemColors.ControlText;
            this.Command3.Cursor = System.Windows.Forms.Cursors.Default;
            this.Command3.RightToLeft = System.Windows.Forms.RightToLeft.No;
            this.Command3.TabStop = true;
            this.Command3.Name = "Command3";
            this.Check2.Text = "LED4";
            this.Check2.Size = new System.Drawing.Size(81, 17);
            this.Check2.Location = new System.Drawing.Point(128, 24);
            this.Check2.TabIndex = 3;
            this.Check2.Font = new System.Drawing.Font("Arial", 8f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
            this.Check2.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.Check2.BackColor = System.Drawing.SystemColors.Control;
            this.Check2.CausesValidation = true;
            this.Check2.Enabled = true;
            this.Check2.ForeColor = System.Drawing.SystemColors.ControlText;
            this.Check2.Cursor = System.Windows.Forms.Cursors.Default;
            this.Check2.RightToLeft = System.Windows.Forms.RightToLeft.No;
            this.Check2.Appearance = System.Windows.Forms.Appearance.Normal;
            this.Check2.TabStop = true;
            this.Check2.CheckState = System.Windows.Forms.CheckState.Unchecked;
            this.Check2.Visible = true;
            this.Check2.Name = "Check2";
            this.Check1.Text = "LED3";
            this.Check1.Size = new System.Drawing.Size(81, 17);
            this.Check1.Location = new System.Drawing.Point(40, 24);
            this.Check1.TabIndex = 2;
            this.Check1.Font = new System.Drawing.Font("Arial", 8f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
            this.Check1.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.Check1.BackColor = System.Drawing.SystemColors.Control;
            this.Check1.CausesValidation = true;
            this.Check1.Enabled = true;
            this.Check1.ForeColor = System.Drawing.SystemColors.ControlText;
            this.Check1.Cursor = System.Windows.Forms.Cursors.Default;
            this.Check1.RightToLeft = System.Windows.Forms.RightToLeft.No;
            this.Check1.Appearance = System.Windows.Forms.Appearance.Normal;
            this.Check1.TabStop = true;
            this.Check1.CheckState = System.Windows.Forms.CheckState.Unchecked;
            this.Check1.Visible = true;
            this.Check1.Name = "Check1";
            this.Command1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.Command1.Text = "Ok";
            this.AcceptButton = this.Command1;
            this.Command1.Size = new System.Drawing.Size(81, 25);
            this.Command1.Location = new System.Drawing.Point(256, 8);
            this.Command1.TabIndex = 1;
            this.Command1.Font = new System.Drawing.Font("Arial", 8f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
            this.Command1.BackColor = System.Drawing.SystemColors.Control;
            this.Command1.CausesValidation = true;
            this.Command1.Enabled = true;
            this.Command1.ForeColor = System.Drawing.SystemColors.ControlText;
            this.Command1.Cursor = System.Windows.Forms.Cursors.Default;
            this.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No;
            this.Command1.TabStop = true;
            this.Command1.Name = "Command1";
            this.Command2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.CancelButton = this.Command2;
            this.Command2.Text = "Cancel";
            this.Command2.Size = new System.Drawing.Size(81, 25);
            this.Command2.Location = new System.Drawing.Point(256, 40);
            this.Command2.TabIndex = 0;
            this.Command2.Font = new System.Drawing.Font("Arial", 8f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
            this.Command2.BackColor = System.Drawing.SystemColors.Control;
            this.Command2.CausesValidation = true;
            this.Command2.Enabled = true;
            this.Command2.ForeColor = System.Drawing.SystemColors.ControlText;
            this.Command2.Cursor = System.Windows.Forms.Cursors.Default;
            this.Command2.RightToLeft = System.Windows.Forms.RightToLeft.No;
            this.Command2.TabStop = true;
            this.Command2.Name = "Command2";
            this.Controls.Add(Text1);
            this.Controls.Add(Command3);
            this.Controls.Add(Check2);
            this.Controls.Add(Check1);
            this.Controls.Add(Command1);
            this.Controls.Add(Command2);
        }
        #endregion
        #region "Upgrade Support "
        private static Form1 m_vb6FormDefInstance;
        private static bool m_InitializingDefInstance;
        public static Form1 DefInstance {
            get {
                if (m_vb6FormDefInstance == null || m_vb6FormDefInstance.IsDisposed) {
                    m_InitializingDefInstance = true;
                    m_vb6FormDefInstance = new Form1();
                    m_InitializingDefInstance = false;
                }
                DefInstance = m_vb6FormDefInstance;
            }
            set { m_vb6FormDefInstance = value; }
        }
        #endregion
//UPGRADE_WARNING: Event Check1.CheckStateChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="vbup2075"'
        private void Check1_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
        {
            byte[] send_buf = new byte[65];
            byte[] receive_buf = new byte[65];

            int RecvLength = 0;

            VBMPUSBAPI.OpenMPUSBDevice();

            if (VBMPUSBAPI.myOutPipe != VBMPUSBAPI.INVALID_HANDLE_VALUE & VBMPUSBAPI.myInPipe != VBMPUSBAPI.INVALID_HANDLE_VALUE) {

                RecvLength = 1;


                send_buf[0] = 50;
                //0x32
                send_buf[1] = 3;
                if (Check1.CheckState == 1) {
                    send_buf[2] = 1;
                } else if (Check1.CheckState == 0) {
                    send_buf[2] = 0;
                }

                if ((VBMPUSBAPI.SendReceivePacket(ref send_buf, ref 3, ref receive_buf, ref RecvLength, 1000, 1000) == 1)) {

                    if ((RecvLength != 1 | receive_buf[0] != 50)) {
                        Interaction.MsgBox("Failed to update LED");
                    }

                }

            }

            VBMPUSBAPI.CloseMPUSBDevice();

        }

//UPGRADE_WARNING: Event Check2.CheckStateChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="vbup2075"'
        private void Check2_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
        {
            byte[] send_buf = new byte[65];
            byte[] receive_buf = new byte[65];

            int RecvLength = 0;

            VBMPUSBAPI.OpenMPUSBDevice();

            if (VBMPUSBAPI.myOutPipe != VBMPUSBAPI.INVALID_HANDLE_VALUE & VBMPUSBAPI.myInPipe != VBMPUSBAPI.INVALID_HANDLE_VALUE) {

                RecvLength = 1;


                send_buf[0] = 50;
                //0x32
                send_buf[1] = 4;
                if (Check2.CheckState == 1) {
                    send_buf[2] = 1;
                } else if (Check2.CheckState == 0) {
                    send_buf[2] = 0;
                }

                if ((VBMPUSBAPI.SendReceivePacket(ref send_buf, ref 3, ref receive_buf, ref RecvLength, 1000, 1000) == 1)) {

                    if ((RecvLength != 1 | receive_buf[0] != 50)) {

                        Interaction.MsgBox("Failed to update LED");

                    }

                }

            }

            VBMPUSBAPI.CloseMPUSBDevice();

        }

        private void Command1_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            this.Close();
        }

        private void Command2_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            System.Environment.Exit(0);
        }

        private void Command3_Click(System.Object eventSender, System.EventArgs eventArgs)
        {
            byte[] send_buf = new byte[65];
            byte[] receive_buf = new byte[65];

            int RecvLength = 0;

            VBMPUSBAPI.OpenMPUSBDevice();

            if (VBMPUSBAPI.myOutPipe != VBMPUSBAPI.INVALID_HANDLE_VALUE & VBMPUSBAPI.myInPipe != VBMPUSBAPI.INVALID_HANDLE_VALUE) {

                RecvLength = 4;

                send_buf[0] = 0;
                //0x0 - READ_VERSION
                send_buf[1] = 2;

                if ((VBMPUSBAPI.SendReceivePacket(ref send_buf, ref 2, ref receive_buf, ref RecvLength, 1000, 1000) == 1)) {

                    if ((RecvLength != 4 | receive_buf[0] != 0)) {

                        Interaction.MsgBox("Failed to obtain version information.");
                    } else {
                        Text1.Text = "Demo Version  " + Conversion.Str(receive_buf[3]) + "." + Conversion.Str(receive_buf[2]);

                    }

                }

            }

            VBMPUSBAPI.CloseMPUSBDevice();

        }

        private void Form1_Load(System.Object eventSender, System.EventArgs eventArgs)
        {
            VBMPUSBAPI.Initialize();

        }
    }
}

Moyano. ¿Crees que te puede dar una idea para empezar desde cero con C# lo mismo que VB .net?

No tengo mucha idea de VB, aún intentaré por mi lado pasarlo desde cero a C# al menos empezando el Form1 y botones antes de poner códigos.
 
Última edición:
Yo apostaria por el VB.net o VB 2008 , me parece mas accesible,sencillo,pero pregunto,hay mas info disponible en VC?:cry:
 
Yo no, MicroSoft Apuesta por el nuevo lenguaje C#, que para ello invirtió muchos millones de $$$$$$$ para su desarrollo y encima con los años quiere que se potencia C# y nos pasemos a C#. VB está porque aún se usa y no va a dejar colgado a las empresas.

Lee por San google de que M$ quiere que nos pasemos a C# y que C# tiene más ventaja que VB .net.

He notado en todo este año 2009 que la gente utiliz más C# que VB .net. En el instituto que estoy daremos C/C++, algo de VB y C# pero nos centraremos a C, en Web HP, Java, etc..

A ver si podemos hacer la conversión a C# manualmente.
 
Yo como vos meta apuesto 100% al C# pero VB.net es un lenguaje un poco más accesible en su entendimiento que C# pero de a poco creo que se puede hacer desde 0 ...aunque va a llevar tiempo. El secreto para mi es como ver como interactúa nuestro programa con las librerías de control....luego ver como se utilizan las funciones y listo...ahi tenemos nuestro programa de control ..pero no todo es tan facil como parece.

He estado haciendo pruebas en C# con MPUSBAPI.dll con exitos...en XP y vista...no probé en 7.

Aún sigo diseñando un programador clon del pickit2 para trabajar ..pero creo que cuando vuelva de mis vacaciones ya va a estar terminado.
 
Hola a todos, a ver jonathan a ver si me pudes ayudar con este problema de usar la libreria mpusbapi.dll, he estado haciendo el programa que me encontr por ahi,yo creo que algunos lo han usado,como importar, el mpusbapi.dll a visual C#, ahi encontre que hay que meterlo en carpeta donde se grabo el proyecto osea en"bin" y luego en "debug", bueno eso hice y puse lo siguiente codigo, cree una clase, y meti este codigo, que me encontre por ahi, que es para importar el DLL, pero al ejecutarlo me acaparece errores...
esta es la clase que cree!!!
es el USBAPI.CS
Código:
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using PVOID = System.IntPtr;
using DWORD = System.UInt32;
namespace PNCHE_HID_NO_FUNCIONA
{
    class USBAPI
    {
        #region Definición de los Strings: EndPoint y VID_PID
        string vid_pid_norm = "vid_04D8&pid_0020";
        string out_pipe = "[URL="file://mchp_ep1/"]\\MCHP_EP1[/URL]";
        string in_pipe = "[URL="file://mchp_ep1/"]\\MCHP_EP1[/URL]";
        #endregion
        #region Funciones importadas de la DLL: mpusbapi.dll
        [DllImport("mpusbapi.dll")]
        private static extern DWORD _MPUSBGetDLLVersion();
        [DllImport("mpusbapi.dll")]
        private static extern DWORD _MPUSBGetDeviceCount(string pVID_PID);
        [DllImport("mpusbapi.dll")]
        private static extern void* _MPUSBOpen(DWORD instance, string pVID_PID, string pEP, DWORD dwDir, DWORD dwReserved);
        [DllImport("mpusbapi.dll")]
        private static extern DWORD _MPUSBRead(void* handle, void* pData, DWORD dwLen, DWORD* pLength, DWORD dwMilliseconds);
        [DllImport("mpusbapi.dll")]
        private static extern DWORD _MPUSBWrite(void* handle, void* pData, DWORD dwLen, DWORD* pLength, DWORD dwMilliseconds);
        [DllImport("mpusbapi.dll")]
        private static extern DWORD _MPUSBReadInt(void* handle, DWORD* pData, DWORD dwLen, DWORD* pLength, DWORD dwMilliseconds);
        [DllImport("mpusbapi.dll")]
        private static extern bool _MPUSBClose(void* handle);
        #endregion
        void* myOutPipe;
        void* myInPipe;
        public void AbrirPipes()
        {
            DWORD seleccion = 0;
            myOutPipe = _MPUSBOpen(seleccion, vid_pid_norm, out_pipe, 0, 0);
            myInPipe = _MPUSBOpen(seleccion, vid_pid_norm, in_pipe, 1, 0);
        }
        //**** FUNCION CERRAR PIPE ****
        public void CerrarPipes()
        {
            _MPUSBClose(myOutPipe);
            _MPUSBClose(myInPipe);
        }
        /**** FUNCIONES ENVIO RECEPCION DE PAQUETES ******/
        private void EnvioPaquete(byte* SendPacket, DWORD SendLength)
        {
            uint Sendelay = 1000;
            DWORD SendDataLength;
            _MPUSBWrite(myOutPipe, (void*)SendPacket, SendLength, &SendDataLength, Sendelay);
        }
        private void ReciboPaquete(byte* ReceiveData, DWORD* ReceiveLength)
        {
            uint ReceiveDelay = 1000;
            DWORD ExpectReceiveLentgh = *ReceiveLength;
            _MPUSBRead(myInPipe, (void*)ReceiveData, ExpectReceiveLentgh, ReceiveLength, ReceiveDelay);
        }
        public void envio() {
            byte* send_buf = stackalloc byte[64];
            send_buf[0] = 0x00;
            send_buf[1] = 0x01; 
            send_buf[2] = 0x03;
            EnvioPaquete(send_buf, 64);
        }
    }
}

Este es el código que uso:
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;
namespace PNCHE_HID_NO_FUNCIONA
{
    public partial class Form1 : Form
    {
        USBAPI usb = new USBAPI();
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            usb.CerrarPipes();
            usb.AbrirPipes();
            usb.envio();
        }
    }
}

Los errores aparecen en las imágenes de abajo..
Lo que trato solo es enviar los 64 bytes y que solo tres de ellos me hagan que prenda o apague un LED.
Este es el código del PIC.

Código:
//=============================================
//AUTOR: JORGE ARTURO RDZ HDZ
//CODE: INICILIZA USB
//DATE:30/AGOSTO/09
//=============================================
#include <18F2550.h> // Definición de registros internos del PIC18F2550.
#fuses HSPLL,MCLR,NOWDT,NOPROTECT,NOLVP,NODEBUG,USBDIV,PLL5,CPUDIV1,VREGEN,NOPBADEN
// NOMCLR: No vamos ha usar el PIN MCLR, el reset se hará por soft.
// HSPLL: Vamos a usar un cristal de 20.00Mhz.
// NOWDT: No vamos a usar el perro guardian.
// NOPROTECT: Memoria no protejida contra lecturas.
// NODEBUG: No utilizamos código para debugear.
// NOLVP: No utilizamos el modo de programación con bajo voltaje.
// USBDIV: signfica que el clock del usb se tomará del PLL/2 = 96Mhz/2 = 48Mhz.
// PLL5: significa que el PLL prescaler no dividirá la frecuencia del cristal. para HS = 20Mhz.
// CPUDIV1: El PLL postscaler decide la división en 2 de la frecuencia de salida del PLL de 96MHZ, si queremos 48MHZ, lo dejamos como está.
// VREGEN: habilita el regulador de 3.3 volts que usa el módulo USB.
// NOPBADEN: Deshabilitamos el módulo conversor ADC del puerto B.
#use delay(clock=48000000)
#DEFINE USB_HID_DEVICE FALSE // NO Vamos a utilizar el protocolo HID.
#define USB_EP1_TX_ENABLE USB_ENABLE_BULK    // Definición del tamaño del buffer de salida.
#define USB_EP1_RX_ENABLE USB_ENABLE_BULK    // Definición del tamaño del buffer de entrada.
#define USB_EP1_TX_SIZE 64
#define USB_EP1_RX_SIZE 64
/*********************************************************************************************************/
// Definición de las librerías utilizadas.
#define USB_CON_SENSE_PIN PIN_C0
#include <pic18_usb.h>    // Drivers's USB del PIC18F2550.
#include <usb_desc_hid.h> // Descriptores USB.
#include <usb.c> // Funciones del USB.
/*********************************************************************************************************/
unsigned int data[64];
void main()
{
   usb_init_cs();    // Iniciamos el puerto USB y salimos.
   output_high(PIN_C6);
   output_low(PIN_C7);
   while(TRUE)
   {
            usb_task(); // Configuramos el puerto USB.
                  if (usb_enumerated()) // Si el puerto es enumerado y configurado por el host..
                  {
     output_low(PIN_C6);
     output_high(PIN_C7);
                     if (usb_kbhit(1)) 
                     {
                        usb_get_packet(1, data, 64);
      if(data[0]==1) output_toggle(PIN_A0);
      if(data[1]==2) output_toggle(PIN_A1);
      if(data[2]==3) output_toggle(PIN_A1);
                     }                                
                  }
   }
}
Ahora bien..he estado conectando el pic, y la laptop si lo detecta..pero me dice que no puede empezar el dispositivo..."the device cannot start (code10)"
Disculpa las molestias pero he etsado casi por un mes intentado y nada!!!!...no se si tengas un codigo en c# para probar...y empezar por ahi...
nota. uso windows xp sp3, y visual c# 2008 express. Espero con tus respuestas...
 

Adjuntos

  • ERRORES.JPG
    ERRORES.JPG
    132.1 KB · Visitas: 75
  • ERRORES_2.JPG
    ERRORES_2.JPG
    112.1 KB · Visitas: 50
Última edición por un moderador:
Que tal moyano, pedazo de tutorial que estas reailzando, se te agradece. Me he leído todo el post de este tema y vaya que me he enterado de varias cosas que no tenía en cuenta, el caso es que me quedan algunas dudas que no he podido entender y no puedo avanzar en mi proyecto sin esa parte, a ver si me pueden dar una ayudadita.

Te cuento, actualmente comienzo a trabajar con el módulo USB del PIC18F4550 para la primera parte de mi tesis de carrera. En esta primera parte tengo que desarrollar la comunicacion entre el microcontrolador y la PC, utilizando Labview del lado del PC, para controlar unos cuantos servos, hasta el momento son tres pero podrían ser mas según se desarrolle el proyecto. Bueno la cuestión es que un requisito es que sea desarrollado en ASM, algo más complicado que en C. Pero bueno me he puesto a leer las especificaciones del USB 2.0 y vaya que es bastante, nada más 650 pags y en inglés!!!!! XD así que me salte una buena parte y fui directo al capítulo donde explican el Framework del USB.

Pues voy configurando los registros del USB y los descriptores(En algunos campos de los descriptores todavía tengo dudas pero creo que van bien jeje) y he aquí mi gran duda donde no he podido avanzar más, ¿Cómo va lo de la enumeración del USB o cuáles son los pasos de esta? :confused: no lo entiendo :eek: a ver si me pueden ayudar en este tema, mientras sigo buscando en la red y si encuentro algo lo comento para que sepan también :). Y otra duda es que tipo de comunicación me convendría utilizar en este caso. Saludos.
 
Esta noche de navidad,ya que estoy al divino boton,me puse a armar una plaquita de entrenamiento con este PIC,y al tener un precio de 38 pesos,que es bajo teniendo en cuanta la cantidad de caracteristicas que tiene,tales como I2C,EEPROM,mucha FLASH,conversores A/D,puertos I/O,y sobre todo USB,es buena opcion como entrada a algun dispositivo mas grande,mucho mejor incluso que el famoso FTDI232 :D
PD: lo estoy haciendo en placa agujereada,porque tengo muuucha fiaca de hacer un PCB :D
 
Por ahora no se ha hablado ni hay proyectos en Linux con el tema del USB, pero si intenraré pasarlo a MonoDevelop con Linux cuando la versión de Windows está acabado y con el lenguaje C#.
 
Acabo de colocar al reves en el zocalo un 18F2550 no calento,pero al parecer fallecio...:cry: aunque sera que fallecio? lo estoy probando pero no se si no anda debido a eso o a que puse mal los FUSES,ustedes que opinan? :rolleyes:
 
He puesto al revés el 16F84A y se me cogió un calentón increible. Prueba con otro por si acaso, hay PIC muy sensibles si les lleva la contraria.
 
Acabo de colocar al reves en el zocalo un 18F2550 no calento,pero al parecer fallecio...:cry: aunque sera que fallecio? lo estoy probando pero no se si no anda debido a eso o a que puse mal los FUSES,ustedes que opinan? :rolleyes:

Murió amigo... que descanse en paz...
Las conecciones de VCC y masa se encuentran exactamente una frente a la otra, al conectarlo al revez muere instantáneamente.
Saludos.
 
Hola que tal, comento que estoy trabajando en un proyecto de leer pulsos, pero aun no hace eso, solo mantiene comunicacion con e ordenador
icon_sad.gif
, ya lo he probado en proteus y fisicamente; si funciona. Pero la lectura de pulsos lo simule en Proteus para visualizarle en hyperterminal y nada. Dejo aqui el codigo: (la comunicacion me base en los ejemplos de Jhonatan (y).
Código:
#include <18F2550.h> // Definición de registros internos.

#fuses HSPLL,NOMCLR,NOWDT,NOPROTECT,NOLVP,NODEBUG,USBDIV,PLL5,CPUDIV1,VREGEN,NOPBADEN

#use delay(clock=48000000) 
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)

#include "usb_cdc.h" // Descripción de funciones del USB.
#include "usb_desc_cdc.h" // Descriptores del dispositivo USB.

#define LED_V PIN_B6
#define LED_R PIN_B7

#define ON output_high
#define OFF output_low

int1 flag_listo = 0;
int16 cont_pulsos = 0;
int16 cont_pulsos_rec;

#INT_EXT
void interrupt_ext (void)
{
cont_pulsos++;
}

#INT_RTCC
void timer0 (void)
{
set_timer0(3036);
cont_pulsos_rec = cont_pulsos;
cont_pulsos = 0;
flag_listo = 1;
}


void main(void) {

   ON(LED_R);
   OFF(LED_V);
   
   usb_cdc_init(); 
   usb_init(); 
   usb_wait_for_enumeration();
   
   OFF(LED_R);            
   ON(LED_V);
   
   set_tris_b(0x01); 
   setup_timer_0 (RTCC_INTERNAL|RTCC_DIV_16);
   ext_int_edge(H_TO_L);    
   enable_interrupts(INT_RTCC);
   enable_interrupts(INT_EXT);
   enable_interrupts(GLOBAL);
   set_tris_b (1);
   set_timer0(3036);
   do{
   if(flag_listo)
   {
   flag_listo = 0;
   printf("Pulsos: %Lu\r\n",cont_pulsos_rec);
   }}while(1);
   
   
   
   
   while(!usb_cdc_connected()) {}
   // espera a detectar una transmisión de la PC (Set_Line_Coding).
   do{
      usb_task();
      if (usb_enumerated()){  // Espera a que el dispositivo sea enumerado por el host.
         if(usb_cdc_kbhit()){ // En espera de nuevos caracteres en el buffer de recepción.
            if(usb_cdc_getc()=='x'){ //¿lo que llegó fué el caracter x?
               printf(usb_cdc_putc, "Se recibe el caracter x.\n\r");
               //si, entonces envía una cadena hacia el PC
             }
            if(usb_cdc_getc()=='a'){ //¿lo que llegó fué el caracter a?
               printf(usb_cdc_putc, "Se recibe el caracter a.\n\r");
               //si, entonces envía una cadena hacia el PC
             }
         }
        }
       }while (TRUE); // bucle infinito.
}



aqui adjunto los archivos de proteus y el .hex por si acaso, al compilar el .hex no me genera errores, solo se comunica pero no manda los pulsos, los pulsos los simulo con un switch, bueno espero un ayudadita para que simule bien para probarlo fisicamente. :)
 

Adjuntos

  • SIMULAR PULSOS USB.rar
    28.5 KB · Visitas: 183
Hola a todos, alguien que me saque de esta duda, al utilizar la clase CDC del usb con el pic18f2550, se puede mandar datos a la hyperterminal para visualizarlos de manera virtual sin conectar el pin-c6 t pin_c7 fisicamente?
 
Atrás
Arriba