Mozzi  version v2.0
sound synthesis library for Arduino
CapPoll.h
1 /*
2  * CapPoll.h
3  *
4  * This file is part of Mozzi.
5  *
6  * Copyright 2015-2024 Tim Barrass and the Mozzi Team
7  *
8  * Mozzi is licensed under the GNU Lesser General Public Licence (LGPL) Version 2.1 or later.
9  *
10  */
11 
12 #ifndef RCPOLL_H
13 #define RCPOLL_H
14 
15 
16 /**
17 A class for reading voltage on a digital pin, derived from http://arduino.cc/en/Tutorial/RCtime.
18 This is designed to be used in updateControl(). Each time it is called, it checks if a capacitor has charged,
19 and returns an output reflecting how long it took for the most recent charge.
20 */
21 
22 template <unsigned char SENSOR_PIN, unsigned char SEND_PIN>
23 class CapPoll
24 {
25 
26 public:
27  /** Constructor.
28  */
29  CapPoll():result(0),rc_cued(true), output(0)
30  {
31  ;
32  }
33 
34  /** Checks whether the capacitor has charged, and returns how long it took for the most recent charge.
35  This would preferably be called in updateControl(), but if the resolution isn't fine enough or the
36  pin charges too fast for updateControl() to catch, try it in updateAudio().
37  @return the sensor value, reflected in how many checking cycles it took to charge the capacitor.
38  */
39  inline
40  unsigned int next(){
41  if (rc_cued){
42  pinMode(SENSOR_PIN, INPUT); // turn pin into an input and time till pin goes low
43  digitalWrite(SENSOR_PIN, LOW); // turn pullups off - or it won't work
44  rc_cued = false;
45  }
46  if(digitalRead(SENSOR_PIN)){ // wait for pin to go low
47  result++;
48  }
49  else{
50  output = result;
51  result = 0;
52  pinMode(SENSOR_PIN, OUTPUT); // make pin OUTPUT
53  digitalWrite(SENSOR_PIN, HIGH); // make pin HIGH to discharge capacitor - see the schematic
54  rc_cued = true;
55  }
56  return output;
57  }
58 
59 private:
60  unsigned int result;
61  boolean rc_cued;
62  unsigned int output;
63 
64 };
65 
66 #endif // #ifndef RCPOLL_H