I have an AS5045 magnetic rotation sensor. It provides 12-bit position data plus 6 status bits.
I can read the 18 bits into variable "packeddata".
I can use a mask and right shift 6 digits to dump the status bits.
I can right shift 8 digits to get a 4-bit binary position code.(Except that leading zeros disappear.)
If I knew how to paste the 4 bits into separate variables I could use XOR to turn the binary code into Gray code.
Please can someone tell me how to fill 4 variables with the bits from the 4-bit word in "angle", and suggest how to deal with the missing leading zeros. Here is amended code from Mad Scientist site.
const int ledPin = 13; //LED connected to digital pin 13
const int clockPin = 7; //output to clock
const int CSnPin = 6; //output to chip select
const int inputPin = 2; //read AS5040
int inputstream = 0; //one bit read from pin
long packeddata = 0; //two bytes concatenated from inputstream
long angle = 0; //holds processed angle value
long anglemask = 262080; // 0x111111111111000000: mask to obtain first 12 digits with position info
int shortdelay = 100; // this is the microseconds of delay in the data clock
int longdelay = 2000; // this is the milliseconds between readings
void setup()
{
Serial.begin(9600);
pinMode(ledPin, OUTPUT); // visual signal of I/O to chip
pinMode(clockPin, OUTPUT); // SCK
pinMode(CSnPin, OUTPUT); // CSn -- has to toggle high and low to signal chip to start data transfer
pinMode(inputPin, INPUT); // SDA
}
void loop()
{
// CSn needs to cycle from high to low to initiate transfer. Then clock cycles. As clock goes high
// again, data will appear on sda
digitalWrite(CSnPin, HIGH); // CSn high
digitalWrite(clockPin, HIGH); // CLK high
delay(longdelay);// time between readings
digitalWrite(CSnPin, LOW); // CSn low: start of transfer
delayMicroseconds(shortdelay); // delay for chip initialization
digitalWrite(clockPin, LOW); // CLK goes low: start clocking
delayMicroseconds(shortdelay); // hold low
for (int x=0; x <18; x++) // clock signal, 18 transitions, output to clock pin
{
digitalWrite(clockPin, HIGH); //clock goes high
delayMicroseconds(shortdelay); //
inputstream =digitalRead(inputPin); // read one bit of data from pin
packeddata = ((packeddata << 1) + inputstream);// left-shift to put next digit into next position
// word length 12 + 6 status bits.
digitalWrite(clockPin, LOW);
delayMicroseconds(shortdelay); // end of one clock cycle
}
// end of entire clock cycle
angle = packeddata & anglemask; // mask rightmost 6 digits of packeddata to zero, into angle.
angle = (angle >> 6); // shift 18-digit angle right 6 digits to form 12-digit value
angle = (angle >> 8);
Serial.println(angle, BIN);
angle = angle * 22.5; // *360/16
Serial.print("angle: ");
Serial.println(angle, DEC);
packeddata = 0; // reset both variables to zero so they don't just accumulate
angle = 0;
}