Category Archives: ADC

Arduino UNO, NANO connected to Scratch

Arduino UNO has an USB connection, which supports serial connection to a host computer. The arduino can be used as a IO expander, connecting digital io lines, pwm, servo or adc-inputs directly to scratchClient and to scratch.
On digital inputs D2-D12, the firmware supports counters. The inputs are debounced  and frequencies are possible till prox 50Hz.

This setup with scratchClient can be run on Raspberry or on windows, unless scratch 1.4 is used.

Powered by the USB-connection, the UNO provides 5V-compatible inputs/outputs. This is an advantage in some constellations. But do not connect these outputs directly back to the raspberry GPIO pins. And be careful on power consumption. Small servo can be operated, but larger current devices need external 5V supply.

The solution is also applicable to arduino NANO. This small board offers a breadboard friendly layout.

nano_breadboard

Sample setup with a NANO, 3 LED, Poti, Button, Servo and NANO on breadboard. Host computer (Raspberry Pi or Windows) not shown.

The functionality presented here is not a bridge to mesh network, propagating events and sensor updates into the arduino. There is a custom arduino sketch needed which only exposes the IO resources, but does not allow for additional logic in arduino (yet).

Configuration of the io-pins (direction, pullup, pwm, servo) and adc-pins (whether used or void) is controlled by scratchClient through configuration.
The scratch names used are configurable in configuration too. This is common functionality of the framework.

Communication between host computer and arduino is by a serial line USB connection.  Speed is 115200 bd, set line end to LF . The arduino protocol uses as short as possible command sequences.
Example:
pwm:4,90\n  sets PWM channel 4 to 90.
p:4,90\n is the same command, abbreviated.

With
help\n
a summary of command features can be printed.

The protocol is build on readable ascii sequences, which makes debugging with arduino serial monitor easy (set line end feature to ‘newline’). This also allows to fully drive the protocol from the serial console.

The command parser uses a state based approach for speed purpose. Each received char needs to be processed as quick as possible, which is only possible with a state machine.
First implementation was collecting chars in buffers and on a LF-char the data have been compared to the different commands. This needed many expensive strcmp-operations, decoding the parameters was done by sscanf. This approach limited throughput.

The parser code is generated by a python program and the resulting code is then inserted into the arduino C-program.

The code for arduino, sample configuration for scratchClient and sample scratch program is in the scratchClient distribution.

For setup, follow the steps described below.

Step 1, program the firmware to arduino

Start arduino IDE software, load arduino/arduinoUno/arduinoUno.ino from the scratchClient distribution and program it into the UNO or NANO. This needs to be done only once. I run this from a windows machine, but arduino IDE should also be supported on Raspberry Pi.

The LED13 on the arduino should blink at 5Hz, quite fast. This indicates that the firmware is running, but did not yet receive configuration.
On a serial monitor, you should see:

arduino sending@115200 Bd
arduinoUno, version 2016-02-21
config?
config?
config?

The config?-request is printed each second until the host provides configuration commands. Close serial monitor in order to allow scratchClient to have access to the serial line.

With ‘help’ from the serial monitor (use newline for line end separator), the arduino provides the list of supported commands.

Step 2, sample Hardware setup

arduinoUno_Steckplatine

The hardware uses a potentiometer (2k to 10k are ok) on AD0. On D3, there is a button connected. The other side is having a 1k-resistor to GND (just in case the output is configured as an output, this prevents damage to the IO).
Two LED are for output. The green LED is on a PWM-output D5, so it can be dimmed.

This setup is a sample. The functionality of all the inputs and outputs are defined by configuration in scratchClient. See config/config_arduino_uno.xml for a sample.

Step 3, connect arduino with USB-Line to RaspberryPi or windows computer.

On raspberry, lookup /dev /tty* connections and configure the UNO serial device in config/config_arduino_uno.xml-File.

For windows, you see the COMn-Device used in deviceManager. Configure this name in config file.

An arduino UNO or NANO needs a few 20mA when running,  LEDs add prox 10mA each. This current is provided by USB port of host computer. If more power is needed, then an external power supply is needed.

Step 4, start scratchClient with configuration

cd ~/scratchClient
python src/scratchClient -c config/config_arduino_uno.xml

After a short while, the LED13 should start blinking at 0.5Hz, quite slow. This indicates that configuration was downloaded and system ready to be used. The Tx, Rx-LED on arduino should flash now and then. Quite often when you turn the potentiometer, or when you press the button.

Step 5, start scratch with sample program

There is a sample program in scratch/arduinoUno/arduino.sb

scratch

The program takes the button input and controls the red LED with it.
The value from the potentiometer is used to set the pwm-rate and dims the green LED. The mapping of the variable names or sensor names to IO-points is done in config file.

ID-Code

The arduino can have an ID-code in eeprom, which can be set by serial line console and read out from remote. This ID allows the host raspberry to recognize the arduino and provide configuration for this special device. This is a very nice feature for school setups where some experiments are hard wired and need fixed configuration. There is a starter code available which checks the connected arduino, and presents the related config files for scratchClient to start. I am working on an extension to start scratch with a basic program too. Avoids a lot of handling errors in school, especially where the focus is on driving an experiment and coding is not so important.

The serial protocol allows to read and set the ident code.

cident?\n     request idcode
cident:<char16>\n write idcode

Configuration Tool

The setup of the xml config file is not very intuitive. There is a config gui available to edit the file. The tool is started with

cd ~/scratchClient/tools
java -jar scratchClientConfig.jar

scratchclientconfig

The left side of the frame is the editor pane which allows to select the various functions for the arduino. The right panel is a view-only display of resulting xml data.

Existing files can be loaded, but current version (2017-02-10) only allows to handle one adapter of type ‘UNO_Adapter’.

Constraints

The adc-channel is limited to 10Hz update rate. There is averaging for three samples per measurement value transmitted.
The digital inputs are limited to 20Hz update rate.
The adc-channel of atmel328 allow for analog inputs or GPIO usage.
PWM pulses are created with arduino native analog_write on the digital pins. Value range for pwm are 0..255.
Servo pulses are created with Servo-library. See limitations of this library in Arduino Servo [https://www.arduino.cc/en/reference/servo]. Input values for servo are 0..180.
Configuration is not persisted in the arduino (but downloaded from the the scratchClient adapter); there is no interface for custom logic (for fast sensors).
Configuration is requested to be sent from PI or windows to arduino on reset of arduino. If scratchClient configuration is changing, then a reset of arduino is needed to make this active. As in most cases a hardware change is made with arduino disconnected from power (either USB cable or power plug), this is only a small limitation.

This scratchClient adapter runs also on windows platform. This allows setups where a windows computer, scratch 1.4 for windows are using IO connections.

Other libraries

Recently I discovered ‘nanpy’, a python library to control an arduino by python programs.

Updates

Updated 2017-03-15, Counter for digital inputs added.
Updated 2017-02-10, Config tool for xml config file included.
Updated 2016-02-21, Some remarks on state based parser, command sets.
Updated 2016-02-15, added servo capability.

Environmental Sensors for scratchClient

The recent months have been busy with preparing new experiments for my
school project, especially one experiment measuring temperatures with TMP36. See
link

When looking in detail to the datasheet of TMP36, there is an accuracy of max
+- 4K (G-Grade device) and +- 3K (F-Grade device). This is not bad for -40 to 125 °C. At 25°C, accuracy is  +- 3K (G-Grade device) and +- 2K (F-Grade device).
Unfortunately the ADC on my adapter board, the MCP3202, uses the
vcc-voltage as reference, which gives additional error for the measurement.
With patch cables, there is also some noise. I twisted signal and ground
line, added some capacity close to the TMP36 power pins and a low pass
filter in the adapter logic. Which reduced, but did not remove the problems.

So I started to look for more precise alternatives. LM35 in combination
with an adc ads1015 and internal precision reference voltage gives better results.
LM35A specs give +-1K over -40 to 110 °C, around 25°C +- 0.5K.

When starting to look for integrated solutions, complex devices like SHT15
come around. Main purpose is to measure humidity, but temperature
measurement is included. +-0.3K around 25°C and +-1.5K in -40 to 90°C are
quite good. I2C is not supported, but a two-wire GPIO protocol is
available. Disadvantage is the high price.

BMP085 is a digital pressure sensor with temperature sensing included. +-2K
accuracy in 0 to 65°C. I2C, internal calibration data in registers, needs
some calculations to correct the raw values.

MAX31855K is used with k-type thermocouples and extends temperature range
to -200 to 1350°C. Note that K thermocouples have about ±2°C to ±6°C
accuracy. SPI interface is easy to use.

And for curiosity, I added a luminosity sensor BH1750 to this collection of
devices.

Scratch integration is ‘as usual’ with adapters, where configuration is
done by xml files.

Hardware interface to the devices (to be more precise: the breakout boards
with the devices, is by I2C, SPI or plain GPIO. For the SHT15, I added a
serial resistor of 1kOhm for the data line to protect against
input-output-mismatches during debug phase of code. For the clock line, this
is not needed, but in general a good idea to a serial resistor there too.
Too expensive this device, to take the risk of burning it away.

These sensors will not be part of the school workshop documentation. Setup
is described in the scratchClient handbook → link.

ADC-328-Board is here

The  boards for the Atmel-328 based ADC board are here. And it works, only the LED connection was on the extra pin used by the 20MHz-version of this design. Corrected in software, already.

See the adc-board post, the capacitive sensor post for application details. The basic design is for a breadboard, but I wanted to have a portable package for this.

Schematic is here, the eagle schematic and board files are in the software package.

To get the board running with scratch, you need my scratchClient software.

Functionality are – with the firmware – 2 adc channels, frequency counter, impulse counter and infrared control. The two rotary encoders are prepared, but not yet coded.

board

The board uses 1206-size SMD components, just the size you can solder without a microscope.

JP1 is usually open, and connects GPIO4 to clock input. See flashing instructions.

SV1 is to the RPi

SV2 is ADC input. 1 = GND, 2 = GND, 3 = ADC0, 4 = ADC1, 5 = VCC, 6 = VCC

SV3 is usually open. It allows to connect RX, TX with those of RPi. It is aligned to allow to connect with two jumpers. I used this mainly for debugging purposes.

SV4 is the frequency measurement input. 1 = GND, 2 = input, 3 = VCC

board

This project is no kickstarter, and I do not sell this pcb.

So setup the parts on a breadboard, and if you like it find one of the reasonable cheap, long delivery time vendors in the world and build your own copy.

ADS1015 als AD-Wandler am Raspberry Pi

Siehe auch
Atmel 328-Prozessor als AD-Wandler für Raspberry Pi
MCP3202-AD Wandler am Raspberry PI
Arduino UNO, NANO connected to Scratch

Die Firma adafruit vertreibt eine kleine Platine, die einen 12-Bit ADC ADS1015 enthält. Dieser hat eine eigene Referenzspannung und einen einstellbaren Verstärker. Bis zu 4 Analogkanäle können angeschlossen werden. Der nutzbare Spannungsbereich ist 0 bis 3.3V, da im Beispiel die Platine mit 3,3V betrieben wird.

Diese Platine kann zum Anschluss von analogen Sensoren mit scratch benutzt werden.

Benötigt: Steckbrett, Lötkolben, Lötzinn, Steckkabel Buchse/Stecker und einige kurze Drahtstücke. Potentiometer 2.2kOhm (hier geht auch bis 10kOhm) als Beispiel für einen Sensor.

aufbauUm die Platine an den RPi anzuschliessen ist ein Steckbrett nötig. Die Platine wird ohne montierte Steckleiste ausgeliefert, diese muss selber angelötet werden. So sieht das dann aus.

 

 

Die Verkabelung ist hier aufgezeichnet.

ads1015_bb

Hier ist das Potentiometer an den Eingang A2 angeschlossen. Es kann jeder Eingang verwendet werden, das muss dann aber auch in der Konfiguration des scratchClient berücksichtigt werden.

Vorbereitung (siehe auch die Installationsanweiung in der Dokumentation des scratchClient):

sudo apt-get python-smbus i2c-tools
sudo modprobe i2c-bcm2708
sudo modprobe i2c-dev

Die ‘i2c-tools’ sind eine Sammlung von Werkzeugen, um den i2c-Bus zu prüfen und Geräte anzusprechen. Nach der Verkabelung kann geprüft werden, ob der Baustein ansprechbar ist.

pi@raspberrypi ~ $ sudo i2cdetect 1
WARNING! This program can confuse your I2C bus, cause data loss and worse!
I will probe file /dev/i2c-1.
I will probe address range 0x03-0x77.
Continue? [Y/n] Y
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- 48 -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --
pi@raspberrypi ~ $

Der ADS1015 taucht hier mit der (hexadezimalen) Adresse 0x48 im Listing auf.

Start des scratchClient:

cd ~/scratchClient
sudo python src/scratchClient.py -c config/config_adc_ads1015.xml

Scratch erhält die Werte vom scratchClient  im Bereich 0..3300 (ungefähr) als adc_A2. Das ungefähr deswegen, da der Baustein die Spannung absolut mit seiner eingebauten Referenzspannung misst. Wenn jetzt die 3.3-V-Versorgung der RPi etwas vom Sollwert 3300 mV abweicht, so weicht auch der Maximalwert ab.

Der Name ‘adc_A2’ ist in der Konfigurationsdatei so eingestellt, da im Beispiel der Kanal A2 verwendet wird.

MCP3202 AD-Wandler am Raspberry Pi

Siehe auch
Atmel 328-Prozessor als AD-Wandler für Raspberry Pi
ADS1015 als AD-Wandler am Raspberry Pi

Im Schulkurs wird eine Adapterplatine verwendet. Im Prinzip sind alle Experimente aber auch ohne diese Platine möglich.

Eine der Ausnahmen ist der Anschluss eines Potentiometers, für das ein Analog-Digital-Umwandler ‘ADC’ benötigt wird.

Der im Kurs verwendete Baustein “MCP3202 CI/P” ist im steckbaren DIP-Gehäuse erhältlich. Der Baustein kann auf dem Steckbrett benutzt werden.

ikg_adc_direkt_Steckplatine

Der Baustein  wird über den SPI-Bus angespochen. Das sind die im Diagramm verwendeten blauen Signale. Die schwarzen und roten Drähte sind die Stromversorgung des Bausteins. Der gelbe Draht ist der Spannungseingang des ADC; da ist im Aufbau ein Potentiometer angeschlossen.

Für den Aufbau der Schaltung sollte der raspberry pi ausgeschaltet sein. Die Schaltung sorgfältig aufbauen und kontrollieren.

Die für den Anschluss an scratch nötige Software ist der scratchClient, die Konfiguration ist config/config_ikg_adc.xml.

cd ~/scratchClient
sudo python src/scratchClient.py -c ikg_adc

Bei der Installation des Rechners muss der SPI-Treiber aktiviert werden.