Skip to content

Instantly share code, notes, and snippets.

@sabretus
Forked from rgl/reed_switch.c
Created May 11, 2019 10:31
Show Gist options
  • Save sabretus/814f12c7dd817ecd67499822ad2d3293 to your computer and use it in GitHub Desktop.
Save sabretus/814f12c7dd817ecd67499822ad2d3293 to your computer and use it in GitHub Desktop.
connect arduino to a reed switch to read the water flow from a water meter
// this is for an arduino uno.
// this was inspired by http://www.instructables.com/id/Arduino-Reed-Switch/?ALLSTEPS but
// changed to use the arduino internal pull up resistor:
//
// +-----------------+
// | arduino GND -----reed_switch----\
// | | |
// | 12 --------------------/
// +-----------------+
//
// tested with a window reed switch alike http://www.aliexpress.com/item/New-Arrival-High-Quality-10W-Recessed-Magnetic-Window-Door-Contacts-Alarm-Security-Reed-Switch-Home-Safely/32550780759.html
const int pinReedSwitch = 12;
const int pinLed = 13;
int lastValue;
unsigned long lastValueTime;
unsigned int counter = 0;
void setup() {
// initialize pins.
pinMode(pinReedSwitch, INPUT_PULLUP);
pinMode(pinLed, OUTPUT);
// initialize serial and wait for the port to open.
Serial.begin(19200);
while (!Serial) {
// wait for serial port to connect.
// needed for native USB port only.
}
Serial.println("hello");
lastValue = !digitalRead(pinReedSwitch);
lastValueTime = millis();
}
void loop() {
int value = !digitalRead(pinReedSwitch);
if (value != lastValue) {
lastValue = value;
digitalWrite(pinLed, value == HIGH ? HIGH : LOW);
if (value) {
++counter;
unsigned long valueTime = millis();
unsigned long timeDifference = valueTime >= lastValueTime
? valueTime - lastValueTime
: lastValueTime - valueTime;
lastValueTime = valueTime;
Serial.print(counter);
Serial.print(" dt=");
Serial.print(timeDifference);
Serial.print('\n');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment