Поклонники продукции Microchip Technology Inc тусуются тут.
Ответить

PIC18F4550 и USB

Вт июл 30, 2019 20:43:48

Здрасте коты. Есть устройство на 18f4550 подключенное к пк через USB. Использую родную микрочиповскую MLA. Не пойму какого лешего не отображается дескриптор производителя в свойствах устройства. Модель видна, а производитель недоступно.
usb_descriptors.c
Код:
#ifndef __USB_DESCRIPTORS_C
#define __USB_DESCRIPTORS_C
#include "usb.h"
#include "usb_device_hid.h"

#if defined(__18CXX)
#pragma romdata
#endif
/* Device Descriptor */
const USB_DEVICE_DESCRIPTOR device_dsc=
{
    0x12,    // Size of this descriptor in bytes
    USB_DESCRIPTOR_DEVICE,                // DEVICE descriptor type
    0x0200,                 // USB Spec Release Number in BCD format
    0x00,                   // Class Code
    0x00,                   // Subclass code
    0x00,                   // Protocol code
    USB_EP0_BUFF_SIZE,          // Max packet size for EP0, see usb_config.h
    0x04D8,                 // Vendor ID
    0x003F,                 // Product ID: Custom HID device demo
    0x0100,                 // Device release number in BCD format
    0x01,                   // Manufacturer string index
    0x02,                   // Product string index
    0x00,                   // Device serial number string index
    0x01                    // Number of possible configurations
};

/* Configuration 1 Descriptor */
const uint8_t configDescriptor1[]={
    /* Configuration Descriptor */
    0x09,//sizeof(USB_CFG_DSC),    // Size of this descriptor in bytes
    USB_DESCRIPTOR_CONFIGURATION,                // CONFIGURATION descriptor type
    0x29,0x00,            // Total length of data for this cfg
    1,                      // Number of interfaces in this cfg
    1,                      // Index value of this configuration
    0,                      // Configuration string index
    _DEFAULT | _SELF,               // Attributes, see usb_device.h
    50,                     // Max power consumption (2X mA)
                     
    /* Interface Descriptor */
    0x09,//sizeof(USB_INTF_DSC),   // Size of this descriptor in bytes
    USB_DESCRIPTOR_INTERFACE,               // INTERFACE descriptor type
    0,                      // Interface Number
    0,                      // Alternate Setting Number
    2,                      // Number of endpoints in this intf
    HID_INTF,               // Class code
    0,     // Subclass code
    0,     // Protocol code
    0,                      // Interface string index

    /* HID Class-Specific Descriptor */
    0x09,//sizeof(USB_HID_DSC)+3,    // Size of this descriptor in bytes
    DSC_HID,                // HID descriptor type
    0x11,0x01,                 // HID Spec Release Number in BCD format (1.11)
    0x00,                   // Country Code (0x00 for Not supported)
    HID_NUM_OF_DSC,         // Number of class descriptors, see usbcfg.h
    DSC_RPT,                // Report descriptor type
    HID_RPT01_SIZE,0x00,//sizeof(hid_rpt01),      // Size of the report descriptor
   
    /* Endpoint Descriptor */
    0x07,/*sizeof(USB_EP_DSC)*/
    USB_DESCRIPTOR_ENDPOINT,    //Endpoint Descriptor
    CUSTOM_DEVICE_HID_EP | _EP_IN,                   //EndpointAddress
    _INTERRUPT,                       //Attributes
    0x40,0x00,                  //size
    0x01,                        //Interval

    /* Endpoint Descriptor */
    0x07,/*sizeof(USB_EP_DSC)*/
    USB_DESCRIPTOR_ENDPOINT,    //Endpoint Descriptor
    CUSTOM_DEVICE_HID_EP | _EP_OUT,                   //EndpointAddress
    _INTERRUPT,                       //Attributes
    0x40,0x00,                  //size
    0x01                        //Interval
};

//Language code string descriptor
const struct{uint8_t bLength;uint8_t bDscType;uint16_t string[1];}sd000={
sizeof(sd000),USB_DESCRIPTOR_STRING,{0x0409
}};

//Manufacturer string descriptor
const struct{uint8_t bLength;uint8_t bDscType;uint16_t string[20];}sd001={
sizeof(sd001),USB_DESCRIPTOR_STRING,
{'M','i','c','r','o','c','h','i','p',' ',
'P','I','C','1','8','F','4','5','5','0'
}};

//Product string descriptor
const struct{uint8_t bLength;uint8_t bDscType;uint16_t string[6];}sd002={
sizeof(sd002),USB_DESCRIPTOR_STRING,
{'P','i','с',' ','1','8'
}};

//Class specific descriptor - HID
const struct{uint8_t report[HID_RPT01_SIZE];}hid_rpt01={
{
    0x06, 0x00, 0xFF,       // Usage Page = 0xFF00 (Vendor Defined Page 1)
    0x09, 0x01,             // Usage (Vendor Usage 1)
    0xA1, 0x01,             // Collection (Application)
    0x19, 0x01,             //      Usage Minimum
    0x29, 0x40,             //      Usage Maximum   //64 input usages total (0x01 to 0x40)
    0x15, 0x00,             //      Logical Minimum (data bytes in the report may have minimum value = 0x00)
    0x26, 0xFF, 0x00,       //      Logical Maximum (data bytes in the report may have maximum value = 0x00FF = unsigned 255)
    0x75, 0x08,             //      Report Size: 8-bit field size
    0x95, 0x40,             //      Report Count: Make sixty-four 8-bit fields (the next time the parser hits an "Input", "Output", or "Feature" item)
    0x81, 0x00,             //      Input (Data, Array, Abs): Instantiates input packet fields based on the above report size, count, logical min/max, and usage.
    0x19, 0x01,             //      Usage Minimum
    0x29, 0x40,             //      Usage Maximum    //64 output usages total (0x01 to 0x40)
    0x91, 0x00,             //      Output (Data, Array, Abs): Instantiates output packet fields.  Uses same report size and count as "Input" fields, since nothing new/different was specified to the parser since the "Input" item.
    0xC0}                   // End Collection
};                 


const uint8_t *const USB_CD_Ptr[]=
{
    (const uint8_t *const)&configDescriptor1
};
const uint8_t *const USB_SD_Ptr[]=
{
    (const uint8_t *const)&sd000,
    (const uint8_t *const)&sd001,
    (const uint8_t *const)&sd002
};

#endif

Re: PIC18F4550 и USB

Пн авг 26, 2019 17:46:47

Добрый день, тоже мучаюсь с usb на PIC18F4550, коечего нашёл в гугле, даже примеры заработали, но есть вопросы.
Мне прегленулся HID протокол, но там беда с дескрипторами, и как Я понял в теле сосновной программы постоянно надо опрашивать одну функцию void ProcessIO(void), причём раз 1мс это помне так очень часто,хотя в одном из примеров, правда на AVR, там такаяж функция опрашивалась раз в 50 мс, уже лутше, но там этот протокол был организован программно на меге8, так Я вот поро что, а у этогож пика аппаратный USB неужели нет там передачи и приёма данных по прерываниям хотяб, чтоб не пришлось теребонькать так часто void ProcessIO(void) ?

Re: PIC18F4550 и USB

Ср авг 28, 2019 22:39:00

Уважаемый, чесное слово, я ничего не понял. Мучаться ни с чем не надо, все есть в MLA в том числе пример HID устройства. На стороне пк использую библиотеку HID API, там все просто:
Код:
#include <stdio.h>
#include <wchar.h>
#include <string.h>
#include <stdlib.h>
#include "hidapi.h"
 
int main(int argc, char* argv[])
{
    int res;
    unsigned char buf[256];
    hid_device *handle;
    hid_init();
    handle = hid_open(0x20A0, 0x4162, NULL); //VID, PID. серийный номер
 
    buf[0] = 0x15; //Номер репорта
    buf[1] = 0x01; //Младший байт
    buf[2] = 0x01; //Старший байт
    res = hid_write(handle, buf, 2); //Куда шлем, что шлем и сколько байт шлем
 
    hid_close(handle);
    hid_exit();
    return 0;
}

например так.

Добавлено after 1 hour 28 minutes 33 seconds:
Да кстати про вопрос в первом посту... дескрипторы производителя вообще всех hid устройств ввода (мышь, клава и др) у меня лично на пк вообще не отображаются. Кажется дело не на стороне мк. Поэтому я решил положить на это болт и не париться.

Добавлено after 52 minutes 1 second:
БАТАРЕЙКУС, Уважаемый, мне сейчас впадлу, но например завтра, если хотите, подкину вам проект-пустышку с реализацией hid и проект софтины на пк. дальше маштабируйте как душе угодно.

Добавлено after 34 minutes 46 seconds:
вроде убрал все лишнее но мог и чтото пропустить. Измерение напряжения на ноге AN0 и вывод результата в консольное окно на пк

Добавлено after 5 minutes 27 seconds:
2 собранные мной либы х86 и х64.

Добавлено after 1 minute 27 seconds:
сторона пк:
Код:
#include <windows.h>
#include <iostream>
#include "hidapi.h"

#pragma comment(lib, "hidapi.lib")
using namespace std;

#define COMMAND_READ_ADC 0x37

unsigned char buf[64];
unsigned char rew[64];

int main(int argc, char * argv[])
{
   
   hid_device *handle;
   if (hid_init()!=0) {
      cout << "hid library initialization error!" << endl;
      system("pause");
      return -1;
   }
   handle = hid_open(0x4D8, 0x3F, NULL);
   if (!handle) {
      cout << "unable to open device!" << endl;
      system("pause");
      return -2;
   }
   
   while (true)
   {
      memset(&buf,0x00, sizeof(buf));
      memset(&rew, 0x00, sizeof(buf));
      buf[1] = COMMAND_READ_ADC;
      hid_write(handle, buf, 64);
      hid_read(handle, rew, 64);
      unsigned int digital = (rew[0] * 256) | (rew[1]);
      float val = (float)digital * 5.06 / 1024;
      cout << "ADC channel 0 = " << val << " V";
      system("cls");
   }
   
   return 0;
}


Добавлено after 1 minute 31 second:
проверенно в железе. работает.
Вложения
18F4550 read adc.rar
консолька на пк
(43.14 KiB) Скачиваний: 196
hidapi.rar
(81.7 KiB) Скачиваний: 228
18F4550.rar
реализация HID из MLA уже и не помню какой версии
(62.19 KiB) Скачиваний: 200
Ответить