8 | input devices

 

Task

measure something: add a sensor to a microcontroller board and read it

Motion Sensor And Fan

Hall-Effect Sensor

#include <SoftwareSerial.h>

#define NOFIELD 505L // Analog output with no applied field, calibrate this

// Uncomment one of the lines below according to device in use A1301 or A1302
// This is used to convert the analog voltage reading to milliGauss
#define TOMILLIGAUSS 1953L // For A1301: 2.5mV = 1Gauss, and 1024 analog steps = 5V, so 1 step = 1953mG
// #define TOMILLIGAUSS 3756L // For A1302: 1.3mV = 1Gauss, and 1024 analog steps = 5V, so 1 step = 3756mG

const int rxPin = 13;
const int txPin = 12;
// pins for the LEDs:
const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;

void setup()
{

}

void DoMeasurement()
{
// set up a new serial port
SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin);
mySerial.begin(9600);
// measure magnetic field
int raw = analogRead(7); // Range : 0..1024

// Uncomment this to get a raw reading for calibration of no-field point
// Serial.print("Raw reading: ");
// Serial.println(raw);

long compensated = raw - NOFIELD; // adjust relative to no applied field
long gauss = compensated * TOMILLIGAUSS / 1000; // adjust scale to Gauss

mySerial.print(gauss);
mySerial.print(" Gauss ");

if (gauss > 0) {
mySerial.println("(South pole)");
digitalWrite(redPin, 255);
digitalWrite(greenPin, 0);
digitalWrite(bluePin, 0);
}

else if(gauss < 0) {
mySerial.println("(North pole)");
digitalWrite(redPin, 0);
digitalWrite(greenPin, 255);
digitalWrite(bluePin, 0);
}

else {mySerial.println();
digitalWrite(redPin, 0);
digitalWrite(greenPin, 0);
digitalWrite(bluePin, 255);
}
}

void loop()
{
delay(1000);
DoMeasurement();
}