Project 4.07 Piezo as an Input 2
In Project 4.06 we found that it was difficult to record a quick tap on the piezo using the Arno’s analog-digital converter (ADC). The voltage created by striking the piezo tended to linger on the pin. In this project, we add a function to quickly pull the piezo pin back to near zero volts after it’s tapped. Most of this sketch is identical to Project 4.06, except for the additional function clearPiezo which is explained below.
Upload this sketch to the Arno, wait a moment, and then open the serial monitor. Strike the piezo. You should see that the signal lasts one millisecond or less.
Concepts: analogRead, boolean variable type, functions, switching pinMode
Circuits:
Upload this sketch to the Arno, wait a moment, and then open the serial monitor. Strike the piezo. You should see that the signal lasts one millisecond or less.
Concepts: analogRead, boolean variable type, functions, switching pinMode
Circuits:
The main difference between this sketch and the previous one is the clearPiezo function. The function changes the piezo pin very briefly to an output, sets its value to LOW to pull the voltage to near zero, and then resets the pin to an input:
void clearPiezo(){
pinMode(piezo,OUTPUT);
digitalWrite(piezo,LOW);
delay(1);
pinMode(piezo,INPUT);
}
The function is called in the setup() block to clear an lingering voltage:
clearPiezo();
Because we have better control of the piezo pins voltage, we can use a lower threshold in the loop() block to detect a strike:
while(knock > 40){
We record millis() with the variable now before calling the clearPiezo function. The clearPiezo function adds a millisecond or so, which would affect how precisely we record the timing of the strike:
digitalWrite(LED1,HIGH);
if(firstKnock==true) now = millis();
firstKnock = false;
Serial.print(millis()-now);
Serial.print(" ");
Serial.println(knock);
clearPiezo();
With a simple change to the code, we get a piezo signal that is much cleaner and easier to interpret. Now let’s use that signal in the next two projects!
void clearPiezo(){
pinMode(piezo,OUTPUT);
digitalWrite(piezo,LOW);
delay(1);
pinMode(piezo,INPUT);
}
The function is called in the setup() block to clear an lingering voltage:
clearPiezo();
Because we have better control of the piezo pins voltage, we can use a lower threshold in the loop() block to detect a strike:
while(knock > 40){
We record millis() with the variable now before calling the clearPiezo function. The clearPiezo function adds a millisecond or so, which would affect how precisely we record the timing of the strike:
digitalWrite(LED1,HIGH);
if(firstKnock==true) now = millis();
firstKnock = false;
Serial.print(millis()-now);
Serial.print(" ");
Serial.println(knock);
clearPiezo();
With a simple change to the code, we get a piezo signal that is much cleaner and easier to interpret. Now let’s use that signal in the next two projects!