Hi PeterT
Can you please comment your code a little bit? I am also interested in using the UTI in my project and I would like to understand your code better...
Why there is a stateMask = (state ? bit : 0)? It is always = bit...
I dont really understand that statemask part myself i saw that in another function and just used it in my code.
int ReadUTI(uint8_t pin, double * res1,double * res2,double * res3,int refRes)
{
int state = HIGH;
int i,startindex=-1;
uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);
uint8_t stateMask = (state ? bit : 0); //State HIGH
unsigned long width[12] = {0,0,0,0,0,0,0,0,0,0,0,0};
double nOff=0,nAB=0,nCD=0,nBC=0,nDF=0;
while ( (*portInputRegister(port) & bit) != stateMask) //While state is LOW
;
for(i=0;i<12;i++) { //Count 12 cycles so you are sure you get the whole.
while ( (*portInputRegister(port) & bit) == stateMask) //Count the HIGH time
width[i]++;
while ( (*portInputRegister(port) & bit) != stateMask) //Count the LOW time and add them together
width[i]++;
}
for(i=1;i<12;i++) { //Find the Index for Toff cycle
if(i<7) {
if(width[i]<width[i+2]&&width[i]<width[i+3]&&width[i]<width[i+4]&&width[i]<width[i+5]&&width[i+1]<width[i+2]&&width[i+1]<width[i+3]&&width[i+1]<width[i+4]&&width[i+1]<width[i+5]) {
startindex=i;
i=12;
}
}
}
if(startindex!=-1) {
//Save the cycles (Makes it easier to know what you are calculating
nOff=width[startindex]+width[startindex+1];
nAB=width[startindex+2];
nCD=width[startindex+3];
nBC=width[startindex+4];
nDF=width[startindex+5];
//Do the calculations according to the UTI manual.
*res1=((nBC-nOff)/(nAB-nOff))*refRes;
*res2=((nCD-nOff)/(nAB-nOff))*refRes;
*res3=((nDF-nOff)/(nAB-nOff))*refRes;
return 1; //Return 1 if the cycles where found
}
else {
return 0;
}
}