|
/****************************************************************************** |
|
edited for 2x2 button pad (without RGB leds) |
|
|
|
red-plus-buttons.ino |
|
Byron Jacquot @ SparkFun Electronics |
|
1/6/2015 |
|
|
|
Exercise 2 in a series of 3. |
|
https://learn.sparkfun.com/tutorials/button-pad-hookup-guide/exercise-2-monochrome-plus-buttons |
|
|
|
******************************************************************************/ |
|
//config variables |
|
#define NUM_BTN_COLUMNS (4) |
|
#define NUM_BTN_ROWS (1) |
|
|
|
#define MAX_DEBOUNCE (3) |
|
|
|
static const uint8_t btncolumnpins[NUM_BTN_COLUMNS] = {8, 9, 10, 11}; |
|
static const uint8_t btnrowpins[NUM_BTN_ROWS] = {13}; |
|
|
|
static int8_t debounce_count[NUM_BTN_COLUMNS][NUM_BTN_ROWS]; |
|
|
|
void setup() |
|
{ |
|
// put your setup code here, to run once: |
|
Serial.begin(115200); |
|
Serial.print("Starting Setup..."); |
|
|
|
// setup hardware |
|
setuppins(); |
|
|
|
Serial.println("Setup Complete."); |
|
|
|
} |
|
|
|
void loop() { |
|
// put your main code here, to run repeatedly: |
|
scan(); |
|
} |
|
|
|
static void setuppins() |
|
{ |
|
uint8_t i; |
|
|
|
// initialize |
|
// button columns |
|
for (i = 0; i < NUM_BTN_COLUMNS; i++) |
|
{ |
|
pinMode(btncolumnpins[i], OUTPUT); |
|
|
|
// with nothing selected by default |
|
digitalWrite(btncolumnpins[i], HIGH); |
|
} |
|
|
|
// button row input lines |
|
for (i = 0; i < NUM_BTN_ROWS; i++) |
|
{ |
|
pinMode(btnrowpins[i], INPUT_PULLUP); |
|
} |
|
|
|
// Initialize the debounce counter array |
|
for (uint8_t i = 0; i < NUM_BTN_COLUMNS; i++) |
|
{ |
|
for (uint8_t j = 0; j < NUM_BTN_ROWS; j++) |
|
{ |
|
debounce_count[i][j] = 0; |
|
} |
|
} |
|
} |
|
|
|
static void scan() |
|
{ |
|
static uint8_t current = 0; |
|
uint8_t val; |
|
uint8_t i, j; |
|
|
|
// Select current columns |
|
digitalWrite(btncolumnpins[current], LOW); |
|
|
|
// Read the button inputs |
|
for ( j = 0; j < NUM_BTN_ROWS; j++) |
|
{ |
|
val = digitalRead(btnrowpins[j]); |
|
|
|
if (val == LOW) |
|
{ |
|
// active low: val is low when btn is pressed |
|
if ( debounce_count[current][j] < MAX_DEBOUNCE) |
|
{ |
|
debounce_count[current][j]++; |
|
if ( debounce_count[current][j] == MAX_DEBOUNCE ) |
|
{ |
|
Serial.print("Key Down "); |
|
Serial.println((current * NUM_BTN_ROWS) + j); |
|
|
|
// Do whatever you want to with the button press here: |
|
|
|
} |
|
} |
|
} |
|
else |
|
{ |
|
// otherwise, button is released |
|
if ( debounce_count[current][j] > 0) |
|
{ |
|
debounce_count[current][j]--; |
|
if ( debounce_count[current][j] == 0 ) |
|
{ |
|
Serial.print("Key Up "); |
|
Serial.println((current * NUM_BTN_ROWS) + j); |
|
|
|
// If you want to do something when a key is released, do it here: |
|
|
|
} |
|
} |
|
} |
|
}// for j = 0 to 3; |
|
|
|
delay(1); |
|
|
|
digitalWrite(btncolumnpins[current], HIGH); |
|
|
|
current++; |
|
|
|
if (current >= NUM_BTN_COLUMNS) |
|
{ |
|
current = 0; |
|
} |
|
|
|
} |
|
|