1 minute read
Software
CHAPTER 8: Hacking with Sensors 203
Figure 8-11 Sensing vibration with an Arduino
The LED is joined to a resistor as described back in Chapter 6. This can then be plugged into sockets 8 and GND on the Arduino, with the positive connection of the LED connected to 8.
Software
The software that follows uses the technique of calibrating itself as it starts, to get the “no vibration” reading from the sensor. It then waits until the sensor reading exceeds the threshold set, at which point it lights the LED. Pressing the Arduino “reset” button will cause the sensor to detect movement again.
// vibration_sensor
int gndPin = A0; int sensePin = 1; int ledPin = 8;
After defining the pins to use, we then define two variables. The variable “normalReading” is used during calibration (more on that in a minute), and the variable “threshold” should be set to the amount that the analog reading is allowed to exceed “normalReading” by before the LED is turned on.
int normalReading = 0; int threshold = 10;
The “setup” function sets the appropriate pin modes and then calls the “calibrate” function to find the reading for the sensor when there is no vibration.
void setup() { pinMode(gndPin, OUTPUT); digitalWrite(gndPin, LOW); pinMode(ledPin, OUTPUT); normalReading = calibrate(); }