Arduino sample code for SPI absolute encoders
The AMT22 expects two bytes of 0x00 to be sent, and it returns data immediately after receiving these bytes. Due to this fast response, certain minimum timing requirements must be followed, which are outlined in the AMT22 datasheet. Regardless of whether the encoder is a 12-bit or 14-bit version, it always responds with two bytes (16 bits) of data. The upper two bits are check-bits, used to verify data integrity. For the 12-bit version, the lower two bits are both 0, and the returned value must be shifted right by 2 bits (or divided by 4) for proper use. To obtain position data, the SPI. transfer() function is called, sending the AMT22_NOP command. The CS line remains low during this process. The AMT22 sends the high byte first, so the received byte is shifted left by 8 bits to align it in the upper half of a uint16_t variable.
This value is assigned to the encoderPosition variable in one operation. After a brief delay to meet the timing requirements, a second SPI.transfer() call is made to send another AMT22_ NOP command. The result is OR'ed with the current value in encoderPosition, effectively combining the two received bytes into a single uint16_t variable. Finally, the CS line is released, completing the communication. Checksum verification After completing the SPI transfer, it is essential to validate the received data using a checksum (Listing 4). To implement this validation, a function can be created based on the equation provided in the datasheet. The checksum is contained in the upper two bits of the received value, and it utilizes odd parity across the odd and even bits in the position response.
The function will perform the following steps: 1. Calculate the parity for the odd bits (bits 1, 3, 5, 7, 9, 11, 13) 2. Calculate the parity for the even bits (bits 0, 2, 4, 6, 8, 10, 12, 14) 3. Compare the calculated parities against the values indicated by the checksum bits The function will return true if the checksum is valid, indicating that the data integrity is confirmed. If the checksum is invalid, the function will return false, signaling a potential error in the received data. Data formatting If the checksum validation confirms the integrity of the data, the next step is to update the encoderPosition variable by removing the upper two bits (Listing 5). This can be achieved by applying a bitwise
Listing 4: Validating the checksum.
50
Powered by FlippingBook