Analog Read and a Piezo

In this one we are going to use the piezo electric effect. Basically a piezo element has a crystal in it and if you squeeze it it will produce electricity. We will use analogRead to measure this electricity. For this circuit hook up the piezo as shown and put an LED in Pin 13 as we've done previously.This circuit will wait until we "knock" the piezo. Really it will look for any loud sound (yes, you could make a clapper with this). Sound is a vibration in the air that results in pressure differences. Air pressure difference caused by a loud sound will squeeze the crystal and produce a measurable voltage.The program below has the Arduino pay attention to the piezo and look for a "knock" when a knock is detected it will turn on the LED if it was off, or turn it off it was on. New Commands: statePin = !statePin

statePin is just a variable name. It was set to LOW in the beginning of the program. The "!" means opposite or NOT. So the command above means set the variable to the opposite of what it currently is.

/* Knock Sensor

* ----------------


* Program using a Piezo element as if it was a knock sensor.


* We have to basically listen to an analog pin and detect

* if the signal goes over a certain threshold. If the Threshold

* is crossed, and toggles the LED on pin 13.


* Modified from one by (cleft) 2005 D. Cuartielles for K3


int ledPin = 13;

int knockSensor = 2;

byte val = 0;

int statePin = LOW;

int THRESHOLD = 100; // if it's too sensitive then change this value

void setup()


pinMode(ledPin, OUTPUT);


void loop()


val = analogRead(knockSensor);

if (val >= THRESHOLD) { // check the piezo

statePin = !statePin; // sets the pin to the opposite state

digitalWrite(ledPin, statePin); // turn on or off the LED