-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflow_sensor.ino
90 lines (74 loc) · 2.28 KB
/
flow_sensor.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*------------------------------------------------------------------------------
24/02/2020
Author: Esterlin Polanco
Platforms: Arduino Nano
Language: C#/Arduino
File: fisica_2.ino
------------------------------------------------------------------------------
Description:
Code for Water flow metter system, built for physics 2 class at Dominico Americano
University, Santo Domingo D.R. Connects to ESP8266 via i2c.
------------------------------------------------------------------------------
License:
Please see attached LICENSE.txt file for details.
------------------------------------------------------------------------------*/
#include <Wire.h>
//Flow Sensor variables:
int sendvalue;
const int sensorPin = 2;
const int measureInterval = 1000;
volatile int pulseConter;
const float factorK = 7.5;
float frequency;
float flow_Lmin;
//i2c Address:
const byte SlaveDeviceId = 1;
/*------------------------------------------------------------------------------
Flow sensor methods:
------------------------------------------------------------------------------*/
void ISRCountPulse()
{
pulseConter++;
}
float GetFrequency()
{
pulseConter = 0;
interrupts();
delay(measureInterval);
noInterrupts();
return (float)pulseConter * 1000 / measureInterval;
}
int measure()
{
frequency = GetFrequency();
flow_Lmin = frequency / factorK;
//Multiply to make the value suitable for integer to be sent:
sendvalue = flow_Lmin * 100;
return sendvalue;
}
/*------------------------------------------------------------------------------
I2C methods:
------------------------------------------------------------------------------*/
void requestCallback()
{
int input = sendvalue;
// Send two bytes to master.
uint8_t buffer[2];
buffer[0] = input >> 8;
buffer[1] = input & 0xff;
Wire.write(buffer, 2);
}
void setup()
{
// Start I2C bus as a slave
Wire.begin(SlaveDeviceId);
// Set the callback to call when data is requested.
Wire.onRequest(requestCallback);
//interrupts initialization:
attachInterrupt(digitalPinToInterrupt(sensorPin), ISRCountPulse, RISING);
}
void loop()
{
//Calculate the water flow and stores the value to send over i2c:
sendvalue = measure();
}