Skip to content

Instantly share code, notes, and snippets.

@stephanschulz
Created December 11, 2019 20:00
Show Gist options
  • Select an option

  • Save stephanschulz/127c5b1c3203587fdf1bb92d111e9e14 to your computer and use it in GitHub Desktop.

Select an option

Save stephanschulz/127c5b1c3203587fdf1bb92d111e9e14 to your computer and use it in GitHub Desktop.
void makeTransfer()
{
digitalWrite(CS_PIN, LOW);
digitalWriteFast(SCK_PIN, LOW); // Set CLK line LOW (to inform encoder -> latch data)
delayMicroseconds(1); // Running above 500kHz perform Delay First Clock function
SPI.begin();
// uint8_t pinIndex = SCK_PIN_13_INDEX;
// volatile uint32_t* reg = portConfigRegister(SPIClass::spi0_hardware.sck_pin[pinIndex]);
// reg = SPIClass::spi0_hardware.sck_mux[pinIndex];
SPI.beginTransaction(settingsA); // We use transactional API
uint8_t fcc = SPI.transfer(0x00); // and in fcc you get First Command Char from Figure 1 in datasheet
uint8_t scc = SPI.transfer(0x00); // and in scc you get Second Command Char from Figure 1 in datasheet
SPI.endTransaction(); // We use transactional API
pinMode(SCK_PIN, OUTPUT); // A while before we set CLK pin to be used by SPI port, now we have to change it manually...
// digitalWriteFast(SCK_PIN, LOW);
digitalWriteFast(SCK_PIN, HIGH); // ... back to idle HIGH
digitalWrite(CS_PIN, HIGH);
// now calculate 12bit position data combining fcc and scc and using datasheet approach:
uint16_t positionData = (static_cast<uint16_t >(fcc) << 8) | static_cast<uint16_t >(scc);
Serial.println();
Serial.print("fcc \t");
Serial.print(fcc, DEC);
Serial.print(" :\t ");
Serial.print(fcc, BIN);
Serial.println();
Serial.print("scc \t");
Serial.print(scc, DEC);
Serial.print(" :\t ");
Serial.print(scc, BIN);
Serial.println();
Serial.print("comb \t");
Serial.print(positionData, DEC);
Serial.print(" :\t ");
Serial.print(positionData, BIN);
Serial.println();
positionData = positionData >> 2; // maybe it's all about - 12-bit data will need right-shifted two bits
Serial.print("shif \t");
Serial.print(positionData, DEC);
Serial.print(" :\t ");
Serial.print(positionData, BIN);
// Serial.println();
float angle = (positionData / (float)(1 << 12)) * 360.0;
Serial.print("\t\tangle ");
Serial.print(angle);
// Serial.println();
angle = ((positionData - 8190) / (float)(1 << 13)) * 360.0;;
Serial.print("\t\tsubt ");
Serial.print(angle);
Serial.println();
positionData = positionData & 0x0FFF; // then mask K1, K0, D14 and D13 and you will get 12 bit position data.
Serial.print("mask \t");
Serial.print(positionData, DEC);
Serial.print(" :\t ");
Serial.print(positionData, BIN);
// Serial.println();
angle = (positionData / (float)(1 << 12)) * 360.0;
Serial.print("\t\tangle ");
Serial.print(angle);
Serial.println();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment