// Sketch adapted from Dave Melis's Touch sensor code for // ATtiny, to run on Adafruit Gemma //Things changed: //-Pin numbers: Although the Gemma is an ATtiny board, // not all of the ATtiny's pins are 'broken out' aka able to be connected to //- Two separate touch sensors: Pin 1 and Pin 2 are both touch //sensors that can be set to trigger different things //The Gemma has 3 pin (0,1,2). As two are used for touch sensing //this leaves just one for lighting leds int togglepin = 3; // the led that's toggled when you touch the input pin //Gemma doesn't have a pin 3, so this part of the code isn't being used int steadypin = 1; // the led that's on while you're touching the input pin //Pin 1 an i/o pin, but it's also connected to the onboard led on the Gemma //Which is handy because it means you don't have to connect an external led to see this work int calibration = 0; //calibrating the first touch sensor int calibration2 = 0; //calibrating the second touch sensor int previous; //this variable is used for toggling the led on and off int togglestate = LOW; void setup() { //pinMode(togglepin, OUTPUT); //commented out as it's not being used pinMode(steadypin, OUTPUT); delay(100); //Calibrate the first touch sensor - pin 2 aka PB2 for (int i = 0; i < 8; i++) { calibration += chargeTime(PB2); delay(20); } calibration = (calibration + 4) / 8; //Calibrate the second touch sensor - pin 0 ak PB0 for (int i = 0; i < 8; i++) { calibration2 += chargeTime(PB0); delay(20); } calibration2 = (calibration2 + 4) / 8; } void loop() { int n = chargeTime(PB2); int n2= chargeTime(PB0); //If pin 2 is being touched, turn on the LED at full brightness if (n > calibration ) digitalWrite(steadypin, HIGH); //If pin 0 is being touched, turn on the LED at low brightness else if (n2 > calibration2 ) analogWrite(steadypin,20); //If nothing is being touched, turn off the led else digitalWrite(steadypin, LOW); ////This part is for toggling the led, which we're not using at the moment // if (previous <= calibration && n > calibration) { // if (togglestate == LOW) togglestate = HIGH; // else togglestate = LOW; // digitalWrite(togglepin, togglestate); // } // // previous = n; delayMicroseconds(500); } //This function detects if a pin is being touched byte chargeTime(byte pin) { byte mask = (1 << pin); byte i; DDRB &= ~mask; // input PORTB |= mask; // pull-up on for (i = 0; i < 16; i++) { if (PINB & mask) break; } PORTB &= ~mask; // pull-up off DDRB |= mask; // discharge return i; }