Ir ao conteúdo

Posts recomendados

Postado

Olá pessoal!!!!

Tenho um dispositivo que serve para conectar um mouse e um teclado para jogar no PS4, o dispositivo funciona corretamente com um teclado USB. Tenho um arduíno Leonardo que emula um teclado USB fiz um programa simples para testar no Notebook e funcionou corretamente. Tipo, quando o pino 3 for pra 1, envia a tecla A.

Minha dúvida e o seguinte, por que o dispositivo não está reconhecendo meu arduíno como teclado, sendo que no Notebook reconhece?

 

 

IMG_20210307_224808451.jpg

IMG_20210307_225320008_HDR.jpg

Postado

@vtrx @vtrx Desculpe minha ignorância mas o que seria descritor?

@Thiago Miotto Vou tentar explicar melhor. Quando conecto o Arduíno no notebook o RX do arduino pisca algumas vezes para estabelecer a comunicação. Quando aciono o pino 3 do arduino, o TX dele fica piscando contínuo e fica enviando o carácter A que é o que foi programado.  Quando conecto o Arduíno no dispositivo o RX pisca e acredito que estabeleceu a comunicação, mas quando aciono o pino 3 do arduino o TX pisca rapidamente e para, depois disso posso acionar novamente o pino 3 que o TX não volta a piscar. Eu não tenho muito conhecimento sobre essa comunicação mas acredito que e na hora de enviar o carácter que perder a comunicação.

Postado
Citação

Desculpe minha ignorância mas o que seria descritor?

Neste caso é melhor voce postar o código todo apara análise.

  • Curtir 1
Postado
1 hora atrás, Thiago Miotto disse:

 

Ele postou uma foto do código

@carlos.camj, quando postar código, copie ele, clique no símbolo <> aqui em cima e cole na tela que abre.

O que ele postou foi um fragmento.

Postou a rotina de inicialização e o looping principal para leitura do botão.

Caso seja um código retirado da net,post o link para ver se consigo achar o descritor.

  • Curtir 2
Postado
1 hora atrás, vtrx disse:

O que ele postou foi um fragmento.

Postou a rotina de inicialização e o looping principal para leitura do botão.

Caso seja um código retirado da net, post o link para ver se consigo achar o descritor.

Na IDE do arduino, o código é só isso mesmo.
Acho que você está falando da biblioteca do keyboard.

Se o autor não baixou a biblioteca de nenhum lugar, entrar em libreries no diretorio do arduino e ache entre as varias pastas o arquivo keyboard.h

  • Curtir 1
Postado

@Thiago Miotto @vtrxDescupe a demora, estava no trabalho. E o seguinte, eu peguei esse código nós exemplos na IDE do arduino ( segue foto em anexo) Eu exclui a parte do mouse e algumas outras. Deixei o programa simples só para enviar o carácter A em ASCII=97. Como Thiago disse, acho que você está querendo saber e do código fonte da biblioteca Keyboad.h. Verifiquei na biblioteca do arduino e achei esse código, acredito que é da biblioteca Keyboard.h. Não sei se fiz certo mais coloquei o código em word para poder anexar.


 

4 horas atrás, Thiago Miotto disse:

Na IDE do arduino, o código é só isso mesmo.
Acho que você está falando da biblioteca do keyboard.

Se o autor não baixou a biblioteca de nenhum lugar, entrar em libreries no diretorio do arduino e ache entre as varias pastas o arquivo keyboard.h

 

IMG_20210308_185718894_HDR.jpg

Keyboard.h.docx

Postado

Provavelmente o exemplo usa este descritor;

Link Arduino Keyboard

Não encontrei nada de diferente,mas a IDE Arduino é bem proprietária e precisa de instalar para encontar mais arquivos.

segundo a Net,precisava ver o arquivo que fica em;

hardware/arduino/sam/cores/arduino/Arduino.h 

E tambem em;

 hardware/arduino/sam/cores/arduino/USB/USBCore.cpp 

 

  • Curtir 2
Postado
#ifndef KEYBOARD_h
#define KEYBOARD_h

#include "HID.h"

#if !defined(_USING_HID)

#warning "Using legacy HID core (non pluggable)"

#else

//================================================================================
//================================================================================
//  Keyboard

#define KEY_LEFT_CTRL   0x80
#define KEY_LEFT_SHIFT    0x81
#define KEY_LEFT_ALT    0x82
#define KEY_LEFT_GUI    0x83
#define KEY_RIGHT_CTRL    0x84
#define KEY_RIGHT_SHIFT   0x85
#define KEY_RIGHT_ALT   0x86
#define KEY_RIGHT_GUI   0x87

#define KEY_UP_ARROW    0xDA
#define KEY_DOWN_ARROW    0xD9
#define KEY_LEFT_ARROW    0xD8
#define KEY_RIGHT_ARROW   0xD7
#define KEY_BACKSPACE   0xB2
#define KEY_TAB       0xB3
#define KEY_RETURN      0xB0
#define KEY_ESC       0xB1
#define KEY_INSERT      0xD1
#define KEY_DELETE      0xD4
#define KEY_PAGE_UP     0xD3
#define KEY_PAGE_DOWN   0xD6
#define KEY_HOME      0xD2
#define KEY_END       0xD5
#define KEY_CAPS_LOCK   0xC1
#define KEY_F1        0xC2
#define KEY_F2        0xC3
#define KEY_F3        0xC4
#define KEY_F4        0xC5
#define KEY_F5        0xC6
#define KEY_F6        0xC7
#define KEY_F7        0xC8
#define KEY_F8        0xC9
#define KEY_F9        0xCA
#define KEY_F10       0xCB
#define KEY_F11       0xCC
#define KEY_F12       0xCD
#define KEY_F13       0xF0
#define KEY_F14       0xF1
#define KEY_F15       0xF2
#define KEY_F16       0xF3
#define KEY_F17       0xF4
#define KEY_F18       0xF5
#define KEY_F19       0xF6
#define KEY_F20       0xF7
#define KEY_F21       0xF8
#define KEY_F22       0xF9
#define KEY_F23       0xFA
#define KEY_F24       0xFB


//  Low level key report: up to 6 keys and shift, ctrl etc at once
typedef struct
{
  uint8_t modifiers;
  uint8_t reserved;
  uint8_t keys[6];
} KeyReport;

class Keyboard_ : public Print
{
private:
  KeyReport _keyReport;
  void sendReport(KeyReport* keys);
public:
  Keyboard_(void);
  void begin(void);
  void end(void);
  size_t write(uint8_t k);
  size_t write(const uint8_t *buffer, size_t size);
  size_t press(uint8_t k);
  size_t release(uint8_t k);
  void releaseAll(void);
};
extern Keyboard_ Keyboard;

#endif
#endif

Baixei e coloquei aqui para facilitar

@carlos.camj Essa biblioteca usa outra. "HID.h"
Ache ela tb. Abra ela e cole aqui, como eu te disse da outra vez.

Postado

@Thiago Miotto Segue HID.h

/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.

This software may be distributed and modified under the terms of the GNU
General Public License version 2 (GPL2) as published by the Free Software
Foundation and appearing in the file GPL2.TXT included in the packaging of
this file. Please note that GPL2 Section 2[b] requires that all works based
on this software must also be made publicly available under the terms of
the GPL2 ("Copyleft").

Contact information
-------------------

Circuits At Home, LTD
Web      :  http://www.circuitsathome.com
e-mail   :  [email protected]
 */
#if !defined(__HID_H__)
#define __HID_H__

#include "Usb.h"
#include "hidusagestr.h"

#define MAX_REPORT_PARSERS                      2
#define HID_MAX_HID_CLASS_DESCRIPTORS           5

#define DATA_SIZE_MASK                          0x03
#define TYPE_MASK                               0x0C
#define TAG_MASK                                0xF0

#define DATA_SIZE_0                             0x00
#define DATA_SIZE_1                             0x01
#define DATA_SIZE_2                             0x02
#define DATA_SIZE_4                             0x03

#define TYPE_MAIN                               0x00
#define TYPE_GLOBAL                             0x04
#define TYPE_LOCAL                              0x08

#define TAG_MAIN_INPUT                          0x80
#define TAG_MAIN_OUTPUT                         0x90
#define TAG_MAIN_COLLECTION                     0xA0
#define TAG_MAIN_FEATURE                        0xB0
#define TAG_MAIN_ENDCOLLECTION                  0xC0

#define TAG_GLOBAL_USAGEPAGE                    0x00
#define TAG_GLOBAL_LOGICALMIN                   0x10
#define TAG_GLOBAL_LOGICALMAX                   0x20
#define TAG_GLOBAL_PHYSMIN                      0x30
#define TAG_GLOBAL_PHYSMAX                      0x40
#define TAG_GLOBAL_UNITEXP                      0x50
#define TAG_GLOBAL_UNIT                         0x60
#define TAG_GLOBAL_REPORTSIZE                   0x70
#define TAG_GLOBAL_REPORTID                     0x80
#define TAG_GLOBAL_REPORTCOUNT                  0x90
#define TAG_GLOBAL_PUSH                         0xA0
#define TAG_GLOBAL_POP                          0xB0

#define TAG_LOCAL_USAGE                         0x00
#define TAG_LOCAL_USAGEMIN                      0x10
#define TAG_LOCAL_USAGEMAX                      0x20

/* HID requests */
#define bmREQ_HID_OUT                           USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE
#define bmREQ_HID_IN                            USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE
#define bmREQ_HID_REPORT                        USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_INTERFACE

/* HID constants. Not part of chapter 9 */
/* Class-Specific Requests */
#define HID_REQUEST_GET_REPORT                  0x01
#define HID_REQUEST_GET_IDLE                    0x02
#define HID_REQUEST_GET_PROTOCOL                0x03
#define HID_REQUEST_SET_REPORT                  0x09
#define HID_REQUEST_SET_IDLE                    0x0A
#define HID_REQUEST_SET_PROTOCOL                0x0B

/* Class Descriptor Types */
#define HID_DESCRIPTOR_HID                      0x21
#define HID_DESCRIPTOR_REPORT                   0x22
#define HID_DESRIPTOR_PHY                       0x23

/* Protocol Selection */
#define HID_BOOT_PROTOCOL                       0x00
#define HID_RPT_PROTOCOL                        0x01

/* HID Interface Class Code */
#define HID_INTF                                0x03

/* HID Interface Class SubClass Codes */
#define HID_BOOT_INTF_SUBCLASS                  0x01

/* HID Interface Class Protocol Codes */
#define HID_PROTOCOL_NONE                       0x00
#define HID_PROTOCOL_KEYBOARD                   0x01
#define HID_PROTOCOL_MOUSE                      0x02

#define HID_ITEM_TYPE_MAIN                      0
#define HID_ITEM_TYPE_GLOBAL                    1
#define HID_ITEM_TYPE_LOCAL                     2
#define HID_ITEM_TYPE_RESERVED                  3

#define HID_LONG_ITEM_PREFIX                    0xfe    // Long item prefix value

#define bmHID_MAIN_ITEM_TAG                     0xfc    // Main item tag mask

#define bmHID_MAIN_ITEM_INPUT                   0x80    // Main item Input tag value
#define bmHID_MAIN_ITEM_OUTPUT                  0x90    // Main item Output tag value
#define bmHID_MAIN_ITEM_FEATURE                 0xb0    // Main item Feature tag value
#define bmHID_MAIN_ITEM_COLLECTION              0xa0    // Main item Collection tag value
#define bmHID_MAIN_ITEM_END_COLLECTION          0xce    // Main item End Collection tag value

#define HID_MAIN_ITEM_COLLECTION_PHYSICAL       0
#define HID_MAIN_ITEM_COLLECTION_APPLICATION    1
#define HID_MAIN_ITEM_COLLECTION_LOGICAL        2
#define HID_MAIN_ITEM_COLLECTION_REPORT         3
#define HID_MAIN_ITEM_COLLECTION_NAMED_ARRAY    4
#define HID_MAIN_ITEM_COLLECTION_USAGE_SWITCH   5
#define HID_MAIN_ITEM_COLLECTION_USAGE_MODIFIER 6

struct HidItemPrefix {
        uint8_t bSize : 2;
        uint8_t bType : 2;
        uint8_t bTag : 4;
};

struct MainItemIOFeature {
        uint8_t bmIsConstantOrData : 1;
        uint8_t bmIsArrayOrVariable : 1;
        uint8_t bmIsRelativeOrAbsolute : 1;
        uint8_t bmIsWrapOrNoWrap : 1;
        uint8_t bmIsNonLonearOrLinear : 1;
        uint8_t bmIsNoPreferedOrPrefered : 1;
        uint8_t bmIsNullOrNoNull : 1;
        uint8_t bmIsVolatileOrNonVolatile : 1;
};

class HID;

class HIDReportParser {
public:
        virtual void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) = 0;
};

class HID : public USBDeviceConfig, public UsbConfigXtracter {
protected:
        USB *pUsb; // USB class instance pointer
        uint8_t bAddress; // address

protected:
        static const uint8_t epInterruptInIndex = 1; // InterruptIN  endpoint index
        static const uint8_t epInterruptOutIndex = 2; // InterruptOUT endpoint index

        static const uint8_t maxHidInterfaces = 3;
        static const uint8_t maxEpPerInterface = 2;
        static const uint8_t totalEndpoints = (maxHidInterfaces * maxEpPerInterface + 1);

        void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr);
        void PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc);

        virtual HIDReportParser* GetReportParser(uint8_t id) {
                return NULL;
        };

public:

        HID(USB *pusb) : pUsb(pusb) {
        };

        const USB* GetUsb() {
                return pUsb;
        };

        virtual bool SetReportParser(uint8_t id, HIDReportParser *prs) {
                return false;
        };

        uint8_t SetProtocol(uint8_t iface, uint8_t protocol);
        uint8_t GetProtocol(uint8_t iface, uint8_t* dataptr);
        uint8_t GetIdle(uint8_t iface, uint8_t reportID, uint8_t* dataptr);
        uint8_t SetIdle(uint8_t iface, uint8_t reportID, uint8_t duration);

        uint8_t GetReportDescr(uint16_t wIndex, USBReadParser *parser = NULL);

        uint8_t GetHidDescr(uint8_t ep, uint16_t nbytes, uint8_t* dataptr);
        uint8_t GetReport(uint8_t ep, uint8_t iface, uint8_t report_type, uint8_t report_id, uint16_t nbytes, uint8_t* dataptr);
        uint8_t SetReport(uint8_t ep, uint8_t iface, uint8_t report_type, uint8_t report_id, uint16_t nbytes, uint8_t* dataptr);
};

#endif // __HID_H__

 

@vtrx Segue codigo que achei em C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\USBCore.cpp



/* Copyright (c) 2010, Peter Barrett
** Sleep/Wakeup support added by Michael Dreher
**  
** Permission to use, copy, modify, and/or distribute this software for  
** any purpose with or without fee is hereby granted, provided that the  
** above copyright notice and this permission notice appear in all copies.  
** 
** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL  
** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED  
** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR  
** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES  
** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,  
** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,  
** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS  
** SOFTWARE.  
*/

#include "USBAPI.h"
#include "PluggableUSB.h"
#include <stdlib.h>

#if defined(USBCON)

/** Pulse generation counters to keep track of the number of milliseconds remaining for each pulse type */
#define TX_RX_LED_PULSE_MS 100
volatile u8 TxLEDPulse; /**< Milliseconds remaining for data Tx LED pulse */
volatile u8 RxLEDPulse; /**< Milliseconds remaining for data Rx LED pulse */

//==================================================================
//==================================================================

extern const u16 STRING_LANGUAGE[] PROGMEM;
extern const u8 STRING_PRODUCT[] PROGMEM;
extern const u8 STRING_MANUFACTURER[] PROGMEM;
extern const DeviceDescriptor USB_DeviceDescriptorIAD PROGMEM;

const u16 STRING_LANGUAGE[2] = {
	(3<<8) | (2+2),
	0x0409	// English
};

#ifndef USB_PRODUCT
// If no product is provided, use USB IO Board
#define USB_PRODUCT     "USB IO Board"
#endif

const u8 STRING_PRODUCT[] PROGMEM = USB_PRODUCT;

#if USB_VID == 0x2341
#  if defined(USB_MANUFACTURER)
#    undef USB_MANUFACTURER
#  endif
#  define USB_MANUFACTURER "Arduino LLC"
#elif USB_VID == 0x1b4f
#  if defined(USB_MANUFACTURER)
#    undef USB_MANUFACTURER
#  endif
#  define USB_MANUFACTURER "SparkFun"
#elif !defined(USB_MANUFACTURER)
// Fall through to unknown if no manufacturer name was provided in a macro
#  define USB_MANUFACTURER "Unknown"
#endif

const u8 STRING_MANUFACTURER[] PROGMEM = USB_MANUFACTURER;


#define DEVICE_CLASS 0x02

//	DEVICE DESCRIPTOR
const DeviceDescriptor USB_DeviceDescriptorIAD =
	D_DEVICE(0xEF,0x02,0x01,64,USB_VID,USB_PID,0x100,IMANUFACTURER,IPRODUCT,ISERIAL,1);

//==================================================================
//==================================================================

volatile u8 _usbConfiguration = 0;
volatile u8 _usbCurrentStatus = 0; // meaning of bits see usb_20.pdf, Figure 9-4. Information Returned by a GetStatus() Request to a Device
volatile u8 _usbSuspendState = 0; // copy of UDINT to check SUSPI and WAKEUPI bits

static inline void WaitIN(void)
{
	while (!(UEINTX & (1<<TXINI)))
		;
}

static inline void ClearIN(void)
{
	UEINTX = ~(1<<TXINI);
}

static inline void WaitOUT(void)
{
	while (!(UEINTX & (1<<RXOUTI)))
		;
}

static inline u8 WaitForINOrOUT()
{
	while (!(UEINTX & ((1<<TXINI)|(1<<RXOUTI))))
		;
	return (UEINTX & (1<<RXOUTI)) == 0;
}

static inline void ClearOUT(void)
{
	UEINTX = ~(1<<RXOUTI);
}

static inline void Recv(volatile u8* data, u8 count)
{
	while (count--)
		*data++ = UEDATX;
	
	RXLED1;					// light the RX LED
	RxLEDPulse = TX_RX_LED_PULSE_MS;	
}

static inline u8 Recv8()
{
	RXLED1;					// light the RX LED
	RxLEDPulse = TX_RX_LED_PULSE_MS;

	return UEDATX;	
}

static inline void Send8(u8 d)
{
	UEDATX = d;
}

static inline void SetEP(u8 ep)
{
	UENUM = ep;
}

static inline u8 FifoByteCount()
{
	return UEBCLX;
}

static inline u8 ReceivedSetupInt()
{
	return UEINTX & (1<<RXSTPI);
}

static inline void ClearSetupInt()
{
	UEINTX = ~((1<<RXSTPI) | (1<<RXOUTI) | (1<<TXINI));
}

static inline void Stall()
{
	UECONX = (1<<STALLRQ) | (1<<EPEN);
}

static inline u8 ReadWriteAllowed()
{
	return UEINTX & (1<<RWAL);
}

static inline u8 Stalled()
{
	return UEINTX & (1<<STALLEDI);
}

static inline u8 FifoFree()
{
	return UEINTX & (1<<FIFOCON);
}

static inline void ReleaseRX()
{
	UEINTX = 0x6B;	// FIFOCON=0 NAKINI=1 RWAL=1 NAKOUTI=0 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=1
}

static inline void ReleaseTX()
{
	UEINTX = 0x3A;	// FIFOCON=0 NAKINI=0 RWAL=1 NAKOUTI=1 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=0
}

static inline u8 FrameNumber()
{
	return UDFNUML;
}

//==================================================================
//==================================================================

u8 USBGetConfiguration(void)
{
	return _usbConfiguration;
}

#define USB_RECV_TIMEOUT
class LockEP
{
	u8 _sreg;
public:
	LockEP(u8 ep) : _sreg(SREG)
	{
		cli();
		SetEP(ep & 7);
	}
	~LockEP()
	{
		SREG = _sreg;
	}
};

//	Number of bytes, assumes a rx endpoint
u8 USB_Available(u8 ep)
{
	LockEP lock(ep);
	return FifoByteCount();
}

//	Non Blocking receive
//	Return number of bytes read
int USB_Recv(u8 ep, void* d, int len)
{
	if (!_usbConfiguration || len < 0)
		return -1;
	
	LockEP lock(ep);
	u8 n = FifoByteCount();
	len = min(n,len);
	n = len;
	u8* dst = (u8*)d;
	while (n--)
		*dst++ = Recv8();
	if (len && !FifoByteCount())	// release empty buffer
		ReleaseRX();
	
	return len;
}

//	Recv 1 byte if ready
int USB_Recv(u8 ep)
{
	u8 c;
	if (USB_Recv(ep,&c,1) != 1)
		return -1;
	return c;
}

//	Space in send EP
u8 USB_SendSpace(u8 ep)
{
	LockEP lock(ep);
	if (!ReadWriteAllowed())
		return 0;
	return USB_EP_SIZE - FifoByteCount();
}

//	Blocking Send of data to an endpoint
int USB_Send(u8 ep, const void* d, int len)
{
	if (!_usbConfiguration)
		return -1;

	if (_usbSuspendState & (1<<SUSPI)) {
		//send a remote wakeup
		UDCON |= (1 << RMWKUP);
	}

	int r = len;
	const u8* data = (const u8*)d;
	u8 timeout = 250;		// 250ms timeout on send? TODO
	bool sendZlp = false;

	while (len || sendZlp)
	{
		u8 n = USB_SendSpace(ep);
		if (n == 0)
		{
			if (!(--timeout))
				return -1;
			delay(1);
			continue;
		}

		if (n > len) {
			n = len;
		}

		{
			LockEP lock(ep);
			// Frame may have been released by the SOF interrupt handler
			if (!ReadWriteAllowed())
				continue;

			len -= n;
			if (ep & TRANSFER_ZERO)
			{
				while (n--)
					Send8(0);
			}
			else if (ep & TRANSFER_PGM)
			{
				while (n--)
					Send8(pgm_read_byte(data++));
			}
			else
			{
				while (n--)
					Send8(*data++);
			}

			if (sendZlp) {
				ReleaseTX();
				sendZlp = false;
			} else if (!ReadWriteAllowed()) { // ...release if buffer is full...
				ReleaseTX();
				if (len == 0) sendZlp = true;
			} else if ((len == 0) && (ep & TRANSFER_RELEASE)) { // ...or if forced with TRANSFER_RELEASE
				// XXX: TRANSFER_RELEASE is never used can be removed?
				ReleaseTX();
			}
		}
	}
	TXLED1;					// light the TX LED
	TxLEDPulse = TX_RX_LED_PULSE_MS;
	return r;
}

u8 _initEndpoints[USB_ENDPOINTS] =
{
	0,                      // Control Endpoint
	
	EP_TYPE_INTERRUPT_IN,   // CDC_ENDPOINT_ACM
	EP_TYPE_BULK_OUT,       // CDC_ENDPOINT_OUT
	EP_TYPE_BULK_IN,        // CDC_ENDPOINT_IN

	// Following endpoints are automatically initialized to 0
};

#define EP_SINGLE_64 0x32	// EP0
#define EP_DOUBLE_64 0x36	// Other endpoints
#define EP_SINGLE_16 0x12

static
void InitEP(u8 index, u8 type, u8 size)
{
	UENUM = index;
	UECONX = (1<<EPEN);
	UECFG0X = type;
	UECFG1X = size;
}

static
void InitEndpoints()
{
	for (u8 i = 1; i < sizeof(_initEndpoints) && _initEndpoints[i] != 0; i++)
	{
		UENUM = i;
		UECONX = (1<<EPEN);
		UECFG0X = _initEndpoints[i];
#if USB_EP_SIZE == 16
		UECFG1X = EP_SINGLE_16;
#elif USB_EP_SIZE == 64
		UECFG1X = EP_DOUBLE_64;
#else
#error Unsupported value for USB_EP_SIZE
#endif
	}
	UERST = 0x7E;	// And reset them
	UERST = 0;
}

//	Handle CLASS_INTERFACE requests
static
bool ClassInterfaceRequest(USBSetup& setup)
{
	u8 i = setup.wIndex;

	if (CDC_ACM_INTERFACE == i)
		return CDC_Setup(setup);

#ifdef PLUGGABLE_USB_ENABLED
	return PluggableUSB().setup(setup);
#endif
	return false;
}

static int _cmark;
static int _cend;
void InitControl(int end)
{
	SetEP(0);
	_cmark = 0;
	_cend = end;
}

static
bool SendControl(u8 d)
{
	if (_cmark < _cend)
	{
		if (!WaitForINOrOUT())
			return false;
		Send8(d);
		if (!((_cmark + 1) & 0x3F))
			ClearIN();	// Fifo is full, release this packet
	}
	_cmark++;
	return true;
}

//	Clipped by _cmark/_cend
int USB_SendControl(u8 flags, const void* d, int len)
{
	int sent = len;
	const u8* data = (const u8*)d;
	bool pgm = flags & TRANSFER_PGM;
	while (len--)
	{
		u8 c = pgm ? pgm_read_byte(data++) : *data++;
		if (!SendControl(c))
			return -1;
	}
	return sent;
}

// Send a USB descriptor string. The string is stored in PROGMEM as a
// plain ASCII string but is sent out as UTF-16 with the correct 2-byte
// prefix
static bool USB_SendStringDescriptor(const u8*string_P, u8 string_len, uint8_t flags) {
        SendControl(2 + string_len * 2);
        SendControl(3);
        bool pgm = flags & TRANSFER_PGM;
        for(u8 i = 0; i < string_len; i++) {
                bool r = SendControl(pgm ? pgm_read_byte(&string_P[i]) : string_P[i]);
                r &= SendControl(0); // high byte
                if(!r) {
                        return false;
                }
        }
        return true;
}

//	Does not timeout or cross fifo boundaries
int USB_RecvControl(void* d, int len)
{
	auto length = len;
	while(length)
	{
		// Dont receive more than the USB Control EP has to offer
		// Use fixed 64 because control EP always have 64 bytes even on 16u2.
		auto recvLength = length;
		if(recvLength > 64){
			recvLength = 64;
		}

		// Write data to fit to the end (not the beginning) of the array
		WaitOUT();
		Recv((u8*)d + len - length, recvLength);
		ClearOUT();
		length -= recvLength;
	}
	return len;
}

static u8 SendInterfaces()
{
	u8 interfaces = 0;

	CDC_GetInterface(&interfaces);

#ifdef PLUGGABLE_USB_ENABLED
	PluggableUSB().getInterface(&interfaces);
#endif

	return interfaces;
}

//	Construct a dynamic configuration descriptor
//	This really needs dynamic endpoint allocation etc
//	TODO
static
bool SendConfiguration(int maxlen)
{
	//	Count and measure interfaces
	InitControl(0);
	u8 interfaces = SendInterfaces();
	ConfigDescriptor config = D_CONFIG(_cmark + sizeof(ConfigDescriptor),interfaces);

	//	Now send them
	InitControl(maxlen);
	USB_SendControl(0,&config,sizeof(ConfigDescriptor));
	SendInterfaces();
	return true;
}

static
bool SendDescriptor(USBSetup& setup)
{
	u8 t = setup.wValueH;
	if (USB_CONFIGURATION_DESCRIPTOR_TYPE == t)
		return SendConfiguration(setup.wLength);

	InitControl(setup.wLength);
#ifdef PLUGGABLE_USB_ENABLED
	int ret = PluggableUSB().getDescriptor(setup);
	if (ret != 0) {
		return (ret > 0 ? true : false);
	}
#endif

	const u8* desc_addr = 0;
	if (USB_DEVICE_DESCRIPTOR_TYPE == t)
	{
		desc_addr = (const u8*)&USB_DeviceDescriptorIAD;
	}
	else if (USB_STRING_DESCRIPTOR_TYPE == t)
	{
		if (setup.wValueL == 0) {
			desc_addr = (const u8*)&STRING_LANGUAGE;
		}
		else if (setup.wValueL == IPRODUCT) {
			return USB_SendStringDescriptor(STRING_PRODUCT, strlen(USB_PRODUCT), TRANSFER_PGM);
		}
		else if (setup.wValueL == IMANUFACTURER) {
			return USB_SendStringDescriptor(STRING_MANUFACTURER, strlen(USB_MANUFACTURER), TRANSFER_PGM);
		}
		else if (setup.wValueL == ISERIAL) {
#ifdef PLUGGABLE_USB_ENABLED
			char name[ISERIAL_MAX_LEN];
			PluggableUSB().getShortName(name);
			return USB_SendStringDescriptor((uint8_t*)name, strlen(name), 0);
#endif
		}
		else
			return false;
	}

	if (desc_addr == 0)
		return false;
	u8 desc_length = pgm_read_byte(desc_addr);

	USB_SendControl(TRANSFER_PGM,desc_addr,desc_length);
	return true;
}

//	Endpoint 0 interrupt
ISR(USB_COM_vect)
{
    SetEP(0);
	if (!ReceivedSetupInt())
		return;

	USBSetup setup;
	Recv((u8*)&setup,8);
	ClearSetupInt();

	u8 requestType = setup.bmRequestType;
	if (requestType & REQUEST_DEVICETOHOST)
		WaitIN();
	else
		ClearIN();

    bool ok = true;
	if (REQUEST_STANDARD == (requestType & REQUEST_TYPE))
	{
		//	Standard Requests
		u8 r = setup.bRequest;
		u16 wValue = setup.wValueL | (setup.wValueH << 8);
		if (GET_STATUS == r)
		{
			if (requestType == (REQUEST_DEVICETOHOST | REQUEST_STANDARD | REQUEST_DEVICE))
			{
				Send8(_usbCurrentStatus);
				Send8(0);
			}
			else
			{
				// TODO: handle the HALT state of an endpoint here
				// see "Figure 9-6. Information Returned by a GetStatus() Request to an Endpoint" in usb_20.pdf for more information
				Send8(0);
				Send8(0);
			}
		}
		else if (CLEAR_FEATURE == r)
		{
			if((requestType == (REQUEST_HOSTTODEVICE | REQUEST_STANDARD | REQUEST_DEVICE))
				&& (wValue == DEVICE_REMOTE_WAKEUP))
			{
				_usbCurrentStatus &= ~FEATURE_REMOTE_WAKEUP_ENABLED;
			}
		}
		else if (SET_FEATURE == r)
		{
			if((requestType == (REQUEST_HOSTTODEVICE | REQUEST_STANDARD | REQUEST_DEVICE))
				&& (wValue == DEVICE_REMOTE_WAKEUP))
			{
				_usbCurrentStatus |= FEATURE_REMOTE_WAKEUP_ENABLED;
			}
		}
		else if (SET_ADDRESS == r)
		{
			WaitIN();
			UDADDR = setup.wValueL | (1<<ADDEN);
		}
		else if (GET_DESCRIPTOR == r)
		{
			ok = SendDescriptor(setup);
		}
		else if (SET_DESCRIPTOR == r)
		{
			ok = false;
		}
		else if (GET_CONFIGURATION == r)
		{
			Send8(1);
		}
		else if (SET_CONFIGURATION == r)
		{
			if (REQUEST_DEVICE == (requestType & REQUEST_RECIPIENT))
			{
				InitEndpoints();
				_usbConfiguration = setup.wValueL;
			} else
				ok = false;
		}
		else if (GET_INTERFACE == r)
		{
		}
		else if (SET_INTERFACE == r)
		{
		}
	}
	else
	{
		InitControl(setup.wLength);		//	Max length of transfer
		ok = ClassInterfaceRequest(setup);
	}

	if (ok)
		ClearIN();
	else
	{
		Stall();
	}
}

void USB_Flush(u8 ep)
{
	SetEP(ep);
	if (FifoByteCount())
		ReleaseTX();
}

static inline void USB_ClockDisable()
{
#if defined(OTGPADE)
	USBCON = (USBCON & ~(1<<OTGPADE)) | (1<<FRZCLK); // freeze clock and disable VBUS Pad
#else // u2 Series
	USBCON = (1 << FRZCLK); // freeze clock
#endif
	PLLCSR &= ~(1<<PLLE);  // stop PLL
}

static inline void USB_ClockEnable()
{
#if defined(UHWCON)
	UHWCON |= (1<<UVREGE);			// power internal reg
#endif
	USBCON = (1<<USBE) | (1<<FRZCLK);	// clock frozen, usb enabled

// ATmega32U4
#if defined(PINDIV)
#if F_CPU == 16000000UL
	PLLCSR |= (1<<PINDIV);                   // Need 16 MHz xtal
#elif F_CPU == 8000000UL
	PLLCSR &= ~(1<<PINDIV);                  // Need  8 MHz xtal
#else
#error "Clock rate of F_CPU not supported"
#endif

#elif defined(__AVR_AT90USB82__) || defined(__AVR_AT90USB162__) || defined(__AVR_ATmega32U2__) || defined(__AVR_ATmega16U2__) || defined(__AVR_ATmega8U2__)
	// for the u2 Series the datasheet is confusing. On page 40 its called PINDIV and on page 290 its called PLLP0
#if F_CPU == 16000000UL
	// Need 16 MHz xtal
	PLLCSR |= (1 << PLLP0);
#elif F_CPU == 8000000UL
	// Need 8 MHz xtal
	PLLCSR &= ~(1 << PLLP0);
#endif

// AT90USB646, AT90USB647, AT90USB1286, AT90USB1287
#elif defined(PLLP2)
#if F_CPU == 16000000UL
#if defined(__AVR_AT90USB1286__) || defined(__AVR_AT90USB1287__)
	// For Atmel AT90USB128x only. Do not use with Atmel AT90USB64x.
	PLLCSR = (PLLCSR & ~(1<<PLLP1)) | ((1<<PLLP2) | (1<<PLLP0)); // Need 16 MHz xtal
#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB647__)
	// For AT90USB64x only. Do not use with AT90USB128x.
	PLLCSR = (PLLCSR & ~(1<<PLLP0)) | ((1<<PLLP2) | (1<<PLLP1)); // Need 16 MHz xtal
#else
#error "USB Chip not supported, please defined method of USB PLL initialization"
#endif
#elif F_CPU == 8000000UL
	// for Atmel AT90USB128x and AT90USB64x
	PLLCSR = (PLLCSR & ~(1<<PLLP2)) | ((1<<PLLP1) | (1<<PLLP0)); // Need 8 MHz xtal
#else
#error "Clock rate of F_CPU not supported"
#endif
#else
#error "USB Chip not supported, please defined method of USB PLL initialization"
#endif

	PLLCSR |= (1<<PLLE);
	while (!(PLLCSR & (1<<PLOCK)))		// wait for lock pll
	{
	}

	// Some tests on specific versions of macosx (10.7.3), reported some
	// strange behaviors when the board is reset using the serial
	// port touch at 1200 bps. This delay fixes this behavior.
	delay(1);
#if defined(OTGPADE)
	USBCON = (USBCON & ~(1<<FRZCLK)) | (1<<OTGPADE);	// start USB clock, enable VBUS Pad
#else
	USBCON &= ~(1 << FRZCLK);	// start USB clock
#endif

#if defined(RSTCPU)
#if defined(LSM)
	UDCON &= ~((1<<RSTCPU) | (1<<LSM) | (1<<RMWKUP) | (1<<DETACH));	// enable attach resistor, set full speed mode
#else // u2 Series
	UDCON &= ~((1 << RSTCPU) | (1 << RMWKUP) | (1 << DETACH));	// enable attach resistor, set full speed mode
#endif
#else
	// AT90USB64x and AT90USB128x don't have RSTCPU
	UDCON &= ~((1<<LSM) | (1<<RMWKUP) | (1<<DETACH));	// enable attach resistor, set full speed mode
#endif
}

//	General interrupt
ISR(USB_GEN_vect)
{
	u8 udint = UDINT;
	UDINT &= ~((1<<EORSTI) | (1<<SOFI)); // clear the IRQ flags for the IRQs which are handled here, except WAKEUPI and SUSPI (see below)

	//	End of Reset
	if (udint & (1<<EORSTI))
	{
		InitEP(0,EP_TYPE_CONTROL,EP_SINGLE_64);	// init ep0
		_usbConfiguration = 0;			// not configured yet
		UEIENX = 1 << RXSTPE;			// Enable interrupts for ep0
	}

	//	Start of Frame - happens every millisecond so we use it for TX and RX LED one-shot timing, too
	if (udint & (1<<SOFI))
	{
		USB_Flush(CDC_TX);				// Send a tx frame if found
		
		// check whether the one-shot period has elapsed.  if so, turn off the LED
		if (TxLEDPulse && !(--TxLEDPulse))
			TXLED0;
		if (RxLEDPulse && !(--RxLEDPulse))
			RXLED0;
	}

	// the WAKEUPI interrupt is triggered as soon as there are non-idle patterns on the data
	// lines. Thus, the WAKEUPI interrupt can occur even if the controller is not in the "suspend" mode.
	// Therefore the we enable it only when USB is suspended
	if (udint & (1<<WAKEUPI))
	{
		UDIEN = (UDIEN & ~(1<<WAKEUPE)) | (1<<SUSPE); // Disable interrupts for WAKEUP and enable interrupts for SUSPEND

		//TODO
		// WAKEUPI shall be cleared by software (USB clock inputs must be enabled before).
		//USB_ClockEnable();
		UDINT &= ~(1<<WAKEUPI);
		_usbSuspendState = (_usbSuspendState & ~(1<<SUSPI)) | (1<<WAKEUPI);
	}
	else if (udint & (1<<SUSPI)) // only one of the WAKEUPI / SUSPI bits can be active at time
	{
		UDIEN = (UDIEN & ~(1<<SUSPE)) | (1<<WAKEUPE); // Disable interrupts for SUSPEND and enable interrupts for WAKEUP

		//TODO
		//USB_ClockDisable();

		UDINT &= ~((1<<WAKEUPI) | (1<<SUSPI)); // clear any already pending WAKEUP IRQs and the SUSPI request
		_usbSuspendState = (_usbSuspendState & ~(1<<WAKEUPI)) | (1<<SUSPI);
	}
}

//	VBUS or counting frames
//	Any frame counting?
u8 USBConnected()
{
	u8 f = UDFNUML;
	delay(3);
	return f != UDFNUML;
}

//=======================================================================
//=======================================================================

USBDevice_ USBDevice;

USBDevice_::USBDevice_()
{
}

void USBDevice_::attach()
{
	_usbConfiguration = 0;
	_usbCurrentStatus = 0;
	_usbSuspendState = 0;
	USB_ClockEnable();

	UDINT &= ~((1<<WAKEUPI) | (1<<SUSPI)); // clear already pending WAKEUP / SUSPEND requests
	UDIEN = (1<<EORSTE) | (1<<SOFE) | (1<<SUSPE);	// Enable interrupts for EOR (End of Reset), SOF (start of frame) and SUSPEND
	
	TX_RX_LED_INIT;
}

void USBDevice_::detach()
{
}

//	Check for interrupts
//	TODO: VBUS detection
bool USBDevice_::configured()
{
	return _usbConfiguration;
}

void USBDevice_::poll()
{
}

bool USBDevice_::wakeupHost()
{
	// clear any previous wakeup request which might have been set but could be processed at that time
	// e.g. because the host was not suspended at that time
	UDCON &= ~(1 << RMWKUP);

	if(!(UDCON & (1 << RMWKUP))
	  && (_usbSuspendState & (1<<SUSPI))
	  && (_usbCurrentStatus & FEATURE_REMOTE_WAKEUP_ENABLED))
	{
		// This short version will only work, when the device has not been suspended. Currently the
		// Arduino core doesn't handle SUSPEND at all, so this is ok.
		USB_ClockEnable();
		UDCON |= (1 << RMWKUP); // send the wakeup request
		return true;
	}

	return false;
}

bool USBDevice_::isSuspended()
{
	return (_usbSuspendState & (1 << SUSPI));
}


#endif /* if defined(USBCON) */

 

@vtrx Segue código C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\Arduino.h

/*
  Arduino.h - Main include file for the Arduino SDK
  Copyright (c) 2005-2013 Arduino Team.  All right reserved.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#ifndef Arduino_h
#define Arduino_h

#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>

#include <avr/pgmspace.h>
#include <avr/io.h>
#include <avr/interrupt.h>

#include "binary.h"

#ifdef __cplusplus
extern "C"{
#endif

void yield(void);

#define HIGH 0x1
#define LOW  0x0

#define INPUT 0x0
#define OUTPUT 0x1
#define INPUT_PULLUP 0x2

#define PI 3.1415926535897932384626433832795
#define HALF_PI 1.5707963267948966192313216916398
#define TWO_PI 6.283185307179586476925286766559
#define DEG_TO_RAD 0.017453292519943295769236907684886
#define RAD_TO_DEG 57.295779513082320876798154814105
#define EULER 2.718281828459045235360287471352

#define SERIAL  0x0
#define DISPLAY 0x1

#define LSBFIRST 0
#define MSBFIRST 1

#define CHANGE 1
#define FALLING 2
#define RISING 3

#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
  #define DEFAULT 0
  #define EXTERNAL 1
  #define INTERNAL1V1 2
  #define INTERNAL INTERNAL1V1
#elif defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
  #define DEFAULT 0
  #define EXTERNAL 4
  #define INTERNAL1V1 8
  #define INTERNAL INTERNAL1V1
  #define INTERNAL2V56 9
  #define INTERNAL2V56_EXTCAP 13
#else  
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__)
#define INTERNAL1V1 2
#define INTERNAL2V56 3
#else
#define INTERNAL 3
#endif
#define DEFAULT 1
#define EXTERNAL 0
#endif

// undefine stdlib's abs if encountered
#ifdef abs
#undef abs
#endif

#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
#define abs(x) ((x)>0?(x):-(x))
#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))
#define round(x)     ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))
#define radians(deg) ((deg)*DEG_TO_RAD)
#define degrees(rad) ((rad)*RAD_TO_DEG)
#define sq(x) ((x)*(x))

#define interrupts() sei()
#define noInterrupts() cli()

#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )
#define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() )
#define microsecondsToClockCycles(a) ( (a) * clockCyclesPerMicrosecond() )

#define lowByte(w) ((uint8_t) ((w) & 0xff))
#define highByte(w) ((uint8_t) ((w) >> 8))

#define bitRead(value, bit) (((value) >> (bit)) & 0x01)
#define bitSet(value, bit) ((value) |= (1UL << (bit)))
#define bitClear(value, bit) ((value) &= ~(1UL << (bit)))
#define bitToggle(value, bit) ((value) ^= (1UL << (bit)))
#define bitWrite(value, bit, bitvalue) ((bitvalue) ? bitSet(value, bit) : bitClear(value, bit))

// avr-libc defines _NOP() since 1.6.2
#ifndef _NOP
#define _NOP() do { __asm__ volatile ("nop"); } while (0)
#endif

typedef unsigned int word;

#define bit(b) (1UL << (b))

typedef bool boolean;
typedef uint8_t byte;

void init(void);
void initVariant(void);

int atexit(void (*func)()) __attribute__((weak));

void pinMode(uint8_t pin, uint8_t mode);
void digitalWrite(uint8_t pin, uint8_t val);
int digitalRead(uint8_t pin);
int analogRead(uint8_t pin);
void analogReference(uint8_t mode);
void analogWrite(uint8_t pin, int val);

unsigned long millis(void);
unsigned long micros(void);
void delay(unsigned long ms);
void delayMicroseconds(unsigned int us);
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout);
unsigned long pulseInLong(uint8_t pin, uint8_t state, unsigned long timeout);

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val);
uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder);

void attachInterrupt(uint8_t interruptNum, void (*userFunc)(void), int mode);
void detachInterrupt(uint8_t interruptNum);

void setup(void);
void loop(void);

// Get the bit location within the hardware port of the given virtual pin.
// This comes from the pins_*.c file for the active board configuration.

#define analogInPinToBit(P) (P)

// On the ATmega1280, the addresses of some of the port registers are
// greater than 255, so we can't store them in uint8_t's.
extern const uint16_t PROGMEM port_to_mode_PGM[];
extern const uint16_t PROGMEM port_to_input_PGM[];
extern const uint16_t PROGMEM port_to_output_PGM[];

extern const uint8_t PROGMEM digital_pin_to_port_PGM[];
// extern const uint8_t PROGMEM digital_pin_to_bit_PGM[];
extern const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[];
extern const uint8_t PROGMEM digital_pin_to_timer_PGM[];

// Get the bit location within the hardware port of the given virtual pin.
// This comes from the pins_*.c file for the active board configuration.
// 
// These perform slightly better as macros compared to inline functions
//
#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )
#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )
#define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) )
#define analogInPinToBit(P) (P)
#define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) )
#define portInputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_input_PGM + (P))) )
#define portModeRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_mode_PGM + (P))) )

#define NOT_A_PIN 0
#define NOT_A_PORT 0

#define NOT_AN_INTERRUPT -1

#ifdef ARDUINO_MAIN
#define PA 1
#define PB 2
#define PC 3
#define PD 4
#define PE 5
#define PF 6
#define PG 7
#define PH 8
#define PJ 10
#define PK 11
#define PL 12
#endif

#define NOT_ON_TIMER 0
#define TIMER0A 1
#define TIMER0B 2
#define TIMER1A 3
#define TIMER1B 4
#define TIMER1C 5
#define TIMER2  6
#define TIMER2A 7
#define TIMER2B 8

#define TIMER3A 9
#define TIMER3B 10
#define TIMER3C 11
#define TIMER4A 12
#define TIMER4B 13
#define TIMER4C 14
#define TIMER4D 15
#define TIMER5A 16
#define TIMER5B 17
#define TIMER5C 18

#ifdef __cplusplus
} // extern "C"
#endif

#ifdef __cplusplus
#include "WCharacter.h"
#include "WString.h"
#include "HardwareSerial.h"
#include "USBAPI.h"
#if defined(HAVE_HWSERIAL0) && defined(HAVE_CDCSERIAL)
#error "Targets with both UART0 and CDC serial not supported"
#endif

uint16_t makeWord(uint16_t w);
uint16_t makeWord(byte h, byte l);

#define word(...) makeWord(__VA_ARGS__)

unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L);
unsigned long pulseInLong(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L);

void tone(uint8_t _pin, unsigned int frequency, unsigned long duration = 0);
void noTone(uint8_t _pin);

// WMath prototypes
long random(long);
long random(long, long);
void randomSeed(unsigned long);
long map(long, long, long, long, long);

#endif

#include "pins_arduino.h"

#endif

 

Postado

No arquivo USBCore.cpp,apague os # no trecho;

 

 

#if USB_VID == 0x2341
#  if defined(USB_MANUFACTURER)
#    undef USB_MANUFACTURER
#  endif
#  define USB_MANUFACTURER "Arduino LLC"
#elif USB_VID == 0x1b4f
#  if defined(USB_MANUFACTURER)
#    undef USB_MANUFACTURER
#  endif
#  define USB_MANUFACTURER "SparkFun"
#elif !defined(USB_MANUFACTURER)
// Fall through to unknown if no manufacturer name was provided in a macro
#  define USB_MANUFACTURER "Unknown"
#endif



-----------------------------
Deixe assim;

if USB_VID == 0x2341
  if defined(USB_MANUFACTURER)
    undef USB_MANUFACTURER
  endif
  define USB_MANUFACTURER "Arduino LLC"
elif USB_VID == 0x1b4f
  if defined(USB_MANUFACTURER)
    undef USB_MANUFACTURER
  endif
  define USB_MANUFACTURER "SparkFun"
elif !defined(USB_MANUFACTURER)
// Fall through to unknown if no manufacturer name was provided in a macro
  define USB_MANUFACTURER "Unknown"
endif

 

Se der algum erro,volte como estava.

Postado

Como citei,então volte como esta.

Procurando nos foruns Arduino,acho que achei o 'problema.

Traduzi para voce;

Citação

O Leonardo sempre ativa um dispositivo serial virtual quando está conectado a um computador. Durante a inicialização, ele está diretamente disponível para uploads por alguns segundos, após o qual o esboço programado é iniciado. Depois que o esboço é iniciado, não apenas esse esboço é executado, mas o IDE adiciona automaticamente o código ao programa carregado para ter um dispositivo serial virtual em execução em segundo plano, mesmo se você não usar o objeto Serial para enviar ou receber dados do computador de controle. Esse dispositivo está lá apenas para ouvir uma conexão. Se essa conexão estiver em 1200 baud e a conexão for encerrada imediatamente (sem enviar nenhum dado), esse é o sinal para o Leonardo de que o IDE deseja fazer o upload de um novo esboço e ele deve reiniciar automaticamente. Se essa funcionalidade não estiver incluída, você pode fazer o upload de um esboço pela conexão USB e nunca mais usá-lo para fazer o upload do esboço. Isso não é o que muitos usuários esperariam, então o pessoal do Arduino o implementou da maneira que a maioria dos usuários se sentem felizes

Conclusão,voce vai ter que programar a placa sem a IDE do Arduino,mas sim diretamente como se faz com uma interface comum.

 

Fonte:

https://forum.arduino.cc/index.php?topic=545288.0

  • Curtir 1
Postado

@vtrx Já voltei como tava. Puts ai complicou😭. Não tenho nem ideia como iria programar sem a IDE do Arduino. O PS4 e o Notebook reconhece o Leonardo como teclado, mas esse dispositivo não reconhece. Acho que não vai compensa o trabalho. Mas muito obrigado por me ajudar.

  • Membro VIP
Postado

Tentado traduzir a tradução ... a ide arduina grava algo oculto além do seu programa... grava o tal bootloader que é um 'programador virtual' (inventei isso agora) pro seus programas durante a fase de desenvolvimento. Pra não gravar o tal bootloader que 2º o amigo @vtrx supostamente está zoando seu barraco, você deve escolher o arquivo que não tem "...bootloader".hex no final e gravar por fora. Vai perder "pra sempre" a 'programabilidade' (inventei isso agora também) do seu dispositivo o que facilita o desenvolvimento. Isso é corrigível  com a aquisição de um "programador de verdade" por fora como p.ex. usbasp (clique) ou usar outro arduino pra programar seu arduino e regravar por fora o arquivo que finaliza com algo como ..._with_bootloader.hex

Postado

Ou, programar toda a porta USB em pinos, colocando uma 2ª USB que você terá controle total.

você poderá usar a IDE, mas terá que programar tudo.
Talvez haja material na net para você seguir por este caminho.
A vantagem é que assim você pode usar um arduino normal, até um nano, caso queira ganhar espaço, ou um mega, caso queira montar algo com muito sensores.

Postado
1 hora atrás, .if disse:

Tentado traduzir a tradução ... a ide arduina grava algo oculto além do seu programa... grava o tal bootloader que é um 'programador virtual' (inventei isso agora) pro seus programas durante a fase de desenvolvimento. Pra não gravar o tal bootloader que 2º o amigo @vtrx supostamente está zoando seu barraco, você deve escolher o arquivo que não tem "...bootloader".hex no final e gravar por fora. Vai perder "pra sempre" a 'programabilidade' (inventei isso agora também) do seu dispositivo o que facilita o desenvolvimento. Isso é corrigível  com a aquisição de um "programador de verdade" por fora como p.ex. usbasp (clique) ou usar outro arduino pra programar seu arduino e regravar por fora o arquivo que finaliza com algo como ..._with_bootloader.hex

Não detalhei tanto pois não utilizo a plataforma Arduino.

  • Membro VIP
Postado

Tem gente confusa por aqui... Ok... talvez seja eu. Mas penso que aquele adaptador não serve pra programar diretamente. É 1 simples conversor de passo: distância entre terminais. Quase semi inútil 🤪

aa8814cc3a.jpg

... além de ser facilmente substituível por um cabo usb qualquer. Algo me diz que você tem milhares de cabos de carregador, mouse quebrado e afins aí na sua gaveta 😁

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...

LANÇAMENTO!

eletronica2025-popup.jpg


CLIQUE AQUI E BAIXE AGORA MESMO!