Pin Wiring and Programming

This is a piece of code from an example project using the keyboard library,

#include <Keyboard.h>                               //Including the keyboard library
#include <Mouse.h>                                  //Including the mouse library

int pinA = 2;                                       //Declaring variables for the pins
int pinB = 3;
int pinC = 4;
int pinD = 5;
int pinE = 6;

void setup() {

pinMode(pinA, INPUT_PULLUP);                        //Setting up the internal pull-ups resistors
pinMode(pinB, INPUT_PULLUP);                        //and also setting the pins to inputs.
pinMode(pinC, INPUT_PULLUP);
pinMode(pinD, INPUT_PULLUP);
pinMode(pinE, INPUT_PULLUP);

}

void loop() {

  if (digitalRead(pinA) == LOW)                     //Checking if the first switch has been pressed
  {
    Keyboard.write('A');                            //Sending the "A" character
    delay(500);
  }

  if (digitalRead(pinB) == LOW)                     //Checking if the second switch has been pressed
  {
    Keyboard.print("You pressed switch B");         //Sending a string
    delay(500);
  }

  if (digitalRead(pinC) == LOW)                     //Checking if the third switch has been pressed
  {
    Keyboard.println("You have pressed switch C."); //Sending a string and a return
    delay(500);
  }

  if (digitalRead(pinD) == LOW)                     //Checking if the fourth switch has been pressed
  {
    Mouse.press(MOUSE_RIGHT);                       //Pressing down the right click
    delay(100);
    Mouse.release(MOUSE_RIGHT);                     //Releasing the right click
    delay(500);
  }

  if (digitalRead(pinE) == LOW)                     //Checking if the fifth switch has been pressed
  {
    Keyboard.println("Subscribe to Simple Electronics!");
    delay(500);                                     //Sending a string and a return
  }
}

Which part of the code assigns each button to a pin, how does the arduino know which pin is which button?

If you haven't yet, read about the keywords pinMode, etc. (highlighted in blue) at

note: This doesn't include things like Mouse. xxx

Read the code. You can actually read code. Sometimes the comments are helpful clues, too.

int pinA = 2;

//

pinMode(pinA, INPUT_PULLUP);

//

  if (digitalRead(pinA) == LOW) ... 

//

  Keyboard.write('A'); 

Looks like something on pin 2 makes it go LOW which the code detects and sends out an 'A'.

Now you do 'B'.

a7

These lines are when the program assigns each button ("pinA") a pin ("2"). The "=" is called the Assignment Operator and will "assign 2 to the word pinA" When you use the word "pinA" the program knows to use value "2"... You will physically connect a button to pin 2. The function of you pressing that button on Pin 2 assigned to "pinA" is what Post #2 showed.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.