Last active
November 13, 2021 11:57
-
-
Save rgl/32e349976da9a545bf8571a9e4122ed1 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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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
very nice gist. I have some questions I am very interested in:
1/ What is the water meter model you are monitoring ?
2/ How precise is the above script performing ? Did the counter perfectly corresponds to the amount of water used sofar ?
3/ Did you consider the alternative where you used an interrupt service that becomes triggered every time the reed switch pin changed status ?