7 #include <pigpiod_if2.h>
10 #define CYCLE_OUT 18 // The cycle output
11 #define CMP_IN 17 // The signal from the comparator
12 #define NR_SAMPLES 20 // Number of samples to avaerage out the jitter
14 void gpio_callback(int pi, unsigned user_gpio, unsigned level, uint32_t tick, void * userdata);
16 #define INPUT_OFFSET 0.97
17 #define INPUT_DIVIDER 0.086
18 #define SLOPE_FACTOR 38.7 // Current / Voltage ( 117uA / 3.0V)
22 int pi; // Connection to pigpio daemon
23 unsigned cycle_gate; // The gate to run a measurement cycle
24 unsigned comparator; // The signal from the comparator
28 uint32_t measure_start;
30 uint32_t samples[NR_SAMPLES];
33 float U; // The measured voltage
38 void input_event(unsigned gpio, unsigned level, uint32_t tick)
42 //printf("Input event: input %u = %u, %d\n", gpio, level, tick - last_tick);
44 if (gpio == cycle_gate && level == 1)
49 if (gpio == comparator && level == 1)
51 samples[sample_index++] = tick - measure_start;
52 sample_index %= NR_SAMPLES;
54 measure_time = (float)(tick - measure_start) / 1.0e6;
55 U = measure_time * 11.4 - INPUT_OFFSET;
58 gpio_write(pi, cycle_gate, 0);
60 if (gpio == comparator && level == 0)
62 gpio_write(pi, cycle_gate, 1);
68 DVM(int pi_connection, unsigned gate, unsigned cmp)
80 set_mode(pi, comparator, PI_INPUT);
81 set_mode(pi, cycle_gate, PI_OUTPUT);
82 set_pull_up_down(pi, comparator, PI_PUD_OFF);
84 open_return = callback_ex(pi, cycle_gate, EITHER_EDGE, gpio_callback, this);
85 //fprintf(stderr, "Set callback returns %d.\n", open_return);
86 open_return = callback_ex(pi, comparator, EITHER_EDGE, gpio_callback, this);
87 //fprintf(stderr, "Set callback returns %d.\n", open_return);
88 gpio_write(pi, cycle_gate, 0);
90 gpio_write(pi, cycle_gate, 1);
96 uint32_t average_time;
99 // To filter out the jitter, calculate the average measured time
101 for (int i = 0; i < NR_SAMPLES; i++)
106 average_time = (sum / NR_SAMPLES) >> 5 << 5;
107 std::cout << " Average time = " << average_time << "\n";
108 measure_time = average_time / 1.0e6;
109 U = measure_time * SLOPE_FACTOR;
115 void gpio_callback(int pi, unsigned user_gpio, unsigned level, uint32_t tick, void * userdata)
119 sensor = (DVM *)userdata;
120 sensor->input_event(user_gpio, level, tick);
127 std::ofstream sensorfile;
129 pi = pigpio_start(NULL, NULL);
132 // pigpio initialisation failed.
133 fprintf(stderr, "GPIO initialization failed.\n");
138 // pigpio initialised okay.
139 DVM sensor(pi, CYCLE_OUT, CMP_IN);
144 printf("%.3f\n", sensor.Voltage());
147 sensorfile.open("sensor1");
148 sensorfile << std::fixed << std::setprecision(3) << sensor.Voltage() << " uF\n";