// original code 4-16-2010 revised for Arduino IDE 2-23-2012
// tested on Atmega 168,328, 8MHz internal RC clock
//
// Wire Digital Pin 2 (IC pin 4) through 10K resistor to one leg of 1 Meg pot
// (10K protects against shorts). Wire wiper of pot to Digital Pin 4 (IC pin 6)
// and to 6" x 6" sensor plate made of copper or aluminum foil - pie tin works great.
//
// Note: we are making an RC timer with the metal plate (sensor) as one plate of a capacitor
//       which is charged through the combined resistance of 10K + 1 Meg pot. 
//       We simply time how long it takes to charge the plate to 5V. This will vary depending 
//       on whether a person is touching it. A person is roughly a 100pF capacitor. Since touching
//       the plate adds capcitance, it will take longer to charge than if no one is touching it.
//
// Wire LED through 330 ohm series resistor to Digital Pin 7 (IC pin 13).
//

#include <ms_arduino.h>	// points to software libraries to use
#include "lcd.h"

// variables for pins
int capchargePin = 2;
int capreadPin = 4;
int ledPin = 7;

int sampleValue;  // variable to count a few samples
int i;     	  // index for counter

void setup() {
  pinMode(capchargePin, OUTPUT);    // initialize pin for charge signal out
  pinMode(capreadPin, INPUT);       // initialize pin for reading charge on plate
  digitalWrite(capreadPin, LOW);    // turn off pull-up resistor, we want it to float)
  pinMode(ledPin, OUTPUT);          // initialize pin as an output (for LED)

  Serial.begin(9600);               // initialize serial port at 9600 bps:
  lcd_init();                       // initialize LCD screen
}

void loop() {

  lcd_clear();
  sampleValue = 0;	// zero data

  for(i=0; i<8; i++) {	                // take eight samples
    digitalWrite(capchargePin, LOW);	// start LOW
    delay(1);		                // let it settle
    digitalWrite(capchargePin, HIGH);	// now make it go HIGH
    delayMicroseconds(5);		// 5 us delay - test for capacitance of subject

    if( digitalRead(capreadPin) ) {  // if pin is high, it means no one is touching
    }
    else {  // someone is touching - takes too long to charge plate
      sampleValue++;
    }
  }

  if (sampleValue >= 4) {        // more than 4 of the 8 samples took too long
    lcd_instruction(GOTO_LINE1);
    lcd_text("someone");         // put text on the LCD screen
    digitalWrite(ledPin, HIGH);  // light LED
    Serial.write(1);             // send the number '1' out serial port
  }
  else {
    lcd_instruction(GOTO_LINE1);
    lcd_text("no one");         // put text on the LCD screen
    digitalWrite(ledPin, LOW);  // LED off
    Serial.write(2);		// send the number '2' out serial port
  }

  delay(10);

}  // end MAIN