pot_cap_charge.c
Go to the documentation of this file.
1 #include <stdio.h>
2 
3 #include <pigpio.h>
4 
5 /*
6  Measure how long a capacitor takes to charge through a resistance.
7 
8  A potentimeter is used to vary the resistance.
9 
10  The time taken will be proportional to the resistance.
11 
12  3V3 ----- Potentiometer --+-- Capacitor ----- Ground
13  |
14  +-- gpio
15 
16 
17  gcc -o pot_cap_charge pot_cap_charge.c -lpigpio -lpthread -lrt
18  sudo ./pot_cap_charge
19 
20 */
21 
22 #define GPIO 25
23 
24 #define MAX_READING 1000
25 
26 static uint32_t rechargeTick = 0;
27 
28 void callback(int gpio, int level, uint32_t tick)
29 {
30  static uint32_t smooth = 0;
31  static int reading = 0;
32 
33  uint32_t raw;
34 
35  if (level == 1) /* measure recharge time */
36  {
37  ++reading;
38 
39  if (rechargeTick)
40  {
41  raw = tick - rechargeTick; /* set in main */
42 
43  if (raw < MAX_READING) /* ignore outliers */
44  {
45  /* smooth using 0.8 * smooth + 0.2 * raw */
46 
47  smooth = (raw + (4 * smooth)) / 5;
48 
49  printf("%d %d %d\n", reading, raw, smooth);
50  }
51  else
52  {
53  /* ignore outlier, set dot at fixed position */
54  printf("%d %d %d\n", reading, 40, smooth);
55  }
56  }
57  else
58  {
59  /* ignore reschedule, set dot at fixed position */
60  printf("%d %d %d\n", reading, 20, smooth);
61  }
62  }
63 }
64 
65 int main (int argc, char *argv[])
66 {
67  uint32_t t1, t2;
68  int tDiff;
69 
70  if (gpioInitialise()<0) return 1;
71 
72  gpioSetAlertFunc(GPIO, callback); /* callback when GPIO changes state */
73 
74  while (1)
75  {
76  gpioWrite(GPIO, PI_OFF); /* drain capacitor */
77 
78  gpioDelay(200); /* microseconds */
79 
80  t1 = gpioTick();
81 
82  gpioSetMode(GPIO, PI_INPUT); /* start capacitor recharge */
83 
84  t2 = gpioTick();
85 
86  /* dump reading if rechargeTick not accurate to 3 micros */
87 
88  if ((t2 - t1) < 3) rechargeTick = t1; else rechargeTick = 0;
89 
90  gpioDelay(5000); /* microseconds, nominal 200 readings per second */
91  }
92 
93  gpioTerminate();
94 }
int gpioInitialise(void)
Definition: pigpio.c:8459
int gpioSetAlertFunc(unsigned gpio, gpioAlertFunc_t f)
Definition: pigpio.c:11303
static uint32_t rechargeTick
#define PI_OFF
Definition: pigpio.h:566
int gpioSetMode(unsigned gpio, unsigned mode)
Definition: pigpio.c:8607
uint32_t gpioDelay(uint32_t micros)
Definition: pigpio.c:13196
#define PI_INPUT
Definition: pigpio.h:581
#define MAX_READING
void callback(int gpio, int level, uint32_t tick)
void gpioTerminate(void)
Definition: pigpio.c:8495
uint32_t gpioTick(void)
Definition: pigpio.c:13217
int gpioWrite(unsigned gpio, unsigned level)
Definition: pigpio.c:8707
Definition: gpio.h:23
int main(int argc, char *argv[])


cob_hand_bridge
Author(s): Mathias Lüdtke
autogenerated on Tue Oct 20 2020 03:35:57