Two button interface problem

I am trying to make a very simple two-button interface with an analog input (all the other digital pins are occupied). For that I made a very simple stair of resistors, so when I press the button 1 I receive a signal from 1000 to 1019 and when I press the other I receive the full 1023. The problem comes when I try to “save” the last button state and change when I press the other button. It gets stuck in the “sip” state and doesn’t change more. Here’s the code:
int ao_input;
int val;
int old_val;
int val1;
int old_val1;
int state;
int state1;
void setup() {
// put your setup code here, to run once:
pinMode(A0, INPUT);


void loop() {
// put your main code here, to run repeatedly:
ao_input = analogRead(A0);
if(ao_input >1000 and ao_input<1019){
val = 1;
else if(ao_input == 1023){
val1 = 1;
if ((val == 1) and (old_val == 0)){
state = 1-state;
old_val = val;
if ((val1 == 1) and (old_val1 == 0)){
state1 = 1-state1;
old_val1 = val1;
if(state == 1){
state1 = 0;

if(state1 == 1){
state = 0;


I will apreciate a lot your help!!

Holy confusing logic, Batman!

You never change val after you set it to 1. To me, this means old_val will also be 1 as soon as val changes but not before the if statement on line 24. So "if ((val == 1) and (old_val == 0))" will be true the very first time, setting state to 1 and it will never be true again so state is stuck with that value.

It is possible that the error is there. How could I modify it??
I am a bit of a newbie and I don't have lots of experience

Welcome to the forum.

Please read the first post in any forum entitled how to use this forum.,148850.0.html then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.

Thanks... Tom... :slight_smile:
PS You d know you can declare analog pins as digital...

Wow, I didn't know that code scrolling was a thing! Thank you for let it me know it! BTW i knew that you can turn an analog pin into a digital one but I want the program to run in a ATtiny and I only have one analog pin available