I am working with Arduino UNO and the "funshield" attachment, and I am trying to make a binary counter that adds with one button and subtracts with another (I managed this), the thing is, I cannot get it to work when I am holding down the buttons.
Here is my rough, but working, code:
#include "funshield.h"
//setting up
constexpr int ledPins[] { led1_pin, led2_pin, led3_pin, led4_pin };
constexpr int ledPinsCount = sizeof(ledPins) / sizeof(ledPins[0]);
constexpr int activationDelay = 1000;
constexpr int periodicDelay = 300;
unsigned lastTime = 0;
int counter = 0;
bool wasDown = false;
bool wasDown2 = false;
//Binary counter
void BN(int number, const int leds[], int ledsCount)
{
for (int i = ledsCount-1; i >= 0; --i){
bool currentBit = number & 1;
digitalWrite(leds[i], currentBit ? ON : OFF);
number = number >> 1;
}
}
void setup(){
for (int i = 0; i < ledPinsCount; ++i){
pinMode(ledPins[i], OUTPUT);
digitalWrite(ledPins[i], OFF);
}
pinMode(button1_pin, INPUT);
pinMode(button2_pin, INPUT);
lastTime = millis();
}
void loop()
{ //Checks if button is down
bool isDown = digitalRead(button1_pin) == ON;
//NOT WORKING
//if (wasDown == isDown) {
//unsigned long time = millis();
//if (time >= lastTime + activationDelay){
//counter = (counter + 1) % 16;
//BN(counter);
//lastTime += activationDelay;
//}
//wasDown = isDown;
//}
//JUST ADDS AUTOMATICALLY
//if wasn't down but now is, do BN +
if (wasDown != isDown){
if (isDown){
counter = (counter + 1) % 16;
BN(counter, ledPins, ledPinsCount);
}
wasDown = isDown;
}
//if wasn't down but now is, do BN -
bool isDown2 = digitalRead(button2_pin) == ON;
if (wasDown2 != isDown2){
if (isDown2){
counter = (counter - 1) % 16;
BN(counter, ledPins, ledPinsCount);
}
wasDown2 = isDown2;
}
}
I have what I think should check if "button was held == button is held" and then run the desired code, but it just starts running the code automatically.
I have no idea why it starts adding as soon as my Arduino turns on, because when it just turned on, isDown and wasDown should NOT be equal, but they are somehow?
EDIT:
I have also tried checking the state of "button1_pin" with things like
if (isDown = ON)
if(isDown = OFF)
but if I did either:
if (isDown = ON && wasDown = ON)
if (isDown = OFF && wasDown = OFF)
it just did the same, and started adding/substracting on startup.
Which is understandable with is OFF and was OFF, but not the other one.