STM32 USB: GETTING STARTED.

Today even the cheapest MCUs have hardware usb, and at the same time this interface is the standard for connecting peripherals to a PC. I realized this long ago, but usb is quite complex and for a long time I didn't know how to approach it.

The problem is that, because data is exchanged continuously and at high speed, you can't debug it the usual way by setting a breakpoint. The exchange process itself is also fairly complex, so it helps to have a picture in front of you to better understand what is going on.
It turned out that a Chinese salea logic analyzer solves these problems: it records the data exchange between the device and the computer and decodes the packets.

Just a couple of words about the physical layer: the signal is transmitted over a differential pair, which makes high speeds possible. Depending on which of the two lines is pulled up to the supply, the device will operate as HS or FS.

The picture below shows very clearly how usb is implemented in software.
STM32 USB: GETTING STARTED.

It shows that once the device is connected, data is exchanged through endpoints.

You can think of an endpoint as a mailbox: the postman knows he has to drop letters into it, and you know you can collect letters from it. In the case of usb, the mailbox is the endpoint.

A very important aspect of usb is that communication is always initiated by the host, and the device can only respond to requests sent by the host. Let's create endpoint zero, which is intended for exchanging service information.

To do this, you need to understand how the communication works:
  • The device pulls one of the data lines up to the supply, which is how the host learns that it has been connected.
  • The host sends a reset signal on the bus. For the device this means that the host is going to talk to it and an endpoint needs to be created.


Let's put this into code.

Initializing usb.
void USB_Init(void)
{
	//enable clocking for the port and alternate functions
	RCC -> APB2ENR |= RCC_APB2ENR_IOPAEN | RCC_APB2ENR_AFIOEN;
	//configure the ports
	GPIOA->CRH &= ~GPIO_CRH_CNF11;
	GPIOA->CRH |= GPIO_CRH_CNF11_1;
	GPIOA->CRH |= GPIO_CRH_MODE11;
	
	GPIOA->CRH &= ~GPIO_CRH_CNF12;
	GPIOA->CRH |= GPIO_CRH_CNF12_1;
	GPIOA->CRH |= GPIO_CRH_MODE12;
	
        //disable the usb prescaler 
	RCC->CFGR &= ~RCC_CFGR_USBPRE;
        //enable usb clocking
	RCC -> APB1ENR |= RCC_APB1ENR_USBEN;
	//exit power down
	USB->CNTR &=~ USB_CNTR_PDWN; 
        //short delay
	uint32_t temp;
	for ( temp=30000; temp != 0; temp--);
	
	//clear the bit that resets usb
	USB->CNTR &=~ USB_CNTR_FRES;
	//enable RESET and CTRM (correct transfer interrupt mask) interrupts
	USB -> CNTR |= USB_CNTR_RESETM | USB_CNTR_CTRM;
	//clear the interrupt flags
	USB -> ISTR = 0;
	//the endpoint table starts at address 0x40006000
        USB -> BTABLE = 0;
        //pull the D+ pin up to the supply
	USB_PULL_UP
        //enable the data receive interrupt
	NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn);
}

You may be wondering what the endpoint table is.
Since usb packets can vary in length and be large, the MCU designers did not make a separate register for the transmitted/received data of each endpoint. Instead, they allocated a chunk of memory for this purpose!!! And so that the MCU knows where one endpoint ends and the next begins, a table is placed at the beginning of this memory.

So if we want to send data using endpoint zero, we write the data to the appropriate address. The MCU will do the rest for us.

Writing the interrupt handler.

void USB_LP_CAN1_RX0_IRQHandler()
{
	uint8_t n;
	if (USB -> ISTR & USB_ISTR_RESET)
        {
		//create endpoint 0, type CONTROL
		EP_Init(0, EP_TYPE_CONTROL, 128, 192);
		//create endpoint 1, type BULK
		EP_Init(1, EP_TYPE_BULK, 256, 320);
		//reset the device address
		USB -> DADDR = USB_DADDR_EF;
		//set the state to DEFAULT STATE
		USB_Dev.USB_Status = USB_DEFAULT_STATE;
	}
}


Creating an endpoint.

void EP_Init(uint8_t number, uint8_t type, uint32_t addr_tx, uint32_t addr_rx)
{
	USB -> EPnR[number] = (type << 9) | (number & USB_EPnR_EA);
	USB -> EPnR[number] ^= USB_EPnR_STAT_RX | USB_EPnR_STAT_TX_1;
	USB_BTABLE -> EP[number].USB_ADDR_TX = addr_tx;
	USB_BTABLE -> EP[number].USB_COUNT_TX = 0;
	USB_BTABLE -> EP[number].USB_ADDR_RX = addr_rx;
	USB_BTABLE -> EP[number].USB_COUNT_RX = 0x8400;	//receive buffer size
	endpoints[number].tx_buf = (uint16_t *)(USB_BTABLE_BASE + 2*addr_tx);
	endpoints[number].rx_buf = (uint8_t *)(USB_BTABLE_BASE + 2*addr_rx);
}


Now that the endpoint has been created, we can exchange data.
  • The host sends a GET_STATUS request. This is a kind of greeting to make sure the endpoint is configured, the device understands the host and further communication makes sense. It expects the device to report the default state status.
  • The host sends a GET_DESCRIPTOR request to obtain basic information about the device, including the maximum packet size for endpoint zero.


As for the device descriptor, I'll leave a table here that describes the purpose of each byte.
STM32 USB: GETTING STARTED.


This is where the fun begins. First, let's extend our interrupt handler code for the case when the MCU has successfully received data.

if (USB -> ISTR & USB_ISTR_CTR)
{
		//determine the number of the endpoint that triggered the interrupt
		n = USB -> ISTR & USB_ISTR_EP_ID;
		//copy the number of received bytes
		endpoints[n].rx_cnt = USB_BTABLE -> EP[n].USB_COUNT_RX;
		//copy the contents of this endpoint's EPnR
		endpoints[n].status = USB -> EPnR[n];
		//update the flag states
		endpoints[n].rx_flag = (endpoints[n].status & USB_EPnR_CTR_RX) ? 1 : 0;
		endpoints[n].setup_flag = (endpoints[n].status & USB_EPnR_SETUP) ? 1 : 0;
		endpoints[n].tx_flag = (endpoints[n].status & USB_EPnR_CTR_TX) ? 1 : 0;
		//clear the receive and transmit flags
		endpoints[n].status = CLEAR_CTR_RX_TX(endpoints[n].status);
		USB -> EPnR[n] = endpoints[n].status;
}


Now let's add functions for writing to and reading from endpoints.

void EP_Write(uint8_t number, uint8_t *buf, uint16_t size){
	uint8_t i;
	uint32_t timeout = 1000000;
	uint16_t status = USB -> EPnR[number];
	if (size > 64) size = 64;
	uint32_t *pv = (uint32_t*)(endpoints[number].tx_buf);
/*
 * WARNING: UGLY WORKAROUND
 * Because of a bug when writing to the USB/CAN SRAM area with 8-bit access
 * the array had to be packed into 16 bits, so the size is divided
 * by 2 if it was even, or divided by 2 plus 1 if it was odd
 */
	uint16_t temp = (size & 0x0001) ? (size + 1) / 2 : size / 2;
	for(i = 0; i < temp; i++, buf += 2)
  {
		*pv++ = *((uint16_t *)buf);
	}
	//Number of bytes to transmit
	USB_BTABLE -> EP[number].USB_COUNT_TX = size;

	status = KEEP_STAT_RX(status);		//RX to NAK
	status = SET_VALID_TX(status);		//TX to VALID
	status = KEEP_DTOG_TX(status);
	status = KEEP_DTOG_RX(status);
	USB -> EPnR[number] = status;

	endpoints[number].tx_flag = 0;
	while (!endpoints[number].tx_flag){
		if (timeout) timeout--;
		else break;
	}
}



/*
 * Function for reading an array from the endpoint buffer
 * number - endpoint number
 * *buf - address of the array to read the data into
 */
void EP_Read(uint8_t number, uint8_t *buf){
  uint32_t timeout = 100000;
  uint16_t status, i, n;
  uint32_t *pm = (uint32_t *)endpoints[number].rx_buf;
  uint16_t *p = (uint16_t *)buf; 
 
  status = USB -> EPnR[number];
  status = SET_VALID_RX(status);
  status = SET_NAK_TX(status);
  status = KEEP_DTOG_TX(status);
  status = KEEP_DTOG_RX(status);
  USB -> EPnR[number] = status;
  endpoints[number].rx_flag = 0;
  while (!endpoints[number].rx_flag){
      if (timeout) timeout--;
      else break;
  }
  n = (endpoints[number].rx_cnt & 0x01) ? (endpoints[number].rx_cnt + 1) / 2 : endpoints[number].rx_cnt / 2;
      for (i = 0; i < n; i++){
          p[i] = (uint16_t)pm[i];
      }
}


This article will definitely have a sequel, but for now I'll publish it as it is.