blob: a2efc647464d9c4cc22bac2c72efd060b34cec70 (
plain)
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
|
/*
LabUI ESP32 Firmware v1.0
─────────────────────────────────────────────────────────────────────────
Author: Adam Shatila
Co-Author: Christian Kolset
Upload this sketch to your ESP32 with a TE SP1 spring potensiometer.
Required library: esp32 by Espressif Systems
─────────────────────────────────────────────────────────────────────────
*/
const int sensorPin = A0;
const unsigned long sampleInterval = 2000;
unsigned long lastSampleTime = 0;
const double lowPassFilter_alpha = 0.00675;
const unsigned long calibration_factor = 1.07517;
const long calibration_offset = -267.25;
float filtered_displacement = 0.0;
void setup() {
Serial.begin(115200);
while (!Serial) {
delay(10);
}
analogReadResolution(12);
}
void loop() {
unsigned long currentTime = micros();
if (currentTime - lastSampleTime >= sampleInterval) {
lastSampleTime = currentTime;
uint32_t millivolts = analogReadMilliVolts(sensorPin);
float displacement = convert_mV_to_mm(millivolts);
filtered_displacement = lowPassFilter(displacement, filtered_displacement, lowPassFilter_alpha);
float volts = filtered_displacement;
// Output the voltage to the serial monitor with 3 decimal places
//Serial.print(displacement, 3);
//Serial.print(", ");
Serial.println(filtered_displacement, 3);
//Serial.println(millivolts);
}
}
float convert_mV_to_mm(float mVolts){
// Reads mV from sensor and output in mm from lower limit
float voltage = mVolts / 1000.0;
float raw_val = voltage * (635.0 / 2.863);
//float inverted_val = 650.0 - raw_val;
//float volts = inverted_val * (635.0 / 637.0);
float volts = raw_val * (635.0 / 637.0);
return calibration_factor * volts + calibration_offset;
}
float lowPassFilter(float newSample, float prevOutput, float alpha) {
// Simple exponential low-pass filter (EMA) formula
return alpha * newSample + (1.0 - alpha) * prevOutput;
}
|