Sunday, 7 August 2016

4-20 mA current output for Arduino Uno

The purpose of this project is to provide a 4-20 mA output from a PWM signal generated by a microcontroller ATmega328 and numerous other chips, such as the PIC. One of the more interesting applications of this circuit would be to replace or to realize a smart sensor with Arduino.

Last year I had designed a circuit suitable only for Arduino Due, this new work makes use of a common Arduino Uno or similar to create a standard 4-20 mA analog output.
Arduino Uno, or systems based on the ATmega328 chip has no a true analog output. The easiest way is to use one of the PWM outputs and filter the signal with a passive RC filter to obtain an analog signal proportional to the duration of the pulses. This expedient creates a considerable noise due to the frequency of the PWM itself. To eliminate the noise I used a second order active low-pass filter, Sallen-key type. The frequency of the Arduino PWM (with 16 MHz clock) on pin 9 is about 490 Hz, so I used a very low cutoff frequency (11 Hz) but with a bandwidth sufficient for the majority of industrial controls.

By connecting the filter directly to the PWM output is obtained a signal which varies from 0 to 5 V which would give an output current of 0 to 20 mA. The pulses duration is programmed with a word of 8 bits, losing 1/5 of the full scale. To improve the current resolution from 20/255 to 16/255, I modified the minimum amplitude of pulses from 0 to 1 volts, giving at the output a 4 to 20mA current. The block diagram is shown in figure 1.

Figure 2 shows the complete diagram of the circuit. To obtain pulses from 1 to 5 volts I had to use a 1 V source realized with U1A and the transistor Q1 that works as a switch. The operational U1B operates as a separator; the filter uses U1C and the voltage / current converter uses U1D and Q2.
The transistor Q1 inverts the PWM signal, so the software must complement the number of PWM duty cycle.

The trimmer pot Rp1 is used to adjust the minimum output current (4 mA) and the Rp2 to adjust the maximum (20 mA). The theoretical value of the emitter resistor is Re = 5/0.02 = 250 W, but that does not take into account the tolerances of the voltage supply of Arduino and of the resistors.
The resistor R8 is used as U1D output current limiter in the situation of absence of load.
A step down converter is a good solution for powering the system because of the 24 V, this value can be varied from 12 to 30 V, depending of the load circuit.
Arduino Uno has a +5 V output pin, It does not recommend using it as a power input          inasmuch this would be in parallel with the internal regulator but it can be powered at +5V using the USB connector, other boards as Arduino Pro Mini, have a +5 V input.

Hardware components
1x Arduino board,
1x Step-down switching converter,
Components list
R1= 27 kW ±5%
R2= 47 kW ±5%
R3= 10 kW ±5%
R4= 27 kW ±1% metal film
R5= 6.2 kW ±1% metal film
R6= 100 kW ±1% metal film
R7= 100 kW ±1% metal film
R8= 1 kW ±5%
R9= 270 W ±1% metal film
R10= 1.8 kW ±1% metal film
Rp1= 1 kW trimmer
Rp2= 10 kW trimmer
C1= 100nF Mylar
C2= 100 nF Mylar
C3= 200 nF Mylar
C4 = 10 MF,50V Electrolytic
C5 = 100 nF Mylar
U1= LM324 quad op amp
Q1 = 2N3904 or eq.
Q2= 2N2219A or eq.
The capacitors used for the filter must be measured with a capacimeter, for my prototype I selected for C3 some 220 nF capacitors to search for a value that approached 200 nF and C2 have selected a value half of C3.  Q1 is a transistor that must have a low Vce(sat.) and Q2 must have a current gain of at least 100 and a Vceo of at least 40V with a minimum power of 500mW.
The operational amplifier U1 must be suitable also for single-rail power supply, such as LM324.
The components layout of my prototype is shown in Figure 3, the resistor on the top is a precision load used for calibration of the system. Q2 has a small heat sink because, with at 20 mA and a low voltage load,  as in this case,  dissipates: (24-3-5) *0.02 = 320 mW. In these circumstances is better to reduce the 24 v.
The test program
To test the system I used an Arduino with an LCD display and a potentiometer connected to analog input A0, as pin PWM I used D9. The program is very simple: read the potentiometer, converts 10 to 8-bit Analog reading and produces the PWM.

// program to test Arduino Uno PWM
// G. Carrera 2 ago 2016

#include <LiquidCrystal.h>

int PWMpin = 9;      // PWM out on digital pin 9
int analogPin = 0;   // potentiometer connected toA0
int val = 0;         // variable to store the read value
char spacestring[17] ="                ";

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

void setup() {
  pinMode(PWMpin, OUTPUT); // sets the pin as output
  lcd.begin(16, 2);// set up number of columns and rows
  lcd.setCursor(0, 0);// set the cursor to column 0, line 0
  lcd.print("Stalker PWM test");// Print a message to the LCD

void loop() {
  val = analogRead(analogPin) >> 2;// 10 to 8 bit conversion 
  analogWrite(PWMpin, val);
  lcd.setCursor(0, 1);
  lcd.setCursor(0, 1);

I reported on the spreadsheet the PWM values and the measurements in volts made on a precision resistor (150 W ±0.5%) that worked as a load,. The PWM / output current diagram is shown in Figure 4.
The linearity is very good as confirmed by the coefficient of determination R2 = 0.999992.
If you want a positive slope, the value must be complemented to 255 in this mode:
val = 255-val;
In my program, you could generate a new value every 500 milliseconds (2 Hz), but you could reduce this period of up to 100 ms (10 Hz).

Saturday, 2 July 2016

A PIC based 50MHz frequency meter

This project describes the realization of a sensible and accurate instrument to measure frequencies up to 50 MHz of signal amplitudes up to a few tens of millivolts. The instrument is small in size and can be battery powered, so it is a handheld instrument.

It is not very difficult to develop a microcontroller program capable of performing the frequency measurement of a periodic signal. The most critical and delicate circuit of a frequency meter is the input stage, which has the main task of amplifying weak signals to the maximum frequency that the microcontroller can process. The amplified signal must be squared and then brought to the logic levels of the microcontroller. Obviously, all these questions are useless if we need to measure only signals that are already at TTL level.

The circuit

After having examined and tested many circuits, I chose the circuit seen in Figure 2.
The transistors Q1 and Q2 form a wide bandwidth high to low impedance converter and the capacitor C1 removes the dc component. The core of the input circuit is the integrated circuit MC10116 which is responsible for amplifying and squaring the signal with switching times of few nanoseconds. This IC is a triple differential amplifier designed for use in sensing differential signals over long lines. This old chip is still produced and reachable on the market.
 Of course, these circuits have to work with very low impedances, thus require a relatively high supply current, approximately 100mA.
The transistors Q3 and Q4 serve to transform the differential output of MC10116 in a single ended signal with TTL levels.
For the measurement of the frequency and for the driving of the LCD display I used a PIC16F628, an extremely diffuse PIC. Power is supplied by four 1.5V batteries. To get the 5V, a low-dropout regulator is employed.

The complete diagram of the system is shown in Figure 3.
The figure 4 shows the inside of my prototype, the PIC microcontroller is not visible because covered by the display, which has a row of 16 characters, but it is seen by its controller as two rows of 8.
The arrangement of all the components on the card is shown in figure 5. A small heat sink is used for the regulator because the current consumption is about 100 mA.

The crystal accuracy

The typical frequency tolerance of a quartz crystal is ±10 to ±100 ppm (part per million), and its frequency/temperature coefficient depends upon the crystal cut, for a 32,768 Hz xtal it is about -0.04 ppm/°C but on other cuts it reaches 5 ppm/°C. Although at 50,000,000 Hz we have the resolution of 1 Hz, the error due to the accuracy of quartz and its stability with temperature is much greater. The more accurate frequency counters have a TCXO (Temperature Compensated Crystal Oscillator) and the best stability is achieved from OCXO (Oven Controlled Crystal Oscillator).
It would be possible to make even the accuracy correction of quartz, usually in the order of +/- 50 ppm. A higher accuracy is obtained with an external high-stability quartz oscillator.
By comparing the reading with that of a precision frequency counter or reading a very precise frequency reference, such as that of the carriers of certain radio stations, you can correct the frequency by setting the final count counts. I made the calibration, correcting particularly the delays introduced by the program instructions execution.

The program

The PIC Timer#1 is used as counter on PB6 digital input, with interrupt on overflow. Every Timer#1 overflow the variable overc is increased by the interrupt routine. The Timer#0 is programmed to generate an interrupt every 8 ms, for a time base of one second 125 ticks are needed. Every second is calculated the total count, it is also made a correction, and displayed on the LCD.
The number of overflows of the 16-bits register of Timer#1, stored in overc, represents the most significant word, while the content of the Timer # 1, stored in count, is the least significant word of the final count. For example, for a frequency of 50,000,000 Hz the variable counts = hex 02 FA F0 80, so overc = hex 02 FA and count = hex F0 80.
The correction tries to reduce delays xx of the overflow interrupt routine, in fact it subtracts from the counts the term xx * overc, in this case xx = 46.
I compiled my program  in mikroPascal PRO rev.7 for PIC (mikroElektronika, The length of the code is longer than 2k bytes, so it can’t be compiled with the free version of the compiler and I provide also the hex file to the PIC programmer. With recent versions of the compiler you must make some modification to the display pin definitions.
You can download the files from:

1)      “MC10116 – Triple line receiver”, Motorola, Inc. 1996.
2)      “AN MSI 500 MHz FREQUENCY COUNTER USING MEeL AND MTTL”, Jon M. Delaune, Motorola application note AN-581.
4)      “Fundamentals of Quartz Oscillators”, Hewlett Packard Application Note 200-2

Sunday, 26 June 2016

A 16 channels 12 bits acquisition system

Today many microcontrollers have one or two 10-bit or more built in AD converters with a multi-channel multiplexer, but the quality of conversion is rather poor because of the considerable background noise always present together with a low linearity. So, I think it will be useful the proposed system, since the components are still readily available and the results obtained are at a professional level.
However I think that even with a different ADC hardware, the software used is still valid, as a result of years of experience. The system design is a front end controlled remotely via a serial link that can be the standard RS232 / RS422, or wireless.

In the years '80 I had designed a digital acquisition system (DAS16) based on the classic 12 bit analog to digital converter AD574, from Analog Devices. In addition to this device I was using a 16-channel multiplexer HI506 followed by a sample and hold circuit based on HA2425. The diagram of this board is visible in Figure 1.  I used it with various computers and microcontrollers, including the IBM PC, through the parallel interface, the Apple II with a my own interface card and finally, with a 80196 microcontroller. The system remained unused for several years, then in 2007, I designed a new controller based on a PIC to interface it with computers or tablets via a serial interface. The system was slower, but the parallel interface was disappearing from laptops.

The counter CD40193 can be used to load the starting address of the channel and then to generate the subsequent scanning addresses by means of a simple clock.
The two 74LS367, hex buffers with 3-state outputs, are required to create an 8 or 4 bit data bus from the 12 bits parallel output of the converter. The 4-bit bus, was necessary for the printer interface of the first PC, which had not yet become an 8-bit bidirectional bus (standard IEEE 1284).
The board must be powered at +/- 15V and a LM7805 is mounted on it to power logic devices. A reed relay (K1) is used to change the range from +/- 5V to +/- 10V, under software control. A 31 pins male connector (DIN 41617) was used in my board.

The DAS controller

I used a PIC16F73 because already available. The scheme is shown in Figure 3. I used a 18.432 MHz quartz because suitable for the exact generation of the UART baud rate. This component is easily found in the old PC serial cards.
Since microcontrollers don’t have a great memory, I could not use a large ram buffer that allows a high sampling rate. Then the achievable sampling frequency is limited by the maximum baud rate of the UART. The program, according also to the channels to be scanned, check if the required sample period is valid for data transmission.
Figure 4 shows the arrangement of the components of the PIC DAS controller. A 32-pin DIN connector connects this board with the DAS16. Note the double-dip switch that is used to set the 4 possible baud rates (on on: 9600, on off: 19200, off on: 57600, off off: 115200). An external push button is used to start the acquisition and a red LED lights up during the whole time of the acquisition.

This system, with the software provided, can acquire up to 16 analog channels at the maximum frequency of 1kHz, for one channel, at a baud rate of 115200 b/s. The time required for one scan of 16channels is about 0.4 milliseconds plus the time to transmit the data. The following table gives an idea of the possible sampling frequency limits.
baud rate
Ts [ms]
Fs max. [Hz]
With a baseline period of 1 ms, the maximum sampling period is 255 ms which corresponds to a minimum frequency of about 3.92 Hz. If you want to use lower frequencies, with simple changes (TMR0 = 76 instead of 238) you can use a basic period of 10 ms, as it was in the first version of the program.
As the project is not new but dates back to 2007, it is used standard serial interface RS232. Today you could use a TTL / USB serial adapter or a serial bluetooth module to connect to PCs, tablets or smartphones.

Figure 5 shows the connections between the boards.

The program
I modified and improved the program I had written in 2007 with a new version of the compiler and improving the interpretation of the command string. I had some problems because the memory limits of the PIC16F73, using about 92% of PIC flash memory and 96% of ram,  but I did not want to change the CPU with the newer ones.
All acquisition parameters, ie the initial and final channel of the scan, the full scale (+/- 5 or 10V) and the sampling frequency can be set by the computer by means of a command string. The acquisition start pressing the appropriate button or sending an ‘A’ by the terminal. The program checks whether the required sample period is compatible with the number of channels and the UART baud rate, in case of incompatibility a warning is printed on the terminal and a new corrected command string will be necessary.
The configuration string is of the form:
ci = start channel (0..15);
cf = last channel of the scan (0..15);
BPm = Base Period multiplier (1..255), the Base Period = 1 [ms];
ns = Number of samples (1.. 65535);
fs = ADC full scale (5 or 10) bipolar.
The command string header is ‘$’ and the end is ‘*’, for example, the command string : “$0,5,50,2048,5*” is interpreted as a scan from channel 0 to channel 5 with a sampling period of 50ms, 2048 samples with a +/- 5V range.
If the parameters are okay, the system print the message 'Push Start Button or write A to start', otherwise one of the following messages will be printed:
Errors on configuration string !!
If we use a sample period too short  compared to the baud rate and the number of channels, the following message will printed:

Ts is incompatible with baud rate !!
Ts must be greater than xxxx [us]

Where xxxx = tscan+ttx is the minimum sampling period to be used, in microseconds.
In both cases a new correct string will be sent. In the case of the example above, the system respond to the command string with the message:

Initial Ch = 0, Final Ch = 5, +/- F.S. [V] = 5
Ts [ms] = 50, Samples = 2048
Push Start Button or write A to start

This information is useful for the program that will process the data, so it may be saved on the captured file. After pressing the button, or sending ‘a’, we can read the transmitted data:
  -720  -481  -708  -505  -730  -488
  -691  -464  -683  -490  -708  -488
The rows with the channel scans are preceded by the word 'DATA'. During acquisition the led is on and, at the end, the system is waiting for a new acquisition with the same parameters. If you want to change them, a reset button or turning off and turning on the power switch will restart the system.
The next lines, one for each scan, contain the data in a fixed format, six characters (including the sign) per channel, expressed in [mV].
On PC or tablet, you can use a terminal emulation program capable to save the received data to an ASCII file, I used RealTerm on Windows 7.
I compiled the new program  in mikroPascal PRO rev.6.6 for PIC (mikroElektronika, The length of the code is greater than 2k bytes, so it can’t be compiled with the free version of the compiler and I provide also the hex file for the PIC programmer.

Monday, 30 May 2016

The acoustic sensors and their limits

by Giovanni Carrera rev. 30/05/16
Ultrasonic ranging modules as the HC-SR04 are widespread in the electronics and amateur robotics, but it is also important to know the limitations of these sensors and the possible improvements of their accuracy. Before introducing the measurement circuits and firmware, I dedicate a space to the speed of sound and its propagation.

The speed of sound in air

The sound waves propagate in a medium by means of oscillatory displacements of its particles, around the rest position and along the direction of propagation of the wave. The vibratory movements are transmitted to neighboring particles and so on. The speed of propagation of sound waves depends on the density of the medium, so it is almost nothing in the vacuum and maximum in metals. The acoustic waves are generated by a source, whose geometrical dimensions are in some way related to the wavelength, therefore the inverse of the frequency generated. For this reason, the speakers used for the bass of a stereo system are considerably larger compared to ultrasonic transducers.
If we know the propagation velocity v we can calculate the wavelength l, the space occupied by a cycle:
v = space/time = l/T = l×Þ  l = v/f
Indicating with T the period of the oscillations of the particles, i.e. the duration of a wave cycle and the inversion of the frequency (T= 1 / f).
In the case of a source from 40 kHz ultrasonic, like that used, the wavelength is:
l = 344/40000 = 8.6 [mm]
For a distance meter, the wavelength is very indicative, since it gives an idea of ​​the spatial resolution and the size that the objects must have to reflect these waves, that is, much larger thanl. These concepts are very similar to those of the radar, which uses electromagnetic waves instead of acoustic waves. The wavelength for typical nautical radar is about three centimeters. Using acoustic waves at higher frequency would create problems because of the greater absorption and therefore require significant peak powers of the transducers, which are currently of the piezoelectric type. Also the echo sounder has the same problem: to be able to detect small targets, such as fish, the frequency must be increased from 30kHz, for bathymetry, to 400kHz for fishing, knowing that the speed of sound at sea is about 1500 m/s, the respective wavelengths are: 5 and 0.375 cm.
Unlike marine transducers, there are major problems in the air, due to the worst acoustic coupling of the transducer in the air with respect to water.
The speed of the acoustic waves is not constant, but depends on various factors such as temperature, humidity and atmospheric pressure in the environment in which it operates. The most significant is the temperature; a linear approximate formula is as follows:
v » 331.45 + 0.6  Tc   (1)
Where Tc is the temperature in degrees Celsius. The previous formula is derived from the linearization of  this more accurate expression:

·        R = universal gas constant = 8.314 [J/(mol×°K)]
·        T= absolute temperature in Kelvin degrees [°K]
·         g = adiabatic constant of gases
For dry air, g = 1.4 and M = 0.02895 [kg /mol], grouping constants, we obtain:

From which we see the dependence of the speed with the square root of the temperature, expressed in Kelvin degrees. For modest temperature variations do not have large differences, as we can see in figure 1.
Figure 1 - Speed of sound versus temperature.
For our application, we can use the linear formula (1), this is because we don’t expect large changes in temperature. Not having the information of the ambient temperature, it is hypothesized that this is fixed: Tc = 20 °C, so v = 343.85. In this case the percentage error on speed is visible in the following table:

T [°C]

In our case, making a measurement, in summer, at 35°C, we have an error of almost 10 cm at full scale (400). Measurements more accurate require a temperature sensor to correct the speed.
Even the air humidity and the pressure modifying the speed of sound: from 50% to 80% relative humidity it has a speed increase of about 1.1% to 101,325 kP atmospheric pressure. The figure 2 shows the variation of speed with relative humidity at various ambient temperatures in Celsius degrees. You may notice that the humidity influence is most evident at high temperatures, as could be expected.

Figure 2 - Speed of sound in air

All the considerations previously views lead to say that the distance measurements based on the detection of the time of flight (TOF) with ultrasound have an accuracy around the centimeter, if corrected with the ambient temperature.
Recent techniques are based on measurement of the phase between continuous wave transmitted and received (Binary Frequency Shift Keyed-or BFSK). With these techniques, using an FSK modulation with frequencies of 40 and 41 kHz, we can achieve  an accuracy of the distance measurement below the millimeter. This greater accuracy is paid with a considerable complexity of electronic circuits and a higher energy consumption, because we have to generate a continuous wave. An alternative is to use a laser rangefinder.

The HC-SR04 sensor

Figure 3 - The HC-SR04 module.
This sensor, which typical aspect is seen in Figure 3, is simple and economical. It has only four pins:

+5v Power supply input
trigger (TTL input)
Measurement (TTL output)
Common ground

The module has a microcontroller that, when the trigger pulse is received (10μs min), send a burst of 8 pulses at 40 kHz. A MAX232 is used as driver for the Tx transducer in order to elevate the driving voltage to approximately +/- 10V. The return echo, received by the Rx transducer, is amplified by an LM324 and processed by the microcontroller that generates an output pulse which duration Dt is proportional to the target distance. It corresponds to the time that elapses between the emission of the burst and the instant at which it receives the echo, also called TOF. The timing diagram shows the sequences described.
Figure 4 -Timing diagram.
It follows that the distance Dt will be proportional to the length of the output pulse according to the expression:
The period Dt must be divided by two because it includes the time for the reflected wave return. This applies to the sonar, echo sounders and radars, which use the propagation time to detect distances.
In our case, expressing d in [cm] and Dt in [µS], we get:
d =  ΔT / 58.165 [cm]
The measurement range of this sensor is from a minimum of 2 cm to a maximum of 400, measured in microseconds the Dt, these limits correspond to 116 µs (2cm) and 23266 µs (400cm). With a system like Arduino it is very easy to measure these times because there is a specific and powerful function.

Teensy (or Arduino) interface and program

Four wires are required for the connection to Teensy, as shown in figure 4. Changing only the signal pins, any Arduino board or compatible can be used for this application, I used a rev.3.1 Teensy interfaced with a LCD display. The figure 5 shows the wiring diagram for my board.
Figure 5. - Wiring diagram for Teensy board.
As shown, the pin 22 of Teensy is connected to the Trigger and pin 23 to Echo.
The code does not require much effort, I add the definitions:

#define Trigger 22 // Trigger Pin
#define Echo 23 // Echo Pin
long duration, distance;

In the main loop it creates the trigger pulse and then uses the pulseIn for Echo pulse duration:

digitalWrite(Trigger, HIGH);
digitalWrite(Trigger, LOW);
duration = pulseIn(Echo, HIGH);
distance = duration/58.165;
A good choice for pulseIn is to use a third parameter:
pulseIn(pin, value, timeout)
As default timeout = 1e6 microseconds, in our case, we might ask timeout = 23266, corresponding to 400cm away. The function returns zero if timeout, or over range.
In the remaining of the program there are instructions for printing on the LCD display the distance measurement.
It would be advisable to check the distances with calibration measurements: placing the sensor at known distances from a flat wall, taking care to position the transducer axis perpendicular to the wall. With three or four measures you can make a good calibration.
As described earlier, a significant improvement of the system is to measure also the temperature. There are several temperature sensors for Arduino; some have the analog output, as the LM35 which has a linear output with a scale factor of approximately 10 mV/°C. Since Arduino has a 10-bit ADC, with full scale of 5 V it would be possible to obtain a resolution of approximately 0.5 °C, more than good for the compensation of the temperature using the formula (1). A more economic system, which requires a better calibration, is to use a thermistor, i.e. a resistor that varies its resistance with temperature. In the web there are many applications of this type.

1.      “HC-SR04 User's_Manual”, Cytron Technologies, May 2013.
2.      “Speed of sound”,
3.      “A high accuracy ultrasonic distance measurement system using binary frequency shift-keyed signal and phase detection”, S. S. Huang, C. F. Huang, K. N. Huang and M. S. Young, REVIEW OF SCIENTIFIC INSTRUMENTS VOLUME 73, NUMBER 10 OCTOBER 2002.

4.       “LM35, Precision Centigrade Temperature Sensors”, National Semiconductor, November 2000