The master's code I plan to use:
const int CLOCK_PIN = 2;
const int DATA_PIN = 3;
const int BIT_COUNT = 16;
void setup() {
pinMode(DATA_PIN, INPUT);
pinMode(CLOCK_PIN, OUTPUT);
digitalWrite(CLOCK_PIN, HIGH);
Serial.begin(115200);
}
void loop() {
float reading = readPosition();
Serial.println(reading,2);
delay(25);
}
//read the current angular position
float readPosition() {
unsigned long graysample = shiftIn(DATA_PIN, CLOCK_PIN, BIT_COUNT);
delayMicroseconds(100); // Clock must be high for 20 microseconds before a new sample can be taken
unsigned long binarysample = grayToBinary32(graysample);
return ((binarysample * 360UL) / 65536.0); // ouptut value from 0 to 360 with two point percision
}
//read in a byte of data from the digital input of the board.
unsigned long shiftIn(const int data_pin, const int clock_pin, const int bit_count) {
unsigned long data = 0;
for (int i=0; i<bit_count; i++) {
data <<= 1; // shift all read data left one bit.
//digitalWrite(clock_pin,LOW);
PORTD &= ~(1 << 5); // clock pin goes low
delayMicroseconds(1);
//digitalWrite(clock_pin,HIGH);
PORTD |= (1 << 5); // lock pin goes high
delayMicroseconds(1);
data |= digitalRead(data_pin); // cat the new read bit to the whole read data.
}
return data;
}
unsigned int grayToBinary32(unsigned int num)
{
num = num ^ (num >> 16);
num = num ^ (num >> 8);
num = num ^ (num >> 4);
num = num ^ (num >> 2);
num = num ^ (num >> 1);
return num;
}
