Category Archives: atmel328 coprocessor

LEGO powerfunctions control with scratch 1.4

LEGO has a nice set of controls named ‘powerfunctions’. The main device is a IR-receiver which can control motors, LED with a variety of functions. ON,OFF, PWM are available.

To connect this to scratch I use an arduino to control the IR-LED. Arduino is connected by USB to raspberry pi.

The LED is connected to the arduino UNO on a breadboard. I had one from an earlier experiment already mounted to a small board. When arduino outputs are used, current for the LED is limited to 20mA. With an external transistor, current and thus the range can be increased. With my setup range was prox one to two meter.


The setup shown uses an arduino UNO. It is also possible to use an arduino NANO instead. Other arduino boards like mega,zero due should be possible, but not tested.

Arduino code uses a library from a library with small modifications.

The code can control up to four channels. The LEGO RC protocol used is ‘Combo PWM mode’. The timeout needed is handled by the scratch Adapter, resending commands each 0.3 sec.

With a mobile camera, it is possible to make the IR LED light visible. The sensors used in camera have a broad sensitivity area and record IR light too.


In scratch are a few variables needed like c_4_A or c_4_B for the channel 4 ‘red’ or ‘blue’ signals. Values are -7 to +7 for backward max speed to forward max speed;, as a special value ‘BREAK’ can be used.

Adjust USB connection in config file config/config_arduino_powerfunctions.xml

Start scratchClient with

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


When variables are available, a sample script is quite easy. This script was used to record the video.

2016-03-27 updated fritzing chart: LED connection now GND to PIN12 with resistor.

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.


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.
pwm:4,90\n  sets PWM channel 4 to 90.
p:4,90\n is the same command, abbreviated.

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

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


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/


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.


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


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’.


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 []. 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.


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.

Atmel328 firmware for DHT22 Temperature, Humidity

The temperature, humidity sensor DHT22 is a quite inexpensive sensor, well suited for microcontroller applications. It uses same protocol as DHT11.
It is connected by a single wire, needs 5ms for a read cycle, but a quite challenging protocol where the pulse width gives ‘0’ or ‘1’ bit values.

This is a typical application for a coprocessor for raspberrypi. For an atmel328, it is not a challenge to handle this protocol.


The signal from this sensor is relying on exact timing.


The initial ‘pulse low’ is not in the chart.

The firmware uses internal timer with 1 us resolution to measure pulse widths. Using the timer unit makes this method insensitive when interrupts produced by SPI communication occur in parallel.

The atmel firmware triggers the data aquisition, and provides a 40bit ‘raw’ result to the raspberry pi host computer. The conversion of the values  to temperature, humidity values is performed in python code. See the sample code provided in the download to see this procedure.

Of course, there is an adapter for scratch.
cd ~/scratchClient
sudo python src/ -c config/config_dht22_atmel328.xml

A detailed description on how to program the firmware is on the download page.

Timer for HC-SR04 ultrasonic sensor and scratch

The ultrasonic sensor HC-SR04 is a quite inexpensive ultrasonic sensor, well suited for microcontroller applications.
It produces pulse width modulation directly giving the signal run time.

For 1.7m, at sound speed in air of 340m/s, you get 10ms pulse width.
Up to now, my scratchClient software had no ability to support this device. In order to evaluate different approaches to measure pulse width timings in this range, I have set up an arduino board simulating this device with 10ms timing.
The goal was to have around 1000 measurements and look for the distribution of values.

Approach A was to take python code as found on the net. Two loops, first one looking for raising pulse and second one looking for falling pulse.

Results are not very precise.
There are quite a lot of measurements at 10ms, but 2/3 of all results are up to 40% higher; few also till 16,5 ms. This is as expected, as the IO system is slow, and a lot of other things are running in the system in parallel.
Advantage is that there are no additional cost, except some voltage dividers needed.

Approach B is a microcontroller subsystem using the atmel 328 chip, sitting on a breadboard and connected with SPI to RPI. The internal oscillator is used for simplicity and reduced cost. This setup is similiar to the adc-setup described in another post.
Time measurement is using the 16 bit timer in 1/64 resolution, yielding 8us values.

Results are pretty nice, although the deviation is 3% from 10.0ms. Most possible this is caused by the free running oscillator running a little bit too fast; some more investigation is needed here to eliminate software errors.

The code is polling the timer, which is fast enough for this application. SPI is handled with an interrupt coded in assembler. This allows up to 240kHz SPI frequency.
The software is completed and supports up to 4 sonic sensors.
Cost is prox 3.5$ per unit, some soldering and some voltage dividers. No difficult software setup needed.

I found other approaches on the net. DMA code, C-Code or alike. Problem here is the complicated software setup (no ready to use solutions) and the difficult integration into the python environment with RPI.GPIO.

The hardware setup is straightforward. Note the 5V on the supply voltage of the HC-SR04. Doublecheck also the ground connection from HCSR04 to breadboard and to Raspberry. This is important to avoid to get 5V into the raspberry inputs.

For the scratch setup, there is a sample configuration with device(0) connected.

cd ~/scatchClient
sudo python src/ -c config/config_hcsr04_atmel328.xml

In scratch, enable remote sensor connections. You receive ‘distance_A’.

For detailed instructions on how to program the atmel processor, see the documentation in the download file on download page. The programming is performed by the raspberry pi with the SPI cabling.

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.


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


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.