On my robot I have two shaft encoders on each side. I average them in my code.
Is there a way to set a variable to automatically average two sensors when I call it?
So instead of having to put:
I’m happy you got what you needed with the function
int LeftEnc()
above. But to be clear (because clear communication is important) the answer to this question:
is “No.”
And the word “call” has a specific meaning in programming. Variables aren’t called, they are refrerenced.
This:
int LeftEnc () {
int value = abs((SensorValue[LeftEnc1]+SensorValue[LeftEnc2])/2;
return(value);
}
isn’t a variable; it’s a function which returns an integer.
Variables are names for memory locations; they don’t (and can’t) do anything.
As I said, the reason to care about naming things correctly here is for clear communications. Some time in the future other people will read this thread, and if they’re just starting to program in C, it will be helpful for the terminology to be correct.
Continuing off of what @kypyro said. Some code needs to actually execute the averaging and a variable is only a number and can’t do the execution.If you wanted a variable to always contain the average of 2 sensors you would have to have a task constantly update the variable.
If you wanted to average multiple readings of the same sensor you need to have a task to save the readings and then average them. Here is some code I made to always get the median of the last 5 ultrasonic sensor readings. Average would be even easier.
short leftDistances[5];
short rightDistances[5];
task helper() {
int nextIndex = 0;
while (true) {
leftDistances[nextIndex] = SensorValue[leftUltra];
rightDistances[nextIndex] = SensorValue[rightUltra];
nextIndex++;
if (nextIndex == 5)
nextIndex = 0;
delay(7);
}
}
short getLeftUltra(){
short biggestIndex=-1;
short secondBiggestIndex=-1;
short currentBiggestIndex=0;
for(int i=0;i<5;i++){
if(leftDistances*>leftDistances[currentBiggestIndex])
currentBiggestIndex=i;
}
biggestIndex=currentBiggestIndex;
for(int i=0;i<5;i++){
if(leftDistances*>leftDistances[currentBiggestIndex]&&i!=biggestIndex)
currentBiggestIndex=i;
}
for(int i=0;i<5;i++){
if(leftDistances*>leftDistances[currentBiggestIndex]&&i!=biggestIndex&&i!=secondBiggestIndex)
currentBiggestIndex=i;
}
return leftDistances[currentBiggestIndex];
}
short getRightUltra(){
short biggestIndex=-1;
short secondBiggestIndex=-1;
short currentBiggestIndex=0;
for(int i=0;i<5;i++){
if(rightDistances*>rightDistances[currentBiggestIndex])
currentBiggestIndex=i;
}
biggestIndex=currentBiggestIndex;
for(int i=0;i<5;i++){
if(rightDistances*>rightDistances[currentBiggestIndex]&&i!=biggestIndex)
currentBiggestIndex=i;
}
for(int i=0;i<5;i++){
if(rightDistances*>rightDistances[currentBiggestIndex]&&i!=biggestIndex&&i!=secondBiggestIndex)
currentBiggestIndex=i;
}
return rightDistances[currentBiggestIndex];
}