66: Analog Input using an Arduino
- revised 11/18/14 -
- revised 11/18/14 -
After my frustration with the MCP3008 (post 65) I decided to try using an Arduino. I bought a new Nano from Sainsmart ($14). Here's the Arduino setup:
Note that the Nano plugs directly into the breadboard
(very handy)
I use the Arduino.app on my iMac to write and debug the Arduino program (over the USB cable). Then I move the cable to a USB port on my Pi. (Note: the Arduino uses Flash memory, so the program starts again.)
Here's the Arduino "sketch" (as programs are called) in C language:
// Rheostat has 3 pins L=GND, R=5v (or 3.3V), Mid to A1
// Readings connected to 3.3V: 0 to 730, to 5V: 0 to 1023
#define RheoPin 1
#define spl(x) Serial.println(x)
void setup() {
Serial.begin(9600);
}
void loop() {
int i, r;
while(!Serial.available()) delay(100); // Wait for request
while(Serial.available() && i < 10) {
Serial.read(); // discard input
}
r = analogRead(RheoPin);
spl(r); // Writes number as ASCII to the USB
}
Meanwhile, on the other end of the USB cable -- the Pi Python program:
import serial # I had to install "pySerial" for this
import time
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
ser = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=1)
ser.open()
while True:
ser.write("1") # Ask the Arduino for a reading
time.sleep(.2)
ct = ser.inWaiting()
if ct > 0:
s = ser.read(ct)
i = int(s.rstrip()) # ASCII to Int
print i
time.sleep(.5)
There's good news and bad news about this approach:
GOOD:
* No GPIO pins used (a USB port, instead).
* My Arduino program worked the first time.
* Because the Arduino only runs one thing at a time, results can be more accurate.
BAD:
* More complicated, two kinds of programming, etc.
* The cheap Nano still costs 3X the MCP3008 chip.
* The request-to-response turn-around is about 1 second, minimum.
Overall, I like using the Arduino. Better yet, the Pi model B+ should have had analog pins.
REVISED:
I have successfully added other sensors to the Arduino end of the setup:
1. A photosensor.
2. An HC-SR04 rangefinder.
And I have checked out adding --
3. DS18B20 temperature and DHT22 temperature/humidity sensors (although they work fine on the Pi).
4. Output to a 2x16 LCD character display (saves 4 GPIOs on the Pi).