-1

I have 3 digital button inputs, I want to do a continuous scan of 3 of them until a button is pressed and to know which button has been pressed. Please help, I'm new to programming and arduino. Thanks

0

Try out this code. You can see result on Serial Monitor. I hope it will help you.

const int kPinBtn1 = 2;  // Button 1
const int kPinBtn2 = 3;  // Button 2
const int kPinBtn3 = 4;  // Button 3

void setup()
{
  pinMode(kPinBtn1, INPUT); // Button 1 as Input
  pinMode(kPinBtn2, INPUT); // Button 2 as Input
  pinMode(kPinBtn3, INPUT); // Button 3 as Input

  digitalWrite(kPinBtn1, HIGH); // Pullup
  digitalWrite(kPinBtn2, HIGH); // Pullup
  digitalWrite(kPinBtn3, HIGH); // Pullup

  Serial.begin(9600);
}

void loop()
{
  if(digitalRead(kPinBtn1) == LOW)      // If button 1 pressed
  {
    Serial.println("Button 1 pressed"); // Print "Button 1 pressed" on Serial Monitor
  }

  if(digitalRead(kPinBtn2) == LOW)      // If button 2 pressed
  {
    Serial.println("Button 2 pressed"); // Print "Button 2 pressed" on Serial Monitor
  }

  if(digitalRead(kPinBtn3) == LOW)      // If button 3 pressed
  {
    Serial.println("Button 3 pressed"); // Print "Button 3 pressed" on Serial Monitor
  }
}
  • Usually you would take advantage of a pin change interrupt and only then read the state of all buttons. This solution will pollute the Serial Monitor while a button is being kept pressed. But it fulfils the requirements of C. Dave. I'm not sure if he exactly knows which direction he is heading. – Kwasmich Mar 8 '17 at 12:18
  • @C.Dave - I guess since you are new to programming Kwasmich kept it simple. Once you have that working you could research arrays (in C or C++) and you'll find that you can half the amount of code. – Code Gorilla Mar 9 '17 at 12:49
  • @C.Dave Glad to know. – Hasan Mar 10 '17 at 4:15

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