This example will explain how to use a piezo as a knock sensor. Knock on it directly, or tape it to a surface and knock on the surface.
Materials
- 1 Arduino Uno board
- 1 Education shield
- 1 piezo speaker
- 1 1M ohm resistor
- 2 black jumper wires
- 2 coloredvjumper wires
Instructions
- Attach the shield onto the top of the Arduino board.
- Connect a 1M ohm resistor across the breadboard gap.
- Connect one leg of the resistor to A0 and the other to GND using jumper wires.
- Connect the piezo across the breadboard gap.
- Connect one leg of the piezo to A0 and the other to GND in parallel with the resistor using jumper wires.
- Connect the board to the computer and upload example PiezoKnockSensor.
Code
Find the code in Example>EducationShield>Help>PiezoKnockSensor
Commands
PiezoKnockSensor(analogPin)
– creates a PiezoKnockSensor object.- Parameters
-
(
int
)analogPin
– the analog pin to which the piezo is connected.
-
- Parameters
config(threshold, debounceTime)
– configures the PiezoKnockSensor.- Parameters
- (
int
)threshold
– defines how hard you need to knock, and therefore the sensitivity of the sensor. Usetest()
to check the values returned when knocked. -
(
int
)debounceTime
– prevents the sensor from returning several hits from one knock, but also limits how rapid you can knock, in milliseconds.
- (
- Parameters
knocked(timeout)
– checks if the sensor is knocked.- Parameters
-
(
int
)timeout
– milliseconds within which the sensor should be knocked. Returns 1 if knocked within time, otherwise 0. If not used, the program pauses until knocked.
-
- Parameters
-
test()
– prints the sensor value to serial monitor.
Troubleshooting
- Make sure everything is connected correctly.
- Make sure you have connected the piezo to the same pin as you have stated in your code.
- If you are using piezo for both Melody and knock sensor, make sure you distinguish between the two.
Note: If you tape the piezo to a surface, it is better to knock on the surface close to the piezo. Removing the plastic casing of the piezo also helps increasing the sensitivity.