Sample Experiment 3: Read Joystick Pushbutton Switches
The pushbutton switches are simply connected to Arduino digital I/O pins as shown in the table below:
When Key A is pressed a digital signal will be sent to D2 and so on. We will use the digitalRead() function to determine the state of the buttons.
Since there are no resistors connected to these buttons on joystick shield you have to enable pull up resistors on your Arduino. Below is the code to enable the pullup resistors and read the digital values.
Whenever a user presses a pushbutton, the Arduino will display the button value on the serial monitor.
Steps
- Attach your joystick shield over Arduino board.
- Connect your Arduino board to your PC.
- Led will light on your joystick shield showing that it’s working properly.
- Write the sketch and compile it before uploading to your board (it’s good practice to compile your sketch before uploading).
- After the sketch is uploaded, run serial monitor to observe the values.
- Press any button on your joystick and it will display which button is pressed.
Code
#define BUTTON_UP 2
#define BUTTON_RIGHT 3
#define BUTTON_DOWN 4
#define BUTTON_LEFT 5
#define BUTTON_E 6
#define BUTTON_F 7
#define DELAY 500
void setup() {
Serial.begin(9600);
// to enable pull up resistors first write pin mode
// and then make that pin HIGH
pinMode(BUTTON_UP, INPUT);
digitalWrite(BUTTON_UP, HIGH);
pinMode(BUTTON_RIGHT, INPUT);
digitalWrite(BUTTON_RIGHT, HIGH);
pinMode(BUTTON_DOWN, INPUT);
digitalWrite(BUTTON_DOWN, HIGH);
pinMode(BUTTON_LEFT, INPUT);
digitalWrite(BUTTON_LEFT, HIGH);
pinMode(BUTTON_E, INPUT);
digitalWrite(BUTTON_E, HIGH);
pinMode(BUTTON_F, INPUT);
digitalWrite(BUTTON_F, HIGH);
}
void loop() {
if(digitalRead(BUTTON_UP) == LOW) {
Serial.println(“Button A is pressed”);
delay(DELAY);
}
else if(digitalRead(BUTTON_RIGHT) == LOW) {
Serial.println(“Button B is pressed”);
delay(DELAY);
}
else if(digitalRead(BUTTON_DOWN) == LOW) {
Serial.println(“Button C is pressed”);
delay(DELAY);
}
else if(digitalRead(BUTTON_LEFT) == LOW) {
Serial.println(“Button D is pressed”);
delay(DELAY);
}
else if(digitalRead(BUTTON_E) == LOW) {
Serial.println(“Button E is pressed”);
delay(DELAY);
}
else if(digitalRead(BUTTON_F) == LOW) {
Serial.println(“Button F is pressed”);
delay(DELAY);
}
}
What is the price of Joystick Shield for Arduino & Raspberry Pi PS2 type in Bangladesh?
Please check out our price at the top of the page.
Reviews
There are no reviews yet.