|
| 1 | +import processing.io.*; |
| 2 | + |
| 3 | +// using a capacitor that gets charged and discharged, while |
| 4 | +// measuring the time it takes, is an inexpensive way to |
| 5 | +// read the value of an (analog) resistive sensor, such as |
| 6 | +// a photocell |
| 7 | +// kudos to ladyada for the original tutorial |
| 8 | + |
| 9 | +// see setup.png in the sketch folder for wiring details |
| 10 | + |
| 11 | +int max = 0; |
| 12 | +int min = 9999; |
| 13 | + |
| 14 | +void setup() { |
| 15 | +} |
| 16 | + |
| 17 | +void draw() { |
| 18 | + int val = sensorRead(4); |
| 19 | + println(val); |
| 20 | + |
| 21 | + // track largest and smallest reading, to get a sense |
| 22 | + // how we compare |
| 23 | + if (max < val) { |
| 24 | + max = val; |
| 25 | + } |
| 26 | + if (val < min) { |
| 27 | + min = val; |
| 28 | + } |
| 29 | + |
| 30 | + // convert current reading into a number between 0.0 and 1.0 |
| 31 | + float frac = map(val, min, max, 0.0, 1.0); |
| 32 | + |
| 33 | + background(255 * frac); |
| 34 | +} |
| 35 | + |
| 36 | +int sensorRead(int pin) { |
| 37 | + // discharge the capacitor |
| 38 | + GPIO.pinMode(pin, GPIO.OUTPUT); |
| 39 | + GPIO.digitalWrite(pin, GPIO.LOW); |
| 40 | + delay(100); |
| 41 | + // now the capacitor should be empty |
| 42 | + |
| 43 | + // measure the time takes to fill it |
| 44 | + // up to ~ 1.4V again |
| 45 | + GPIO.pinMode(pin, GPIO.INPUT); |
| 46 | + int start = millis(); |
| 47 | + while (GPIO.digitalRead(pin) == GPIO.LOW) { |
| 48 | + // wait |
| 49 | + } |
| 50 | + |
| 51 | + // return the time elapsed |
| 52 | + // this will vary based on the value of the |
| 53 | + // resistive sensor (lower resistance will |
| 54 | + // make the capacitor charge faster) |
| 55 | + return millis() - start; |
| 56 | +} |
0 commit comments