43Views2Replies

Author Options:

Arduino Pish Button code Issue Answered

Hey all, I am having a problem with my code and was hoping someone could help shed some light on how to fix it. Below is a code for an arduino push button counter. The concept is that there are 2 buttons, an "add" button and "subtract" button. Every time add is pressed it adds 1 to the count and vice versa when subtract is hit. The code works fine until we hit double digits. Once you subtract from 1 from 10 the LCD displays 90 not 9. Not sure how to fix this, any ideas?

LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

int add=8;

int sub=9;

int valadd;

int valsub;

int count=000;
int press;

void setup() {
lcd.begin(16,2);

pinMode(add,INPUT);

pinMode(sub,INPUT);

}

void loop() {

valadd=digitalRead(add);

valsub=digitalRead(sub);

if(valadd==HIGH) {

delay(100);

press=count++;

delay(250);

}

if(valsub==HIGH) {

delay(100);

press=count--;

delay(250);

}

lcd.setCursor(0,0);

lcd.print(press);

}

Tags:Counter

Discussions

1
None
Palingenesis

2 months ago

It's where you place the cursor before you print the number on the display.
Printing 9, prints over the 1, but nothing removes the 0.
Either clear screen before a print, or print a space after the number.

0
None
Downunder35m

3 months ago

I have not run your code but think the problem might be within your loop.
Both if functions for the button pressed could go in the same section.
Only other thing is the actual adding and subtractions.
Although you defined a delay it is quite possible that your Arduino gets confused.
Count is set as an integer with the value 000 - it would make sense to make this just 0.
A statement like press=count++; is logical from a users point of view.
However firstly defining press like count to 0 and then actually adding real values would be better.
Similar to press=press+1; or press=press-1;
Inlcuding a check for zero and negative numbers should be added as well.

My suspicion is that your press count stuff at some stage cause invalid results.
A computer always needs to have clear and defined states, for the rest we need to tell the thing what is going on ;)