The easy way to connect an analog sensor to a Parallax BASIC Stamp

One of the biggest limitations of the BASIC Stamp (other than its price and the fact that you can’t program it in C) is its lack of analog inputs. The RCTIME command provides a clever way of reading resistive sensors, but what can you do if you want to read a sensor that directly generates an analog voltage (such as the Sharp GP2D and GP2Y series of IR range detectors)?

First of all, if you just need binary (“target - no target”) information, you can connect an analog sensor directly to any BASIC Stamp input pin. If the analog output is greater than 1.3V the pin will read high, if less than 1.3V the pin will read low. For the GP2Y0A21YK sensor this means that an object in the range of approximately 10-20cm will generate a high reading.

For reading an analog sensor or multiple analog sensors, the use of an A/D converter may be the way to go. Instructions on interfacing a BASIC Stamp (BS2) to a PCF8591 I2C A/D D/A converter can be found here:
However, due to the coded needed to “bit bang” a solution to I2C connectivity on the BS2, this is not exactly a trivial solution.

Here’s a much easier way to do it:
The trick to interfacing a Voltage-output analog sensor with the BS2, without using an A/D converter, is to make the sensor look like a resistive sensor. The circuit shown below converts the sensor’s output from a voltage to a current. The voltage from the sensor, applied to the base of the transistor, will cause the C-E path to behave much like a variable resistor. The sensor can then be read using the standard RCTIME procedure (i.e. charge capacitor, measure time to discharge). The Sharp distance sensors provide voltages in the range of roughly 0.2V to 2.6V. A diode has been added to the negative lead of the sensor in the schematic. This will limit the sensor’s output voltage to a minimum of 0.6V so the circuit can operate properly over the sensor’s full range of detection. (At input voltages below about 0.6V the transistor will shut off completely.)
I used a BC33725 transistor because it's cheap and I have a bag full of them. But the circuit should work with almost any small signal NPN transistor (2N2222, 2N3904, etc...)

NOTE: The readings may vary significantly from transistor to transistor, dependent upon the transistor's hfe. Experiment with different capacitor values to select a range you're happy with. Also, because the gain of a transistor is temperature sensitive, the response of this circuit will vary to some degree with the ambient temperature.

The BASIC code to read the sensor is the same as that used to read a resistive sensor:

time VAR Word

RCTIME 3,1,time

Here is another variation that will be less sensitive to component and temperature changes:

Acroname sharp infrared ranger distance sensor infra red GP2D12 GP2D15 GP2D120 GP2Y0A02YK GP2Y0D02YK GP2Y0A21YK

Chris Vecchio, Physical Computing, Temple University, installation art, interactive art