stationxml_rs/
conversion.rs1#[derive(Debug, Clone, PartialEq)]
21pub struct AdcConversion {
22 pub full_scale_voltage: f64,
24 pub max_count: f64,
26 pub pga_gain: f64,
28 pub adc_gain: f64,
30}
31
32impl AdcConversion {
33 pub fn new(full_scale_voltage: f64, bits: u32, pga_gain: f64, adc_gain: f64) -> Self {
37 Self {
38 full_scale_voltage,
39 max_count: (1_i64 << (bits - 1)) as f64 - 1.0,
40 pga_gain,
41 adc_gain,
42 }
43 }
44
45 pub fn count_to_voltage(&self, count: f64) -> f64 {
47 (count / self.max_count) * self.full_scale_voltage / (self.pga_gain * self.adc_gain)
48 }
49
50 pub fn voltage_to_count(&self, voltage: f64) -> f64 {
52 voltage * self.max_count * self.pga_gain * self.adc_gain / self.full_scale_voltage
53 }
54
55 pub fn count_to_physical(&self, count: f64, sensitivity: f64) -> f64 {
59 self.count_to_voltage(count) / sensitivity
60 }
61
62 pub fn overall_sensitivity(&self, sensor_sensitivity: f64) -> f64 {
66 self.max_count * self.pga_gain * self.adc_gain * sensor_sensitivity
67 / self.full_scale_voltage
68 }
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74
75 fn cs5532_24bit() -> AdcConversion {
76 AdcConversion::new(5.0, 24, 1.0, 1.0)
78 }
79
80 #[test]
81 fn max_count_24bit() {
82 let adc = cs5532_24bit();
83 assert_eq!(adc.max_count, 8388607.0);
84 }
85
86 #[test]
87 fn count_to_voltage_full_scale() {
88 let adc = cs5532_24bit();
89 let v = adc.count_to_voltage(adc.max_count);
90 assert!((v - 5.0).abs() < 1e-6);
91 }
92
93 #[test]
94 fn count_to_voltage_zero() {
95 let adc = cs5532_24bit();
96 assert_eq!(adc.count_to_voltage(0.0), 0.0);
97 }
98
99 #[test]
100 fn voltage_to_count_roundtrip() {
101 let adc = cs5532_24bit();
102 let voltage = 2.5;
103 let count = adc.voltage_to_count(voltage);
104 let v_back = adc.count_to_voltage(count);
105 assert!((v_back - voltage).abs() < 1e-6);
106 }
107
108 #[test]
109 fn overall_sensitivity_gs11d() {
110 let adc = cs5532_24bit();
111 let overall = adc.overall_sensitivity(32.0);
113 assert!((overall - 53687084.8).abs() < 0.1);
115 }
116
117 #[test]
118 fn count_to_physical() {
119 let adc = cs5532_24bit();
120 let sensitivity = 32.0; let physical = adc.count_to_physical(1000.0, sensitivity);
123 let expected_voltage = 1000.0 / 8388607.0 * 5.0;
124 let expected_physical = expected_voltage / 32.0;
125 assert!((physical - expected_physical).abs() < 1e-12);
126 }
127
128 #[test]
129 fn with_pga_gain() {
130 let adc = AdcConversion::new(5.0, 24, 2.0, 1.0);
131 let v_no_pga = cs5532_24bit().count_to_voltage(1000.0);
133 let v_with_pga = adc.count_to_voltage(1000.0);
134 assert!((v_with_pga - v_no_pga / 2.0).abs() < 1e-10);
135 }
136}