Part 2.
int i;
int sign;
long value;
float resultx;
float resulty;
int clockpinx = A2;
int datapinx = A0;
int clockpiny = 7;
int datapiny = 9;
unsigned long tempmicrosx;
unsigned long tempmicrosy;
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
void setup()
{
{pinMode(clockpinx, INPUT);
pinMode(datapinx, INPUT);
}
{
pinMode(clockpiny, INPUT);
pinMode(datapiny, INPUT);
}
Serial.begin(9600);
lcd.begin(16,2);
lcd.backlight();
{ lcd.setCursor(0,0);
lcd.print("X val mm"
;
lcd.setCursor(0,1);
lcd.print("Y val mm"
;
}
}
void loop() {
ReadX();
}
void ReadX(){
//This is for reading the caliper x data.
while (digitalRead(clockpinx)==HIGH) {} //if clock is LOW wait until it turns to HIGH
tempmicrosx=micros();
while (digitalRead(clockpinx)==LOW) {} //wait for the end of the HIGH pulse
if ((micros()-tempmicrosx)>1000) { //if the HIGH pulse was longer than 1000 micros we are at the start of a new bit sequence
decodex(); //decode the bit sequence
}
}
void decodex()
{
//this turns the binary code of x data into a decimal value.
sign=1;
value=0;
for (i=0;i<23;i++) {
while (digitalRead(clockpinx)==HIGH) { } //wait until clock returns to HIGH- the first bit is not needed
while (digitalRead(clockpinx)==LOW) {} //wait until clock returns to LOW
if (digitalRead(datapinx)==LOW)
{
if (i<20)
{
value|= 1<<i;
}
if (i==20)
{
sign=-1;
}
}
}
resultx = ((value*sign)/100.0);
lcd. setCursor(10,0);
lcd.print(resultx,4);
ReadY();
} ///END
void ReadY(){
//This is for reading the caliper Y data.
while (digitalRead(clockpiny)==HIGH) {} //if clock is LOW wait until it turns to HIGH
tempmicrosy=micros();
while (digitalRead(clockpiny)==LOW) {} //wait for the end of the HIGH pulse
if ((micros()-tempmicrosy)>1000) { //if the HIGH pulse was longer than 1000 micros we are at the start of a new bit sequence
decodey(); //decode the bit sequence
}
}
void decodey()
{
sign=1;
value=0;
for (i=0;i<23;i++) {
while (digitalRead(clockpiny)==HIGH) { } //wait until clock returns to HIGH- the first bit is not needed
while (digitalRead(clockpiny)==LOW) {} //wait until clock returns to LOW
if (digitalRead(datapiny)==LOW)
{
if (i<20)
{
value|= 1<<i;
}
if (i==20)
{
sign=-1;
}
}
}
resulty = ((value*sign)/100.0);
lcd. setCursor(10,1);
lcd.print(resulty,4);
ReadX();
}