Friday, 30 September 2016

An isolated analog output for Arduino Uno

This project uses the Arduino PWM Uno or other systems to realize a fully isolated analog output with a range of 0-5 volts or more, changing only the reference voltage.

This project completes the series of my articles about the Arduino analog I/O with the aim to use it as a controller of small automation systems.
In control systems of the industrial plants it is always advisable to isolate both the inputs and the outputs coming from the field. This prevents disturbances caused by power surges, lightning strikes or other EMI sources and also by ground potential differences.
Arduino Uno, or systems based on the ATmega328 chip has no a true analog output, but it may be realized using a PWM output averaged with a low-pass filter.
The use of an averaged PWM signal with 8-bit setting is not comparable with a real DAC, but in the insulation case presents undoubted advantages of simplicity since it is sufficient to use an optocoupler for isolating the PWM digital signal. Recently I designed another circuit to generate a 4-20 mA current with Arduino, that experience gave me the idea for this new project.

The Arduino PWM
Arduino Uno has several pins (3, 5, 6, 9, 10, and 11) that can be configured for PWM output. For this project I used pin 9 because the others were used by various devices (LCD, SD and RTC) in my Arduino system.
The PWM signal on pins D9 and D10 is generated by Timer# 1 of ATmega328. It has a prescaler which divides by 1, 8, 64, 256, 1024, controlled by the three least significant bits of the register TCCR1B. The default value of the prescaler set by the Arduino IDE is equal to Np= 64 (TCCR1B, bits 2-0= 110), which provides an output frequency:

PWM frequency = CPUClock/(2´Np´TOP) = 16000000/(2´64´255)= 490.196 Hz

Where the TOP value is he maximum Timer/Counter value.
The following table shows the frequencies generated by Timer# 1 of an Arduino Uno (Atmega 328) on pins 9 and 10,  with a 16 MHz clock and in “phase­correct PWM” mode. In this mode, the timer counts from 0 to 255 and then back down to 0. 

Prescaler divider (Np)
Prescaler code
PWM frequency

The prescaler code must be put in the three least significant bits of the register TCCR1B – Timer/Counter1 Control Register B. For example, to generate a PWM of 3921 Hz, the following instruction must be inserted in the setup function:

TCCR1B = TCCR1B & B11111000 | B00000010;// set timer 1 prescaler to 8

Using a common optocoupler with a phototransistor, as 4N25, the frequency is limited because of the high transition times, so I used a faster optocoupler with photodiode and with an open collector output, such as the 6N136.
To eliminate the output noise I utilized a second order active low-pass filter, Sallen-key type, with a cut-off frequency of about 11.2 Hz. The isolation is achieved with an optocoupler, of course you must use for this circuit a power supply different from the one used for Arduino. If the insulation is not required, things become even simpler and connect the filter to the PWM output, in this case not even need the reference source U2.

The circuit diagram, shown in Figure 1, is quite simple. I recommend using for U1 a double operational amplifier suitable for single-rail power supply, such as LM358. 
The LM358 chip must be powered with a voltage higher than 7 V (and lower than 32) to have in output a maximum voltage of 5V and also the regulator has a 2 V dropout.
The advantage of the open collector of the optocoupler is that you can easily obtain a different output range, for example, using a 10V reference voltage and R2=10 kohm the output range became 0-10V. In this case the LM78L05 must be replaced with a LM317 with an appropriate circuitry.
In figure 2 you can see the arrangement of the components of my prototype.

Hardware components
1x Arduino board,
Components list
R1= 330 ohm ±5%
R2= 5.1 kohm ±5%
R3= 100kohm ±5%
R4= 100 kohm ±1% metal film
C1= 100nF ceramic
C2 = 10 MF,50V Electrolytic
C3= 200 nF Mylar ±2%
C4 = 100 nF Mylar ±2%

U1= LM358 dual op amp
U2= LM78L05 regulator
OPT1= 6N136
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 200nF and C4 have selected a value half of C3. 

The test on the circuit
The Figure 3 shows the results of the linear regression on the 14 measurements points made on my prototype. The test conditions are:
·        PWM frequency = 490.196 Hz;
·        Vin = 12V;
·        Vref = 5.00 V
The standard error is about 6.1 mV, so the results are very good at the default PWM frequency.

I also tested the system with a frequency of 3921.569 Hz, but with a standard error of 39 mV. The largest errors are found for high duty cycle values, in this area the pulses are narrow and the rise time is high and this phenomenon creates non-linearity. The period is: T = 1/3921.569 = 255 µs. The more narrow pulse has a duration of about 1 µs, approximately the same value as the rise time of the pulses, the cause of non-linearity is due just to this phenomenon. Using the default frequency of 490.196 Hz, the minimum pulse has a duration eight times larger, so it greatly improves the linearity.

The program list
To test the system I used an Arduino Uno with a LCD display and the analog input A0 connected to a potentiometer to vary the duty cycle of the PWM.

// program to test Arduino Uno PWM at 3.9 kHz
// G. Carrera 30 sett 2016

#include <LiquidCrystal.h>

int PWMpin = 9;      // PWM out on digital pin 9
int analogPin = 0;   // potentiometer connected to A0
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");// Print a message to the LCD
  // set timer 1 prescaler to 8 for PWM frequency of 3921.57 Hz
  //TCCR1B = TCCR1B & B11111000 | B00000010;

void loop() {
  val = analogRead(analogPin) >> 2;// read the potentiometer as 8 bit

  analogWrite(PWMpin, val);
  val = 255-val;// complement
  lcd.setCursor(0, 1);
  lcd.setCursor(0, 1);

1.      “Secrets of Arduino PWM”, Ken Shirriff,
2.      “Atmel 8-bit Microcontroller with 4/8/16/32KBytes In-System Programmable Flash”, 8271G–AVR–02/2013

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.