The following is the sketch uploaded directly to the Arduino.
It has been set up to send back to the Serial Monitor an On/Off message to identify if there is a magnet in the vicinity of the sensor.
I have also added an LED which turns on and off as a magnet is detected.
//Following code modified from original code by Author: Bruce Allen - 23/07/09
// Set up the constant variable to read in the ping. I have set this one to Digital Pin 8 on the Arduino.
const int pwPin = 8;
// Store these values to convert the pulse in to distance.
long pulse, inches, cm;
// variable for the final distance
int distSensor = 0;
// *********************************
void setup() {
// Intitiate Serial connection for debugging and seeing the results live
Serial.begin(9600);
}
// *********************************
void loop() {
int i = 0;
distSensor = 0;
// Average of 8 conesecutive readings (within 1/2 a second) to accomodate noise and error
for (i=0; i<8; i++) {
// Used to read in the pulse that is being sent by the MaxSonar device.
pulse = pulseIn(pwPin, HIGH);
// Pulse Width representation with a scale factor of 147 uS per Inch.
inches = pulse/147;
//change inches to centimetres
cm = inches * 2.54;
//add all 8 readings together
distSensor += cm;
// Wait for 1/20th of a second - 50 miliseconds
delay(50);
}
// get average of the 8 readings
distSensor /= 8;
// send the results back to the console on the pc to review.
Serial.print(distSensor);
Serial.print("cm");
Serial.println();
// Wait for 1/2 a second - 500 miliseconds
delay(500);
}
// *********************************