The buttons are connected together via identical resistors to form a resistive ladder (see previous post). It was a simple matter of pressing a button, reading the resulting decoded value at the analog port of the ATMEGA328, and then inserting the correct value in the table for that button (Note: some of the current coding details have been left out, see source if necessary).
// ###############################################################################
int btnDown(){
int val;
val = analogRead(FN_PIN);
if (val>1000) return 0;
// 47K Pull-up, and 4.7K switch resistors,
// Val should be approximately = 1024*btnN*4700/(47000+(btnN*4700))
// N = 0 to Number_of_button - 1
if (val > 350) return 7;
if (val > 300) return 6;
if (val > 250) return 5;
if (val > 200) return 4;
if (val > 150) return 3;
if (val > 50) return 2;
return 1;
}
That became a little boring, so I decided to replace the table with an algorithm.
// ###############################################################################
int btnDown(){
int val = 0;
val = analogRead(FN_PIN);
if (val>1000) return 0;
// 47K Pull-up, and 4.7K switch resistors,
// Val should be approximately = 1024*btnN*4700/(47000+(btnN*4700))
// N = 0 to Number_of_button - 1
// 1024L*b*4700L/(47000L+(b*4700L)) >>> 1024*b/(10+b);
for(int b = MAX_BUTTONS - 1; b >= 0; b--) {
if(val + 15 > 1024*b/(10+b)) return b+1;
}
return 1;
}
The NEW algorithm is smaller, faster and more flexible than the "table", only MAX_BUTTONS need to be change to add/remove new buttons. There is probably a limit to the number of buttons that can reasonably be added to the Resistive/Switch chain, currently I have used eight.
Note: According to ohm's law, with 47K ohm Bias Resistor and 4.7K ohm Switch Resistors, (see previous post) the value read by the ATMEGA should be:
As long as the Bias and Switch Resistors have a fixed ratio (in this case 10:1), they can be factored-out to leave a much smaller function:
The biggest disadvantage of using an algorithm is; it can NOT easily be tweaked to solve a resistive tolerance problems - the moral of the story, use good resistors and pay attention to the Bias source for the network and the ATMEGA contained ADC's.
-- Home Page: https://WA0UWH.blogspot.com
No comments:
Post a Comment