1
int pin1 = 8, pin2 = 9, pin3 = 10, pin4 = 11;
volatile byte  num = 0;
int coinPin = 2;


void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(coinPin), inc_counter, RISING );
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
  pinMode(pin3, OUTPUT);
  pinMode(pin4, OUTPUT);
}

void display(int num) {
  digitalWrite(pin1, bitRead(num, 1));
  digitalWrite(pin2, bitRead(num, 2));
  digitalWrite(pin3, bitRead(num, 3));
  digitalWrite(pin4, bitRead(num, 4));
}

void loop() {
  Serial.print(num);
  Serial.print("credit(s) towards balance");
  display(num);
  delay(500);
}

void inc_counter() {
  num++;
}
1
  • what is your question? ... not all people would ask the same question
    – jsotola
    Commented Jul 24, 2021 at 17:53

1 Answer 1

1

Based on the code supplied, you are only updating the display every half second because of the delay(500). You could press the button a number of times in 500mills.

I feel it may be better to update a flag and check that in your loop to increment your value and trigger the display update.

Based on the info provided, this may help in your endeavours.

int pin1 = 8, pin2 = 9, pin3 = 10, pin4 = 11;
int coinPin = 2;
int num = 0;
volatile bool coinFlag = false; // When true there is a coin.

void coin_present()
{
    coinFlag = true;
}

void setup()
{
    Serial.begin(9600);
    attachInterrupt(digitalPinToInterrupt(coinPin), coin_present, RISING);
    pinMode(pin1, OUTPUT);
    pinMode(pin2, OUTPUT);
    pinMode(pin3, OUTPUT);
    pinMode(pin4, OUTPUT);
}

void display(int num)
{
    digitalWrite(pin1, bitRead(num, 1));
    digitalWrite(pin2, bitRead(num, 2));
    digitalWrite(pin3, bitRead(num, 3));
    digitalWrite(pin4, bitRead(num, 4));
}

void loop()
{
    // If the flag is set increment num and then display value.
    if (coinFlag)
    {
        //We have a coin, reset the flag first.
        coinFlag = false;

        num++;        // Increment value
        display(num); //
        Serial.print(num);
        Serial.println("credit(s) towards balance");
    }

    // No need for a delay as only `coinFlag` being `true` will update the display.
}

Hope this helps in someway.

2
  • Nice answer. Code that I can copy+paste into the IDE that compiles makes this answer better than most we receive.
    – VE7JRO
    Commented Jul 27, 2021 at 0:21
  • @VE7JRO Thanks, your comment made me aware of the issue and now prompts me to double check! Commented Jul 29, 2021 at 9:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.