#include SoftwareSerial mySerial(0, 1); // Pin for the LED int LEDPin = 3; // Pin to connect to the drawing/sensor int capSensePin = 7; // Value the sensor needs to read in order to trigger a // touch. Takes ten samples over a five-second period // from the touch sensor; chooses the maximum sample // and sets it to the cutoff value. During this five- // second setup the sensor should not be touched. int values = 0; int capPin; int get_cutoff() { for (int i=0; i<10; i++){ capPin = readCapacitivePin(capSensePin); if (capPin > values) { values = capPin; delay(500); } } return values; } int touchedCutoff; void setup(){ mySerial.begin(9600); // Set up the LED pinMode(LEDPin, OUTPUT); digitalWrite(LEDPin, LOW); // Get and print the cutoff value. touchedCutoff = get_cutoff(); mySerial.print("Cutoff value: "); mySerial.println(touchedCutoff); } void loop(){ // If the capacitive sensor reads above the cutoff, // turn on the LED if (readCapacitivePin(capSensePin) > touchedCutoff) { digitalWrite(LEDPin, HIGH); } else { digitalWrite(LEDPin, LOW); } // Uncomment below to print the value of the sensor every // 500 ms. It took up too much space in memory for the attiny44. //if ( (millis() % 500) == 0){ //mySerial.print("Capacitive Sensor on pin 7 reads: "); //mySerial.println(readCapacitivePin(capSensePin)); //} } // readCapacitivePin // Input: pin number // Output: A number from 0 to 17 expressing // how much capacitance is on the pin // When you touch the pin, or whatever you have // attached to it, the number will increase. // In order for this to work, there needs to be a // >= 1 Megaohm pull-up resistor to VCC (5V). uint8_t readCapacitivePin(int pinToMeasure){ // Declare a variable which will hold the PORT, // PIN, and DDR registers. volatile uint8_t* port; volatile uint8_t* ddr; volatile uint8_t* pin; // Translate the input pin number to the actual register // location. Bitmask chooses which bit we want to look at. // Attiny44 only has one 8-bit port, Port A (Port B is 4 // bits wide), so we need to use Port A and its corresponding // DDR and PIN values. byte bitmask; port = &PORTA; ddr = &DDRA; bitmask = 1 << pinToMeasure; pin = &PINA; // Discharge the pin by setting it as an output (and writing it low) *port &= ~(bitmask); *ddr |= bitmask; delay(1); // Make the pin an input WITHOUT the internal pull-up on *ddr &= ~(bitmask); // Now see how long the pin takes to get pulled up int cycles = 16000; for(int i = 0; i < cycles; i++){ if (*pin & bitmask){ cycles = i; break; } } // Discharge the pin again by setting it low and as output. // It's important to leave the pins low if you want to // be able to touch more than 1 sensor at a time - if // the sensor is left pulled high, when you touch // two sensors, your body will transfer the charge between // sensors. *port &= ~(bitmask); *ddr |= bitmask; return cycles; }