Imagine you have a varying number of push buttons that you need to connect to a microcontroller such as Arduino, of which you can only use a maximum of two pins (not counting 5v and gnd). Each button must be wired to the next one, and the total number of wires between them must not exceed 4, with 2 being 5v and gnd. The objective is to know how many push buttons are connected and determine when a push button is pressed, and which one. The push buttons don't have a fixed order; you must be able to change their positions if necessary.
I managed to make it work to a certain degree by using 2k resistors along with the buttons and measuring the resistance in the end. When I press a button, I read the resistance up to that point, adding an extra 1k resistor before the Arduino pin. So if I get an even value, I divide it by two and I get the total number of push buttons. If I get an odd value, it's because some button is being pressed, so I divide it by two and round it down, getting the position of the button being pressed.
The problem is that I can't have both the information of the total number of buttons and the button being pressed at the same time. While I'm pressing the button, I can remove a button to the right and I have no way of knowing. Also, if I press two or more buttons simultaneously, only the leftmost button being pressed will be detected.
Is there a way of doing this in a somewhat inexpensive way, being able to know at any given time how many buttons there are, how many are being pressed and which ones, using only a maximum of two pins?