Перейти к содержанию

Pic18F4550 Проблема С Usb


92

Рекомендуемые сообщения

Здравствуйте уважаемые.

Изучаю как работать с USB на микроконтроллере PIC18F4550. Над данным контроллером провожу различные эксперименты, собрана небольшая платка для опытов.

К делу. Взял исходники из Микрочиповских примеров, в частности: Device - CDC - Serial Emulator (это из Microchip Solutions). Вроде бы понятна логика работы USB, но всё равно не заводиться.

Windows 7 выдаёт: USB устройство не опознано.

На плате стоит внешний кварц на 20Mhz

VID и PID в usb_descriptors.c заданы.

определён USB_POLLING

резисторы на D+/D- включены (пробовал даже внешние резисторы ставить)

FULL SPEED режим выбран.

Конфигурационные биты заданы в MPLAB'е:

PLLDIV: divide by 5

CPUDIV: Primary Osc /1, PLL /2

USBDIV: div by 2

FOSC: HSPLL

FCMEN disabled

IESO disabled

PWRT disabled

BOR disabled

VREGEN enabled

WDT disabled

STVREN enabled

Код main.c:

			lcd_clearScreen();
		USBDeviceInit();
		lcd_writeString("USB init OK");
		while(1)
		{
			USBDeviceTasks();
			if(USBGetDeviceState() < CONFIGURED_STATE || USBIsDeviceSuspended() == TRUE)
			{
				continue;
			}
			else
			{
				lcd_setCursor(0,8);
				lcd_writeString("USB ready");
				break;
			}
		}
		while(1)
		{

		}

До "USB ready" дело не доходит.

Выводил на экран события EVENT HANDLER'а, получал такое:

SUSPEND, WAKE, SUSPEND, WAKE, SOF, SOF, SOF, SOF, SOF, SOF... (тут винда пишет что устройство не опознано), SUSPEND

Иногда, вместо SOF'ов были парочка BUS ERROR'ов

По части железа:

земля с разьёма USB подключена к общей земле, +5V подключен к общей шине +5V, D+ и D- соответственно подключены (не перепутаны, проверял),

нога контроллера Vusb подключена через конденсатор 470нФ к земле.

Бьюсь два дня уже, прошу помощи.

usb_descriptors.c

/* Device Descriptor */
ROM 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
   0x000A,                 // Product ID
   0x0100,                 // Device release number in BCD format
   0x01,                   // Manufacturer string index
   0x02,                   // Product string index
   0x03,                   // Device serial number string index
   0x01                    // Number of possible configurations
};

/* Configuration 1 Descriptor */
ROM BYTE configDescriptor1[]={
   /* Configuration Descriptor */
   0x09,//sizeof(USB_CFG_DSC),    // Size of this descriptor in bytes
   USB_DESCRIPTOR_CONFIGURATION,                // CONFIGURATION descriptor type
   67,0,                   // Total length of data for this cfg
   2,                      // Number of interfaces in this cfg
   1,                      // Index value of this configuration
   0,                      // Configuration string index
   _DEFAULT,               // Attributes, see usb_device.h
   50,                     // Max power consumption (2X mA)

   /* Interface Descriptor */
   9,//sizeof(USB_INTF_DSC),   // Size of this descriptor in bytes
   USB_DESCRIPTOR_INTERFACE,               // INTERFACE descriptor type
   0,                      // Interface Number
   0,                      // Alternate Setting Number
   1,                      // Number of endpoints in this intf
   HID_INTF,              // Class code
   BOOT_INTF_SUBCLASS,	 // Subclass code
   HID_PROTOCOL_MOUSE,               // Protocol code
   0,                      // Interface string index

/* HID Class-Specific Descriptor */
   0x09,//sizeof(USB_HID_DSC)+3,    // Size of this descriptor in bytes RRoj hack
   DSC_HID,                // HID descriptor type
   DESC_CONFIG_WORD(0x0111),                 // 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
   DESC_CONFIG_WORD(50),   //sizeof(hid_rpt01),      // Size of the report descriptor

   /* Endpoint Descriptor */
   0x07,/*sizeof(USB_EP_DSC)*/
   USB_DESCRIPTOR_ENDPOINT,    //Endpoint Descriptor
   HID_EP | _EP_IN,            //EndpointAddress
   _INTERRUPT,                       //Attributes
   DESC_CONFIG_WORD(3),                  //size
   0x01                        //Interval                    //Interval
};


//Language code string descriptor
ROM struct{BYTE bLength;BYTE bDscType;WORD string[1];}sd000={
sizeof(sd000),USB_DESCRIPTOR_STRING,{0x0409}};

//Manufacturer string descriptor
ROM struct{BYTE bLength;BYTE bDscType;WORD string[25];}sd001={
sizeof(sd001),USB_DESCRIPTOR_STRING,
{'M','i','c','r','o','c','h','i','p',' ',
'T','e','c','h','n','o','l','o','g','y',' ','I','n','c','.'
}};

//Product string descriptor
ROM struct{BYTE bLength;BYTE bDscType;WORD string[25];}sd002={
sizeof(sd002),USB_DESCRIPTOR_STRING,
{'C','D','C',' ','R','S','-','2','3','2',' ',
'E','m','u','l','a','t','i','o','n',' ','D','e','m','o'}
};

//Class specific descriptor - HID mouse
ROM struct{BYTE report[HID_RPT01_SIZE];}hid_rpt01={
   {0x05, 0x01, /* Usage Page (Generic Desktop)             */
   0x09, 0x02, /* Usage (Mouse)                            */
   0xA1, 0x01, /* Collection (Application)                 */
   0x09, 0x01, /*  Usage (Pointer)                         */
   0xA1, 0x00, /*  Collection (Physical)                   */
   0x05, 0x09, /*      Usage Page (Buttons)                */
   0x19, 0x01, /*      Usage Minimum (01)                  */
   0x29, 0x03, /*      Usage Maximum (03)                  */
   0x15, 0x00, /*      Logical Minimum (0)                 */
   0x25, 0x01, /*      Logical Maximum (1)                 */
   0x95, 0x03, /*      Report Count (3)                    */
   0x75, 0x01, /*      Report Size (1)                     */
   0x81, 0x02, /*      Input (Data, Variable, Absolute)    */
   0x95, 0x01, /*      Report Count (1)                    */
   0x75, 0x05, /*      Report Size (5)                     */
   0x81, 0x01, /*      Input (Constant)    ;5 bit padding  */
   0x05, 0x01, /*      Usage Page (Generic Desktop)        */
   0x09, 0x30, /*      Usage (X)                           */
   0x09, 0x31, /*      Usage (Y)                           */
   0x15, 0x81, /*      Logical Minimum (-127)              */
   0x25, 0x7F, /*      Logical Maximum (127)               */
   0x75, 0x08, /*      Report Size (8)                     */
   0x95, 0x02, /*      Report Count (2)                    */
   0x81, 0x06, /*      Input (Data, Variable, Relative)    */
   0xC0, 0xC0}
};/* End Collection,End Collection            */

//Array of configuration descriptors
ROM BYTE *ROM USB_CD_Ptr[]=
{
   (ROM BYTE *ROM)&configDescriptor1
};
//Array of string descriptors
ROM BYTE *ROM USB_SD_Ptr[uSB_NUM_STRING_DESCRIPTORS]=
{
   (ROM BYTE *ROM)&sd000,
   (ROM BYTE *ROM)&sd001,
   (ROM BYTE *ROM)&sd002
};

usb_config.h

//#define USE_SELF_POWER_SENSE_IO
#define tris_self_power     TRISAbits.TRISA2    // Input
#if defined(USE_SELF_POWER_SENSE_IO)
#define self_power          PORTAbits.RA2
#else
#define self_power          1
#endif

//#define USE_USB_BUS_SENSE_IO
#define tris_usb_bus_sense  TRISAbits.TRISA1    // Input
#if defined(USE_USB_BUS_SENSE_IO)
#define USB_BUS_SENSE       PORTAbits.RA1
#else
#define USB_BUS_SENSE       1
#endif

/** DEFINITIONS ****************************************************/
#define USB_EP0_BUFF_SIZE		8	// Valid Options: 8, 16, 32, or 64 bytes.
							// Using larger options take more SRAM, but
							// does not provide much advantage in most types
							// of applications.  Exceptions to this, are applications
							// that use EP0 IN or OUT for sending large amounts of
							// application related data.

#define USB_MAX_NUM_INT     	2   // For tracking Alternate Setting

//Device descriptor - if these two definitions are not defined then
//  a ROM USB_DEVICE_DESCRIPTOR variable by the exact name of device_dsc
//  must exist.
#define USB_USER_DEVICE_DESCRIPTOR &device_dsc
#define USB_USER_DEVICE_DESCRIPTOR_INCLUDE extern ROM USB_DEVICE_DESCRIPTOR device_dsc

//Configuration descriptors - if these two definitions do not exist then
//  a ROM BYTE *ROM variable named exactly USB_CD_Ptr[] must exist.
#define USB_USER_CONFIG_DESCRIPTOR USB_CD_Ptr
#define USB_USER_CONFIG_DESCRIPTOR_INCLUDE extern ROM BYTE *ROM USB_CD_Ptr[]

//Make sure only one of the below "#define USB_PING_PONG_MODE"
//is uncommented.
//#define USB_PING_PONG_MODE USB_PING_PONG__NO_PING_PONG
#define USB_PING_PONG_MODE USB_PING_PONG__FULL_PING_PONG
//#define USB_PING_PONG_MODE USB_PING_PONG__EP0_OUT_ONLY
//#define USB_PING_PONG_MODE USB_PING_PONG__ALL_BUT_EP0		//NOTE: This mode is not supported in PIC18F4550 family rev A3 devices


#define USB_POLLING
//#define USB_INTERRUPT

/* Parameter definitions are defined in usb_device.h */
#define USB_PULLUP_OPTION USB_PULLUP_ENABLE
//#define USB_PULLUP_OPTION USB_PULLUP_DISABLED

#define USB_TRANSCEIVER_OPTION USB_INTERNAL_TRANSCEIVER
//External Transceiver support is not available on all product families.  Please
//  refer to the product family datasheet for more information if this feature
//  is available on the target processor.
//#define USB_TRANSCEIVER_OPTION USB_EXTERNAL_TRANSCEIVER

#define USB_SPEED_OPTION USB_FULL_SPEED
//#define USB_SPEED_OPTION USB_LOW_SPEED //(not valid option for PIC24F devices)

//------------------------------------------------------------------------------------------------------------------
//Option to enable auto-arming of the status stage of control transfers, if no
//"progress" has been made for the USB_STATUS_STAGE_TIMEOUT value.
//If progress is made (any successful transactions completing on EP0 IN or OUT)
//the timeout counter gets reset to the USB_STATUS_STAGE_TIMEOUT value.
//
//During normal control transfer processing, the USB stack or the application 
//firmware will call USBCtrlEPAllowStatusStage() as soon as the firmware is finished
//processing the control transfer.  Therefore, the status stage completes as 
//quickly as is physically possible.  The USB_ENABLE_STATUS_STAGE_TIMEOUTS 
//feature, and the USB_STATUS_STAGE_TIMEOUT value are only relevant, when:
//1.  The application uses the USBDeferStatusStage() API function, but never calls
//      USBCtrlEPAllowStatusStage().  Or:
//2.  The application uses host to device (OUT) control transfers with data stage,
//      and some abnormal error occurs, where the host might try to abort the control
//      transfer, before it has sent all of the data it claimed it was going to send.
//
//If the application firmware never uses the USBDeferStatusStage() API function,
//and it never uses host to device control transfers with data stage, then
//it is not required to enable the USB_ENABLE_STATUS_STAGE_TIMEOUTS feature.

#define USB_ENABLE_STATUS_STAGE_TIMEOUTS    //Comment this out to disable this feature.  

//Section 9.2.6 of the USB 2.0 specifications indicate that:
//1.  Control transfers with no data stage: Status stage must complete within 
//      50ms of the start of the control transfer.
//2.  Control transfers with (IN) data stage: Status stage must complete within 
//      50ms of sending the last IN data packet in fullfilment of the data stage.
//3.  Control transfers with (OUT) data stage: No specific status stage timing
//      requirement.  However, the total time of the entire control transfer (ex:
//      including the OUT data stage and IN status stage) must not exceed 5 seconds.
//
//Therefore, if the USB_ENABLE_STATUS_STAGE_TIMEOUTS feature is used, it is suggested
//to set the USB_STATUS_STAGE_TIMEOUT value to timeout in less than 50ms.  If the
//USB_ENABLE_STATUS_STAGE_TIMEOUTS feature is not enabled, then the USB_STATUS_STAGE_TIMEOUT
//parameter is not relevant.

#define USB_STATUS_STAGE_TIMEOUT     (BYTE)45   //Approximate timeout in milliseconds, except when
                                               //USB_POLLING mode is used, and USBDeviceTasks() is called at < 1kHz
                                               //In this special case, the timeout becomes approximately:
//Timeout(in milliseconds) = ((1000 * (USB_STATUS_STAGE_TIMEOUT - 1)) / (USBDeviceTasks() polling frequency in Hz))
//------------------------------------------------------------------------------------------------------------------

#define USB_SUPPORT_DEVICE

#define USB_NUM_STRING_DESCRIPTORS 3

//#define USB_INTERRUPT_LEGACY_CALLBACKS
#define USB_ENABLE_ALL_HANDLERS
//#define USB_ENABLE_SUSPEND_HANDLER
//#define USB_ENABLE_WAKEUP_FROM_SUSPEND_HANDLER
//#define USB_ENABLE_SOF_HANDLER
//#define USB_ENABLE_ERROR_HANDLER
//#define USB_ENABLE_OTHER_REQUEST_HANDLER
//#define USB_ENABLE_SET_DESCRIPTOR_HANDLER
//#define USB_ENABLE_INIT_EP_HANDLER
//#define USB_ENABLE_EP0_DATA_HANDLER
//#define USB_ENABLE_TRANSFER_COMPLETE_HANDLER

/** DEVICE CLASS USAGE *********************************************/
#define USB_USE_HID

/** ENDPOINTS ALLOCATION *******************************************/
#define USB_MAX_EP_NUMBER	    2

/* CDC */
#define CDC_COMM_INTF_ID        0x0
#define CDC_COMM_EP             1
#define CDC_COMM_IN_EP_SIZE     10

#define CDC_DATA_INTF_ID        0x01
#define CDC_DATA_EP             2
#define CDC_DATA_OUT_EP_SIZE    64
#define CDC_DATA_IN_EP_SIZE     64

#define USB_CDC_SET_LINE_CODING_HANDLER mySetLineCodingHandler

//------------------------------------------------------------------------------                                                
//Uncomment the "extra UART signals" that are desired to be enabled/supported.  
//These items are optional and none of them are required for basic RX and TX
//USB to UART translator devices.
//If one or more of the below options is enabled however, make sure that the
//polarity is selected correctly, and that the respective pin definitions 
//(ex: UART_RTS) and initialization macros (ex: mInitRTSPin()) are present and 
//defined correctly in the HardwareProfile - [platform name].h file.  
//------------------------------------------------------------------------------                                                
//#define USB_CDC_SUPPORT_DSR_REPORTING   //Signal from UART peripheral device, to CDC/USB host.  Indicates UART peripheral is ready to receive data and/or commands.
//#define USB_CDC_SUPPORT_DTR_SIGNALING   //Signal sent from the USB/CDC host, down to the UART peripheral device
//#define USB_CDC_SUPPORT_HARDWARE_FLOW_CONTROL   //Implements RTS/CTS UART flow control.

//RTS is GPIO output signal from CDC/USB host micro (indicates UART Rx buffer 
//   space available, and that the UART peripheral device is free to send data to the USB CDC micro)
//CTS is GPIO input on CDC/USB host micro (allows UART peripheral to tell the 
//   UART host [the USB micro] not to send anymore Tx data to it for awhile)

//Define the logic level for the "active" state.  Setting is only relevant if 
//the respective function is enabled.  Allowed options are:
//1 = active state logic level is Vdd
//0 = active state logic level is Vss
#define USB_CDC_CTS_ACTIVE_LEVEL    0
#define USB_CDC_RTS_ACTIVE_LEVEL    0
#define USB_CDC_DSR_ACTIVE_LEVEL    0
#define USB_CDC_DTR_ACTIVE_LEVEL    0                                      

//#define USB_CDC_SUPPORT_ABSTRACT_CONTROL_MANAGEMENT_CAPABILITIES_D2 //Send_Break command
#define USB_CDC_SUPPORT_ABSTRACT_CONTROL_MANAGEMENT_CAPABILITIES_D1 //Set_Line_Coding, Set_Control_Line_State, Get_Line_Coding, and Serial_State commands

/* HID */
#define HID_INTF_ID             0x00
#define HID_EP 					1
#define HID_INT_OUT_EP_SIZE     3
#define HID_INT_IN_EP_SIZE      3
#define HID_NUM_OF_DSC          1
#define HID_RPT01_SIZE          50

Изменено пользователем 92
Ссылка на комментарий
Поделиться на другие сайты

  • 3 года спустя...

Реклама: ООО ТД Промэлектроника, ИНН: 6659197470, Тел: 8 (800) 1000-321

20% скидка на весь каталог электронных компонентов в ТМ Электроникс!

Акция "Лето ближе - цены ниже", успей сделать выгодные покупки!

Плюс весь апрель действует скидка 10% по промокоду APREL24 + 15% кэшбэк и бесплатная доставка!

Перейти на страницу акции

Реклама: ООО ТМ ЭЛЕКТРОНИКС, ИНН: 7806548420, info@tmelectronics.ru, +7(812)4094849

Выбираем схему BMS для корректной работы литий-железофосфатных (LiFePO4) аккумуляторов

 Обязательным условием долгой и стабильной работы Li-FePO4-аккумуляторов, в том числе и производства EVE Energy, является применение специализированных BMS-микросхем. Литий-железофосфатные АКБ отличаются такими характеристиками, как высокая многократность циклов заряда-разряда, безопасность, возможность быстрой зарядки, устойчивость к буферному режиму работы и приемлемая стоимость. Но для этих АКБ, также как и для других, очень важен контроль процесса заряда и разряда, а специализированных микросхем для этого вида аккумуляторов не так много. Инженеры КОМПЭЛ подготовили список имеющихся микросхем и возможных решений от разных производителей. Подробнее>>

Реклама: АО КОМПЭЛ, ИНН: 7713005406, ОГРН: 1027700032161

Присоединяйтесь к обсуждению

Вы можете написать сейчас и зарегистрироваться позже. Если у вас есть аккаунт, авторизуйтесь, чтобы опубликовать от имени своего аккаунта.
Примечание: Ваш пост будет проверен модератором, прежде чем станет видимым.

Гость
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Ответить в этой теме...

×   Вставлено с форматированием.   Восстановить форматирование

  Разрешено использовать не более 75 эмодзи.

×   Ваша ссылка была автоматически встроена.   Отображать как обычную ссылку

×   Ваш предыдущий контент был восстановлен.   Очистить редактор

×   Вы не можете вставлять изображения напрямую. Загружайте или вставляйте изображения по ссылке.

Загрузка...
  • Последние посетители   0 пользователей онлайн

    • Ни одного зарегистрированного пользователя не просматривает данную страницу
×
×
  • Создать...