What is the best way to approach this in my code: If the highest average value o
ID: 3768999 • Letter: W
Question
What is the best way to approach this in my code:
If the highest average value of the two inputs was 0V, then the led is completely off. If the highest average value of the two inputs was 3V, then the LED should be at maximum brightness. If one average is at 1V and the other average is at 1.5V, then the LED would be at "half" brightness.
Should it be a switch statement or just if statements?
It's in C++ language.
This is what I have so far, but I'm stuck:
int ledPin = 3; // LED connected to digital pin 13
unsigned int val1 = 0; // variable to store the value coming from the left sensor
unsigned int val2 = 0; // variable to store the value coming from the right sensor
unsigned int sensorDiff = 0; // variable to store the value coming from the differential POT
float readings[30]; //readings from analog input after each loop
float totalReadings[10]; //readings from analog input loop
float average[30];
void setup()
{
pinMode(ledPin, OUTPUT); // sets the digital pin as output
pinMode(A0, INPUT);
pinMode(A1, INPUT);
}
void loop()
{
val1 = analogRead(A0); // read the value from the left sensor
delay(1000);
val2 = analogRead(A1); // read the value from the right sensor
delay(1000);
sensorDiff = analogRead(A2); // read the value from the differential POT
delay(1000);
for(val1 = 0; val1 < 30; val1++)
{
}
for ( val2 = 0; val2 < 30; val2++)
{
}
totalReadings[val2, val2] + readings[val1];
readings[i] = analogRead(A0);
average[30] = totalReadings[val1, val2] / val2;
Serial.println(average[30]);
}
Explanation / Answer
Solution:
The power of switch is twofold:
If the number of switch labels is N, a chain of ifs takes O(N) to dispatch, while a switch always dispatches in O(1). This is how it is done: compiler places addresses of switch labels into an array, computes an index based on the label values, and performs a jump directly, without comparing the switch expression to value one by one. In case of strings used as switch labels, the compiler produces a hash table, which looks up an address in O(1) as well.
When the number of switch becomes high (above 100), converting between switch and a chain of ifs could no longer be regarded as a micro-optimization: time savings may be very significant, especially in tight loops. If a profiler tells you that your chain of ifs is taking a significant time, rewriting as a switch may very well be a solution.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.