1 minute read

How to Sense Magnetic Fields

Next Article
Index

Index

210 Hacking Electronics

In the main loop, we read the X and Y accelerations and see how much they have strayed from the values of “levelX” and “levelY”. The “abs” function returns the absolute value of a number, so if the difference is negative, it is turned into a positive value, and it is this that is compared with the thresholds that have been set.

void loop() { int × = analogRead(xPin); int y = analogRead(yPin); boolean shakey = (abs(x - levelX) > ledThreshold || abs(y - levelY) > ledThreshold); digitalWrite(ledPin, shakey); boolean lost = (x > levelX + buzzerThreshold || y > levelY + buzzerThreshold); if (lost) { tone(buzzerPin, 400); } }

The only complication in the “calibrate” function is that we must wait for 200 milliseconds before we can take the readings. This gives the accelerometer time to turn on properly.

void calibrate() { delay(200); // give accelerometer time to turn on levelX = analogRead(xPin); levelY = analogRead(yPin); }

How to Sense Magnetic Fields

Sensing a magnetic field is made easy using a three-pin sensor IC like the A1302 linear hall effect sensor. You can use this chip in very much the same way as we did the TMP36 temperature sensor in the section “How to Measure Temperature” earlier in this chapter.

This article is from: