22
22
23
23
/* Optional delay between shift register reads.
24
24
*/
25
- #define POLL_DELAY_MSEC 1
25
+ #define POLL_DELAY_MSEC 10
26
26
27
27
const size_t numButtonGroups = 3 ;
28
28
@@ -59,6 +59,48 @@ void setup()
59
59
hc165_collection_setup (hc165_collection);
60
60
hc165_collection_read (hc165_collection);
61
61
hc165_collection_print (hc165_collection);
62
+
63
+ analogReference (DEFAULT);
64
+ pinMode (A0, INPUT);
65
+ pinMode (A1, INPUT);
66
+ pinMode (A8, INPUT);
67
+ pinMode (A9, INPUT);
68
+ }
69
+
70
+ /*
71
+ * Attempting to read the voltage across only a potentiometer will always
72
+ * return 1023. The voltage difference is 5V because there is nothing else in
73
+ * the circuit. To measure the resistance, we use a reference resistor in
74
+ * series with the potentiometer:
75
+ *
76
+ * 5V --v^v^v-- V1 --v^v^v-- GROUND
77
+ * Rpot Rref
78
+ *
79
+ * To solve for Rpot, use Ohm's law and the fact that 2 resistors in series
80
+ * must have the same current:
81
+ *
82
+ * (Vsupply - V1) / Rpot = (V1 - 0V) / Rref
83
+ * (Vsupply - V1) * Rref = V1 * Rpot
84
+ * (Vsupply / V1 - 1) * Rref = Rpot
85
+ * Vsupply * Rref / V1 - Rref = Rpot
86
+ *
87
+ * The ADC maps 5V (assumed to be both the ADC reference voltage and the supply
88
+ * voltage) to a value 0 - 1023 (kAdcOutputMax). Since only the ratio of
89
+ * Vsupply and V1 is important, we can treat both as ADC outputs instead of
90
+ * converting from ADC to voltage on both sides.
91
+ *
92
+ * See http://www.built-to-spec.com/blog/2009/09/10/using-a-pc-joystick-with-the-arduino/
93
+ */
94
+ const long kDivResistanceKOhm = 100 ;
95
+ const long kAdcOutputMax = 1023 ;
96
+
97
+ uint8_t get_potentiometer_resistance (int adc_in)
98
+ {
99
+ if (adc_in > 0 ) {
100
+ return uint8_t ((kAdcOutputMax * kDivResistanceKOhm ) / adc_in - kDivResistanceKOhm );
101
+ } else {
102
+ return 0 ;
103
+ }
62
104
}
63
105
64
106
void loop ()
@@ -68,5 +110,25 @@ void loop()
68
110
hc165_collection_print (hc165_collection);
69
111
}
70
112
113
+ bool isButtonPressed = false ;
114
+ for (int i = 0 ; i < hc165_collection.size ; i++) {
115
+ if (hc165_data[i].values != 0xff ) {
116
+ isButtonPressed = true ;
117
+ break ;
118
+ }
119
+ }
120
+
121
+ if (!isButtonPressed) {
122
+ Serial.print (" Axes: x:" );
123
+ Serial.print (get_potentiometer_resistance (analogRead (A0)));
124
+ Serial.print (" y:" );
125
+ Serial.print (get_potentiometer_resistance (analogRead (A1)));
126
+ Serial.print (" r:" );
127
+ Serial.print (get_potentiometer_resistance (analogRead (A8)));
128
+ Serial.print (" t:" );
129
+ Serial.print (get_potentiometer_resistance (analogRead (A9)));
130
+ Serial.print (" \r\n " );
131
+ }
132
+
71
133
delay (POLL_DELAY_MSEC);
72
- }
134
+ }
0 commit comments