PIC 18f2550 USB HID application in C#

General discussion on mikroC PRO for PIC.
Post Reply
Author
Message
erBMB
Posts: 1
Joined: 10 Feb 2022 10:45

PIC 18f2550 USB HID application in C#

#1 Post by erBMB » 18 Feb 2022 16:55

Hello!!!

I am trying to connect PIC microcontroller with PC by USB cable in order to receive data from PIC 18F2550 microcontroller (in order to display it to a gauge in win form C# ) and send data to it in order to modify its EEPROM values.

I found an example that works (https://www.edaboard.com/threads/c-usb- ... or.344165/)BUT when I added the gauge, it stops after 2 seconds.
I created the gauge both in devexpress and syncfusion.
I think that one of the problem could be the difference versions of .net framework (usb hid library was made with version 3 but devexpress tools operates on a higher version) but I can`t solve it.

I have also tried with other hid libraries but the results were same: some of them were not compatible with windows forms, with others I could only receive data...

How could I achieve communication between PIC an PC ? Is there any tool made by mikroE (other than HID Terminal) in order to use data from PIC?



Image
Image
Image
https://www.edaboard.com/threads/c-usb- ... or.344165/

Code: Select all

   USB_Polling_Proc();
  kk = HID_Read();
  //if (kk != 0) {
    for(cnt=0; cnt < 64; cnt++)
      //writebuff[cnt]=readbuff[cnt];
       writebuff[1]=pActual;
       writebuff[2]=1;
           if(readbuff[0] == 1)
   {  for(i=0;i<10;i++){
       LATd1_bit = 1; Delay_ms(100); LATd1_bit = 0; Delay_ms(100);
     }
     readbuff[0] = 0;
   }
    if(readbuff[5] != 0)
   {
                   presetMin=readbuff[5];
     readbuff[0] = 0;
   }

Code: Select all

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UsbLibrary;

namespace USB_Term
{
    public partial class Form1 : Form
    {
        byte[] RecievedData = new byte[65];
        byte Tam = 0;
        byte Onda = 0;
        byte presiuneActuala = 0;
        byte presiuneMinima = 0;
        byte presiuneMaxima = 0;
        bool durum = false;
        private SpecifiedDevice device;
        private byte[] lastData = new byte[65];
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.usbHidPort1.ProductId = Int32.Parse("0001", System.Globalization.NumberStyles.HexNumber);
            this.usbHidPort1.VendorId = Int32.Parse("2DBC", System.Globalization.NumberStyles.HexNumber);
            usbHidPort1.CheckDevicePresent();
            if (durum)
            {
               toolStripStatusLabel1.ForeColor = Color.Green;
               toolStripStatusLabel1.Text = "USB Conectat";
            }
            else
            {
              toolStripStatusLabel1.ForeColor = Color.Red;
              toolStripStatusLabel1.Text = "Eroare USB";
            }
        }

        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);
            usbHidPort1.RegisterHandle(Handle);
        }

        protected override void WndProc(ref Message m)
        {
            usbHidPort1.ParseMessages(ref m);
            base.WndProc(ref m);
        }

        private void usbHidPort1_OnDataRecieved(object sender, DataRecievedEventArgs args)
        {
            if(device == null)
            {
                device = (SpecifiedDevice)sender;
            }

            



            double presiuneActualaVirgula = double.Parse(presiuneActuala.ToString());
            double presiuneMinimaVirgula = double.Parse(presiuneMinima.ToString());
            double presiuneMaximaVirgula = double.Parse(presiuneMaxima.ToString());

            if (InvokeRequired)
            {
                try
                {
                    Invoke(new DataRecievedEventHandler(usbHidPort1_OnDataRecieved), new object[] { sender, args });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            //
            else
            {
                RecievedData = args.data;
                Tam = RecievedData[2];
                Onda = RecievedData[3];
                label2.Text = Tam.ToString() + "," + Onda.ToString()+"°C";
                presiuneActuala = RecievedData[1];
                lblValPresiune.Text = (presiuneActualaVirgula/10).ToString();
                presiuneMinima = RecievedData[2];
                lblValPresiuneMinima.Text = (presiuneMinimaVirgula / 10).ToString();
                presiuneMaxima = RecievedData[3];
                radialGauge1.Value = presiuneActuala/10;
                lblValoarePresiuneMaxima.Text = (presiuneMaximaVirgula / 10).ToString();
                arcScaleNeedleComponent1.Value = (float)presiuneMinimaVirgula / 10;
            }

        }

        private void usbHidPort1_OnDataSend(object sender, EventArgs e)
        {
            
        }

        private void usbHidPort1_OnDeviceArrived(object sender, EventArgs e)
        {
          
        }

        private void usbHidPort1_OnDeviceRemoved(object sender, EventArgs e)
        {

        }

        private void usbHidPort1_OnSpecifiedDeviceArrived(object sender, EventArgs e)
        {
            toolStripStatusLabel1.ForeColor = Color.Green;
            toolStripStatusLabel1.Text = "USB Conectat";
            durum = true;
        }  

        private void usbHidPort1_OnSpecifiedDeviceRemoved(object sender, EventArgs e)
        {
            toolStripStatusLabel1.ForeColor = Color.Red;
            toolStripStatusLabel1.Text = "Eroare USB";
            label2.Text = "--,-°C";
            durum = false;
        }

        private void label2_Click(object sender, EventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {

            for(int x = 0; x < 64; x++)
            {
                lastData[x] = (byte)x;
            }

            device.SendData(lastData);

        }

        private void radialGauge1_Click(object sender, EventArgs e)
        {

        }

        private void radialGauge1_Click_1(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void btn_trimite_Click(object sender, EventArgs e)
        {

            
            byte[] data = new byte[64];
            data[5] = Convert.ToByte(15);
          


            //for (int x = 0; x < 64; x++)
            //{
            //    lastData[x] = (byte)x;
            //}

            //device.SendData(0);


        }

        private void lblPresiuneActuala_Click(object sender, EventArgs e)
        {

        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }
    }
}

Code: Select all

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HIDLib;
using System.Threading;
namespace WindowsFormsApplication1
{    public partial class Form1 : Form
    {   HIDDevice dev = new HIDDevice();
        
        public Form1()
        {   
            InitializeComponent();

            dev.vid = 0x2DBC;
            dev.pid = 0x0001;

            dev.in_size = 64;
            dev.out_size = 64;
            dev.Initialize();
            Thread timer = new Thread(ReadSerial);
            timer.Start();
        }
        private void DateTimeUpdate_Tick(object sender, EventArgs e)
        {
            lbDateTime.Text = DateTime.Now.ToString("dd/MM/yyyy  hh:mm:ss");
        }
 static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            int iLength = str.Length;
            //string strNull = null;
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            //System.Buffer.BlockCopy(strNull.ToCharArray(), 64-str.Length, bytes, 64-str.Length, 64);
            //System.Buffer.BlockCopy( null, 64 - str.Length, bytes, 64 - str.Length, 64);
            return bytes;
        }

        static string GetString(byte[] bytes)
        {
            char[] chars = new char[bytes.Length / sizeof(char)];
            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }
       //Ket thuc phan ham them vao ---dtn89
  protected override void WndProc(ref Message m)
           {
               dev.DeviceChange(ref m);
               base.WndProc(ref m);
               if (!dev.AttachedState) { lblPrimire.Text = "Disconnected!"; lblPrimire.ForeColor = Color.Red; }
               else { lblPrimire.Text = "Connected!"; lblPrimire.ForeColor = Color.Green; }
           }
private void timer1_Tick(object sender, EventArgs e)
        {
            byte[] data = new byte[64];
            byte[] str = new byte[64];
            data = dev.Receive();
            if (data != null)
            {
                lblDate.Text = data[6].ToString();
            }
        }
        public void ReadSerial()
        {

            while (true)
            {
                try
                {
                    byte[] data = new byte[64];
                    byte[] str = new byte[64];
                    data = dev.Receive();
                    if (data != null)
                    {
                        lblDate.Invoke(new MethodInvoker(delegate {lblDate.Text = data[6].ToString(); }));
                       
                    }
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                { MessageBox.Show(ex.ToString()); }

            }
        }

        private void btnPresMin_Click(object sender, EventArgs e)
        {
            int valCaseta1 = int.Parse(txtSetPresMin.Text.ToString());
            byte valCaseta = Convert.ToByte(valCaseta1);
            byte[] data = new byte[64];
            data[5] = valCaseta;
            if (!dev.Transmit(data)) MessageBox.Show("Device not ready");
        }

        private void btnPresMax_Click(object sender, EventArgs e)
        {
            int valCaseta1 = int.Parse(txtSetPresMax.Text.ToString());
            byte valCaseta = Convert.ToByte(valCaseta1);
            byte[] data = new byte[64];
            data[6] = valCaseta;
            if (!dev.Transmit(data)) MessageBox.Show("Device not ready");
        }

Post Reply

Return to “mikroC PRO for PIC General”