28.3.2.2 SETUP

When a SETUP token is detected and if the device address n of the token packet does not match the endpoint, the packet is discarded, and the USB peripheral returns to idle and waits for the next token packet.

When the address matches, the USB peripheral then fetches the Endpoint Status (EP[n].[dir].STATUS) register and Endpoint Control (EP[n].[dir].CTRL) register from the addressed output endpoint in the endpoint configuration table. If the endpoint type is not a Control endpoint, the USB peripheral returns to idle and waits for the next token packet.

Figure 28-4. SETUP Transaction

If the endpoint type matches, the USB peripheral then fetches the Endpoint Data Pointer (EP[n].[dir].DATAPTR) register and waits for a DATA0 packet. If a PID error or any other PID than DATA0 is detected, the USB peripheral returns to idle and waits for the next token packet.

When the data PID matches, the incoming data are written to the data buffer pointed to by DATAPTR. If detecting a bit-stuff error in the incoming data, the USB peripheral returns to idle and waits for the next token packet. If the number of received data bytes exceeds the endpoint’s maximum data payload size, as specified by the Data Size (BUFSIZE) bit field in CTRL, the remainder of the received data bytes are discarded. The packet will still be checked for bit-stuff and CRC errors. Eight bytes are written to RAM independent of the maximum payload specified by BUFSIZE, as SETUP transactions always have eight data bytes. If there was a bit-stuff or CRC error in the packet, the USB peripheral returns to idle and waits for the next token packet.

If data are successfully received, an ACK handshake is returned to the host, and the number of received data bytes, excluding the CRC, is written to the Endpoint Byte Counter (EP[n].[dir].CNT) register.

Finally, the Endpoint SETUP Complete Flag (EPSETUP), the Data Buffer Not Acknowledge Flag (BUSNAK), and the Data Toggle Flag (TOGGLE) are set when the remaining flags in STATUS are cleared for both the addressed input and output endpoints. If the Automatic Global NAK (GNAUTO) bit in the Control B (USB.CTRLB) register is ‘1’, the Global NAK (GNAK) bit in CTRLB is set. The BUSNAK bit, and possibly the GNAK bit, is set to ensure that the USB peripheral will NAK all future IN and OUT transactions until the FW is ready to process them. The ACK response for setup tokens is not affected by GNAK or BUSNAK. The Setup Transaction Complete Interrupt Flag (SETUP) in the Interrupt Flags B (USB.INTFLAGSB) register is set.

Control transfers use the endpoint buffers differently from IN and OUT endpoints. The data packet in the Setup stage is stored in the endpoint’s OUT data buffer, while data packets in the Data stage (i.e., IN or OUT) are stored in the IN data buffer. In other words, EP[n].OUT.DATAPTR points to the received Setup stage packet and EP[n].IN.DATAPTR points to data to be transmitted or received in the Data stage.