-
Notifications
You must be signed in to change notification settings - Fork 0
/
Joystick.cpp
32 lines (27 loc) · 983 Bytes
/
Joystick.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include "Joystick.hpp"
#ifdef ARDUINO
#include <Arduino.h>
#endif
static const int lower_bound = 256; // 512 - 256
static const int higher_bound = 768; // 512 + 256
Joystick::Joystick(int xPin, int yPin, int switchPin)
: xPin(xPin), yPin(yPin), switchPin(switchPin) {}
Direction Joystick::readDirection() const {
int x, y;
// Deliberate double reading to stabilize analog readings
analogRead(xPin), x = analogRead(xPin);
analogRead(yPin), y = analogRead(yPin);
if (y < lower_bound && x >= lower_bound && x <= higher_bound)
return Direction::Up;
if (y > higher_bound && x >= lower_bound && x <= higher_bound)
return Direction::Down;
if (x < lower_bound && y >= lower_bound && y <= higher_bound)
return Direction::Left;
if (x > higher_bound && y >= lower_bound && y <= higher_bound)
return Direction::Right;
return Direction::None;
}
bool Joystick::isPressed() const {
int status = digitalRead(switchPin);
return status == LOW;
}