Created
June 15, 2017 12:02
-
-
Save troth/a8f3084f0a21dfba72b43e90bb751275 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SPI.h> | |
const int spiCSEncoderPin = 10; | |
void setup() | |
{ | |
Serial.begin(115200); | |
pinMode(spiCSEncoderPin, OUTPUT); | |
digitalWrite(spiCSEncoderPin, HIGH); | |
SPI.begin(); | |
} | |
static uint16_t readEncoder(); | |
void loop() | |
{ | |
uint16_t angle = readEncoder(); | |
Serial.println(angle, DEC); | |
delay(10); | |
} | |
/* | |
* Encoder is an AS5147P (On Axis, Magnetic Encoder). | |
* It communicates via SPI using MODE=1 (CPOL=0, CPHA=1). | |
* 10 MHz max clock rate. | |
* Data word is 16 bits. | |
* Bit order is MSB first. | |
*/ | |
#define PARC_BIT (1 << 15) | |
#define RD_BIT (1 << 14) | |
#define ERR_BIT (1 << 14) | |
#define CMD_RD_NOP (0x0000 | RD_BIT | PARC_BIT) | |
#define CMD_RD_ERRFL (0x0001 | RD_BIT) | |
#define CMD_RD_ANGLECOM (0x3fff | RD_BIT | PARC_BIT) | |
static const uint16_t cmd_rd_errfl = CMD_RD_ERRFL; | |
static const uint16_t cmd_rd_angle = CMD_RD_ANGLECOM; | |
static const uint16_t cmd_rd_nop = CMD_RD_NOP; | |
static uint16_t readEncoder() | |
{ | |
uint16_t err; | |
uint16_t data; | |
SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE1)); | |
digitalWrite(spiCSEncoderPin, LOW); | |
SPI.transfer16(cmd_rd_angle); | |
digitalWrite(spiCSEncoderPin, HIGH); | |
digitalWrite(spiCSEncoderPin, LOW); | |
data = SPI.transfer16(cmd_rd_errfl); | |
digitalWrite(spiCSEncoderPin, HIGH); | |
digitalWrite(spiCSEncoderPin, LOW); | |
err = SPI.transfer16(cmd_rd_nop); | |
digitalWrite(spiCSEncoderPin, HIGH); | |
SPI.endTransaction(); | |
if (data & ERR_BIT) { | |
Serial.print("ERROR:"); | |
Serial.println(err, HEX); | |
} | |
return (data & 0x3fff); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment