Created
January 28, 2013 21:12
-
-
Save kylekyle/4659053 to your computer and use it in GitHub Desktop.
This sketch determines which buttons are being pressed by checking how long a pin takes to pull high. See comments for details.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This sketch is a trivial extension of: | |
// http://www.instructables.com/id/Turn-a-pencil-drawing-into-a-capacitive-sensor-for/ | |
// This sketch returns which digital pins | |
// specified in the pins array take 50 or more | |
// cycles to pull high. Pins that take more than | |
// 50 cycles have a + and pins that take less | |
// have a - | |
int pins[] = { | |
2,3,5,6,8,9,11,12 | |
}; | |
void setup(){ | |
Serial.begin(9600); | |
} | |
void loop(){ | |
for(int i=0; i<sizeof(pins)/sizeof(int);i++) { | |
Serial.print(checkForTouch(pins[i]) ? "+" : "-"); | |
Serial.print(pins[i]); | |
Serial.print(" "); | |
} | |
Serial.println(); | |
} | |
boolean checkForTouch(int pin){ | |
volatile uint8_t* r_port; | |
volatile uint8_t* r_ddr; | |
volatile uint8_t* r_pin; | |
byte bitmask; | |
if ((pin >= 0) && (pin <= 7)){ | |
r_port = &PORTD; | |
r_ddr = &DDRD; | |
bitmask = 1 << pin; | |
r_pin = &PIND; | |
} | |
if ((pin > 7) && (pin <= 13)){ | |
r_port = &PORTB; | |
r_ddr = &DDRB; | |
bitmask = 1 << (pin - 8); | |
r_pin = &PINB; | |
} | |
if ((pin > 13) && (pin <= 19)){ | |
r_port = &PORTC; | |
r_ddr = &DDRC; | |
bitmask = 1 << (pin - 13); | |
r_pin = &PINC; | |
} | |
*r_port &= ~(bitmask); | |
*r_ddr |= bitmask; | |
delay(1); | |
*r_ddr &= ~(bitmask); | |
int cycles = 16000; | |
for(int i = 0; i < cycles; i++){ | |
if (*r_pin & bitmask){ | |
cycles = i; | |
break; | |
} | |
} | |
*r_port &= ~(bitmask); | |
*r_ddr |= bitmask; | |
return cycles > 50; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment