Voltage Measurements Using the Arduino

I often need to make voltage measurements using my arduino.  I recently built a voltage, current and temperature data logger for testing lithium batteries and I needed to be able to measure 50 Vdc safely into the Arduino although any ADC input from a microcontroller could be substituted.

Rather than reinvent the wheel I decided (possibly foolishly) to use a voltage measurement breakout board:

I bought mine from Hobby Components but they can be obtained everywhere:

To be fair I didn’t really look into the module properly as I was in a rush.  The circuit itself is a simple 5:1 voltage divider and a screw terminal and some header pins.  For the price of £1.99 I shouldn’t complain.  The circuit is below for those that are interested.

Not sure why they added the Banana connector footprint…but hey ho, Or why they used a 3 pin connector on the output…as one of the pins does nothing at all…

The circuit is a 5:1 voltage divider.  So a person using this circuit can measure voltage signals ranging from 0 volts to 25 volts.  If you were to change the resistor values you can then change the voltage measurement range.

Here is some simple code to get this to work with an arduino with the measurement output connected to A0 on the arduino:

/*
DC Voltmeter Using a Voltage Divider
*/

int analogInput = A0;  // Read the voltage from the divider on A0 
float vout = 0.0;      // variable for the calculated voltage 
float vin = 0.0;       // variable for the resulting voltage
float R1 = 30000.0;    // variable to store the value of R1  
float R2 = 7500.0;     // variable to store the value of R2
int raw = 0;           // variable to store the raw ADC measurement

void setup(){
   pinMode(analogInput, INPUT);  // set pin A0 to be an input
   
   Serial.begin(9600);           // start the serial monitor
   Serial.print(“DC VOLTMETER”); // display a welcome message
}
void loop(){
   
   // read the value at analog input A0
   // calculate the voltage from the raw adc value
   // account for the voltage divider
   // Display the result

   raw = analogRead(analogInput);
   vout = (value * 5.0) / 1023.0; 
   vin = vout / (R2/(R1+R2)); 
   
   Serial.print(“INPUT V= “);
   Serial.println(vin,2);
   delay(500);
}

I tested the above code and it works perfectly well and this board can be used to make voltage measurements.  My concerns with it are that it has no protection against a person trying to measure too much voltage or a signal to high in current.  With the above breakout board an over voltage or over current event will damage the ADC input of the arduino.  The maximum current an Atmel 328p pin can accept according to the datasheet is 20 mA.  

If we apply more than 25 Volts to input of the voltage divider the instantaneous current presented to the A0 input pin could be more than 20 mA and if the voltage is really high it will give us an incorrect reading.  It would be better if we protected the ADC input from over-voltage and current events and then ensure our circuit and our micro-controller ADC inputs work perfectly in any condition, fault or normal.

To protect against over current events we need to add a series resistor.  I’m choosing to add a 22 ohm resistor in series.  This prevents the current being presented to the ADC input every becoming greater than 20 mA even if 2500 volts are applied (by mistake) to the voltage divider input.

Next we are going to add a low value capacitor (100 pF).  This takes some of energy out a high voltage transient (pulse) like an electrostatic discharge and also provide a small amount of filtering to the circuit.

Finally lets ensure that the voltage applied to the ADC input of the microcontroller is always about 5 volts.  This is achieved by adding some clamping diodes.  These are simple signal diodes – 1N4148 diodes will do…Here is the final circuit.

Just to prove the function of the circuit and what achieves for us lets simulate the different error conditions to show what happens.  I’m going to show pictures rather than a full video.

Lets set some parameters.  Lets assume by mistake someone tries to measure a voltage and by mistake they apply 2500 Vdc…This is what gets applied to the ADC input of the arduino.  It might not destroy it but it would certainly damage the microcontroller…

Lets add the current limiting 22 Ohm series resistor, which doesn’t affect the measurement but reduces the current presented to the load (the ADC input pin).

Lets now add the capacitor to the circuit.

Finally lets add the clamping diodes…which incidentally have the most effect!

What the simulation clearly shows is that if by mistake 2500 volts was applied to the voltage divider with the clamp diodes, series resistor and capacitor only 6.37 volts and 637 nA will be applied to the ADC input.  The voltage divider will still work as intended though and nothing will be damaged on the microcontroller – good things all round.

The point I’m getting at is that if a voltage divider circuit is used to measure voltages on an arduino or any other microcontroller then without the above components to provide protection bad things may happen.  This is why the 25 Volt measurement breakout boards are not the best circuit.  It would not cost much more to apply the protection components.

Well that’s all for now people – Enjoy and hope this post was helpful.  I might make a few voltage sensor breakout boards for sale if demand is high enough – I know I’ll need some from time to time.

Cheers – Langster!

Voltage Measurements Using the Arduino

I often need to make voltage measurements using my arduino.  I recently built a voltage, current and temperature data logger for testing lithium batteries and I needed to be able to measure 50 Vdc safely into the Arduino although any ADC input from a microcontroller could be substituted.

Rather than reinvent the wheel I decided (possibly foolishly) to use a voltage measurement breakout board:

I bought mine from Hobby Components but they can be obtained everywhere:

To be fair I didn’t really look into the module properly as I was in a rush.  The circuit itself is a simple 5:1 voltage divider and a screw terminal and some header pins.  For the price of £1.99 I shouldn’t complain.  The circuit is below for those that are interested.

Not sure why they added the Banana connector footprint…but hey ho, Or why they used a 3 pin connector on the output…as one of the pins does nothing at all…

The circuit is a 5:1 voltage divider.  So a person using this circuit can measure voltage signals ranging from 0 volts to 25 volts.  If you were to change the resistor values you can then change the voltage measurement range.

Here is some simple code to get this to work with an arduino with the measurement output connected to A0 on the arduino:

/*
DC Voltmeter Using a Voltage Divider
*/

int analogInput = A0;  // Read the voltage from the divider on A0 
float vout = 0.0;      // variable for the calculated voltage 
float vin = 0.0;       // variable for the resulting voltage
float R1 = 30000.0;    // variable to store the value of R1  
float R2 = 7500.0;     // variable to store the value of R2
int raw = 0;           // variable to store the raw ADC measurement

void setup(){
   pinMode(analogInput, INPUT);  // set pin A0 to be an input
   
   Serial.begin(9600);           // start the serial monitor
   Serial.print(“DC VOLTMETER”); // display a welcome message
}
void loop(){
   
   // read the value at analog input A0
   // calculate the voltage from the raw adc value
   // account for the voltage divider
   // Display the result

   raw = analogRead(analogInput);
   vout = (value * 5.0) / 1023.0; 
   vin = vout / (R2/(R1+R2)); 
   
   Serial.print(“INPUT V= “);
   Serial.println(vin,2);
   delay(500);
}

I tested the above code and it works perfectly well and this board can be used to make voltage measurements.  My concerns with it are that it has no protection against a person trying to measure too much voltage or a signal to high in current.  With the above breakout board an over voltage or over current event will damage the ADC input of the arduino.  The maximum current an Atmel 328p pin can accept according to the datasheet is 20 mA.  

If we apply more than 25 Volts to input of the voltage divider the instantaneous current presented to the A0 input pin could be more than 20 mA and if the voltage is really high it will give us an incorrect reading.  It would be better if we protected the ADC input from over-voltage and current events and then ensure our circuit and our micro-controller ADC inputs work perfectly in any condition, fault or normal.

To protect against over current events we need to add a series resistor.  I’m choosing to add a 22 ohm resistor in series.  This prevents the current being presented to the ADC input every becoming greater than 20 mA even if 2500 volts are applied (by mistake) to the voltage divider input.

Next we are going to add a low value capacitor (100 pF).  This takes some of energy out a high voltage transient (pulse) like an electrostatic discharge and also provide a small amount of filtering to the circuit.

Finally lets ensure that the voltage applied to the ADC input of the microcontroller is always about 5 volts.  This is achieved by adding some clamping diodes.  These are simple signal diodes – 1N4148 diodes will do…Here is the final circuit.

Just to prove the function of the circuit and what achieves for us lets simulate the different error conditions to show what happens.  I’m going to show pictures rather than a full video.

Lets set some parameters.  Lets assume by mistake someone tries to measure a voltage and by mistake they apply 2500 Vdc…This is what gets applied to the ADC input of the arduino.  It might not destroy it but it would certainly damage the microcontroller…

Lets add the current limiting 22 Ohm series resistor, which doesn’t affect the measurement but reduces the current presented to the load (the ADC input pin).

Lets now add the capacitor to the circuit.

Finally lets add the clamping diodes…which incidentally have the most effect!

What the simulation clearly shows is that if by mistake 2500 volts was applied to the voltage divider with the clamp diodes, series resistor and capacitor only 6.37 volts and 637 nA will be applied to the ADC input.  The voltage divider will still work as intended though and nothing will be damaged on the microcontroller – good things all round.

The point I’m getting at is that if a voltage divider circuit is used to measure voltages on an arduino or any other microcontroller then without the above components to provide protection bad things may happen.  This is why the 25 Volt measurement breakout boards are not the best circuit.  It would not cost much more to apply the protection components.

Well that’s all for now people – Enjoy and hope this post was helpful.  I might make a few voltage sensor breakout boards for sale if demand is high enough – I know I’ll need some from time to time.

Cheers – Langster!

Voltage Measurements Using the Arduino

I often need to make voltage measurements using my arduino.  I recently built a voltage, current and temperature data logger for testing lithium batteries and I needed to be able to measure 50 Vdc safely into the Arduino although any ADC input from a microcontroller could be substituted.

Rather than reinvent the wheel I decided (possibly foolishly) to use a voltage measurement breakout board:

I bought mine from Hobby Components but they can be obtained everywhere:

To be fair I didn’t really look into the module properly as I was in a rush.  The circuit itself is a simple 5:1 voltage divider and a screw terminal and some header pins.  For the price of £1.99 I shouldn’t complain.  The circuit is below for those that are interested.

Not sure why they added the Banana connector footprint…but hey ho, Or why they used a 3 pin connector on the output…as one of the pins does nothing at all…

The circuit is a 5:1 voltage divider.  So a person using this circuit can measure voltage signals ranging from 0 volts to 25 volts.  If you were to change the resistor values you can then change the voltage measurement range.

Here is some simple code to get this to work with an arduino with the measurement output connected to A0 on the arduino:

/*
DC Voltmeter Using a Voltage Divider
*/

int analogInput = A0;  // Read the voltage from the divider on A0 
float vout = 0.0;      // variable for the calculated voltage 
float vin = 0.0;       // variable for the resulting voltage
float R1 = 30000.0;    // variable to store the value of R1  
float R2 = 7500.0;     // variable to store the value of R2
int raw = 0;           // variable to store the raw ADC measurement

void setup(){
   pinMode(analogInput, INPUT);  // set pin A0 to be an input
   
   Serial.begin(9600);           // start the serial monitor
   Serial.print(“DC VOLTMETER”); // display a welcome message
}
void loop(){
   
   // read the value at analog input A0
   // calculate the voltage from the raw adc value
   // account for the voltage divider
   // Display the result

   raw = analogRead(analogInput);
   vout = (value * 5.0) / 1023.0; 
   vin = vout / (R2/(R1+R2)); 
   
   Serial.print(“INPUT V= “);
   Serial.println(vin,2);
   delay(500);
}

I tested the above code and it works perfectly well and this board can be used to make voltage measurements.  My concerns with it are that it has no protection against a person trying to measure too much voltage or a signal too high in current.  With the above breakout board an over voltage or over current event will damage the ADC input of the arduino or microcontroller being used.  The maximum current an Atmel 328p pin can accept according to the datasheet is 20 mA.  

If we apply more than 25 Volts to input of the voltage divider the instantaneous current presented to the A0 input pin could be more than 20 mA and if the voltage is really high it will give us an incorrect reading.  It would be better if we protected the ADC input from over-voltage and current events and then ensure our circuit and our micro-controller ADC inputs work perfectly in any condition, fault or normal.

To protect against over current events we need to add a series resistor.  I’m choosing to add a 22 ohm resistor in series.  This prevents the current being presented to the ADC input ever becoming greater than 20 mA even if 2500 volts are applied (by mistake) to the voltage divider input.

Next we are going to add a low value capacitor (100 pF).  This takes some of energy out a high voltage transient (pulse) like an electrostatic discharge and also provide a small amount of filtering to the circuit.

Finally lets ensure that the voltage applied to the ADC input of the microcontroller is always about 5 volts.  This is achieved by adding some clamping diodes.  These are simple signal diodes – 1N4148 diodes will do…Here is the final circuit.

Just to prove the function of the circuit and what achieves for us lets simulate the different error conditions to show what happens.  I’m going to show pictures rather than a full video.

Lets set some parameters.  Lets assume by mistake someone tries to measure a voltage and by mistake they apply 2500 Vdc…This is what gets applied to the ADC input of the arduino.  It might not destroy it but it would certainly damage the microcontroller…

Lets add the current limiting 22 Ohm series resistor, which doesn’t affect the measurement but reduces the current presented to the load (the ADC input pin).

Lets now add the capacitor to the circuit.

Finally lets add the clamping diodes…which incidentally have the most effect!

What the simulation clearly shows is that if by mistake 2500 volts was applied to the voltage divider with the clamp diodes, series resistor and capacitor only 6.37 volts and 637 nA will be applied to the ADC input.  The voltage divider will still work as intended though and nothing will be damaged on the microcontroller – good things all round.

The point I’m getting at is that if a voltage divider circuit is used to measure voltages on an arduino or any other microcontroller then without the above components to provide protection bad things may happen.  This is why the 25 Volt measurement breakout boards are not the best circuit.  It would not cost much more to apply the protection components.

Well that’s all for now people – Enjoy and hope this post was helpful.  I might make a few voltage sensor breakout boards for sale if demand is high enough – I know I’ll need some from time to time.

Cheers – Langster!

Pressure Sensor Breakout Board – MPS20N0040D-D

I was checking the statistics of how many people read my blog and which pages are the most popular. I am always surprised and often humbled by how many people read my stuff – please keep reading and commenting and let me know if there is something specific I need to cover.  Anyway I noticed that one of my most popular posts concerned the usage of a cheap pressure sensor – the MPS20N0040D-D.  A lot of readers have commented and contacted me on getting this sensor up and running – I’m not surprised, its hard to do!

To try to make things more simple I’ve decided to design a small breakout board which should make things easier – If people are interested I will get a load manufactured, built and tested and that way all that’s needed is to connect the breakout board up to the microcontroller or ADC of choice and get on with using the sensor.

The original pressure sensor post

So referencing the previous post the sensor is essentially a 5 kOhm Wheatstone bridge sensor which measures pressure.  In order to get it to work a difference amplifier with some gain is required. To get the sensor to work well in any given situation I’m going to add some filtering to ensure that the sensor works properly as much as possible even if there is electrical noise present – it’s always a good idea to do that.

Here is the breakout board circuit:

I’ve already discussed the circuit function in the other post about the pressure sensor so I’m not going to go into great detail.

The left part of the schematic is the pressure sensor itself which is connected to a filter stage.  The filter stage contains ferrite beads which are special soft iron components designed to remove high frequency electronic noise.  The rest of the filter circuit is made up of standard RC filters to remove any other unwanted noise.

Wikipedia entry on Ferrite beads

The next part of the circuit is the difference amplifier made up on a ‘Jelly bean’ Op-Amp the LMV385 and some resistors.  The circuit amplifies the difference measured between pins 2 and 3 and passes the output to another gain stage which amplifies it further.  The output is then passed to a 3 pin connector which will be used to connect the breakout board to a breadboard before connecting this on to a microcontroller or ADC.

LMV358 datasheet.pdf

The important part of this design is going to be the PCB layout.  We need to ensure that the circuit is constructed and designed as robustly and efficiently as possible.  Because it is a breakout board it needs to be of a small form factor but we also want the circuit to be noise immune and still function as intended.  This isn’t always easy – lets set some parameters and see if they are achievable:

  • PCB dimensions – less than 25 x 25 mm
  • Use a complete ground plane on one layer
  • Ensure the external connections are accessible
  • Minimize track length as much as possible
  • Utilize surface mount components (0805)
The layout took me about an hour and a half!  I don’t think it came out too badly.  There was a great deal of moving components and tracks about.  It was completely routed by hand – I don’t agree with using an auto-router.  The results are always poor (in my opinion).

Top Layer of Pressure Sensor Breakout
Bottom Layer of Pressure Sensor Breakout
The combined layers with dimensions

I managed to get it all into a tight space – less than 22 mm is fair I feel.  The electronics is all on the top side and the pressure sensor is on the bottom side.  When in use the top side will be facing downwards but that is no hardship. I used a design rule checking file from a board manufacturing house to check that the design is viable and they can make it – It passed with no errors!  I must be getting better at this…

Just for fun and because I have found it lets me know if mechanically the design won’t work – here is the PCB rendered in 3D.

The rendered PCB top layer

The rendered PCB viewed isometrically

For those that are interested here is the parts list for this breakout board:

It’s a bit annoying that the minimum order quantity for surface mount resistors are sometimes in the hundreds…I never seem to need that many – hey ho.  The cost of 10 uF 0805 capacitors is extortion in my opinion!  The total component cost is £3.15 to populate a single PCB.  The problem is because of the minimum order quantity (MOQ) it would cost £7.28 to obtain all of the components and there will be some left over (moan…grumble…whinge)

No matter – Lets get some quotes for the cost of constructing the PCB.  I use Elecrow in China to make my PCBS but there are plenty of places you can get this service.

http://www.elecrow.com/

The quoted cost for manufacture from Elecrow was £9.70 for ten PCBS so that brings the cost for one complete breakout board to £4.12 – this doesn’t take into account design or manufacture or testing…If we were to include all of that it pushes the price up considerably.

– UPDATE – 25-09-2015

The boards arrived from Elecrow in record time and I’ve built one up.  Guess what…there were some mistakes.  The land pattern for the sensor I used was incorrect – I had to bend the pins a little to get it to fit.  I also made a mistake with the OP-amp configuration.  Pins 5 and 6 need to be reversed in order for the circuit to work as intended.  I now have 8 PCBS which will need to be modified in order to get them to work.  No matter – I’ll update the design to ensure the correct connections and footprints are used.  I also want to increase the footprint for the 0805 parts as it was difficult to hand solder the boards.  The silk screen was absolutely useless!  I must have set the font size too low.  It didn’t take too long to populate the board so I’m pleased overall (read massively proud of myself!)

Here are some pictures of the completed board:

The underside of the board with the Sensor
The topside of the board with the components…and mistakes – hey ho!

I have setup an online store here selling this breakout board and some of my other designs –

Lang Electronics Design – Online Store

I will probably do a post using the breakout board soon as I can now make more use of the sensors.

That’s all for now, take care – Langster

Driving the VGA Port Using the Elbert V2 and Mimas V2 FPGA Development Boards

I haven’t done anything with an FPGA development board for some time.  My excuse is that I’m too busy doing other things!

Let’s use the FPGA development boards to drive a monitor via the VGA port on on the board.  VGA stands for Video Graphics Array.  VGA is basically a method of driving a computer monitor at a resolution of 640 x 480 pixels with either 16 or 256 colours.  The port itself is a 15 pin connector known as a D-type connector.

Wikipedia VGA entry

VGA Connector

On the Elbert V2 FGPA development board the VGA connector is at the top edge of the board in the middle:

On the Mimas V2 FGPA development board the VGA connector is also at the top of the board in the middle:

To use the board just connect a suitable colour monitor to the connector via the integral lead and turn on the Monitor.  
There is a demonstration file available to test all of the functions available on the Elbert V2 FGPA development board.  It is available from the link below.  Download it, extract it and ensure that the board is working correctly before continuing.  In order to save time we are going re-use some of the code available and I have found that it isn’t possible to write the code from scratch
So how does VGA work?  When first implemented most computer displays used cathode ray tubes to drawing a pixel on the phosphor screen.  The image is made up of multiple ‘pixels’ by drawing a single pixel on the screen at a time faster than the human eye can perceive.  The constant drawing of pixels was known as a beam.  The entire image displayed is known as a frame and the speed at which a frame is displayed is known as the frame rate.      
The position of the pixel is controlled by two signals known as H-Sync and V-Sync.  H-Sync is for the horizontal co-ordinate and V-Sync is for the vertical co-ordinate.
H-sync is a signal pulse which occurs every 31.77 µs and moves the position of the pixel to the left of the display.  The pulse is 3.77 µs long and the pulse is negative in polarity at TTL voltage levels moving from +5 volts to 0 volts.  Once the beam is at the left of the current line it moves to the right of the display.  The H-sync marks the start and stop of each line in the frame.  A 0.94 µs delay is introduced and then the H-sync pulse going low for 3.77 µs.  Another delay is introduced for 1.89 µs.  The 0.94 µs delay is known as the “Front Porch”, the 1.89 µs delay is known as the “Back Porch” *  The line of pixels is then drawn on the screen and this takes 25.17 µs.  A whole line is therefore displayed in 31.77 µs (0.94 µs + 3.77 µs + 25.17 µs + 1.89 µs = 31.77 µs).    

V-Sync is actually a signal pulse which moves the position of the pixel to the top of the display. The signal is pulsed every 16.78 ms or 0.01678 seconds which is known as the refresh rate.  The refresh rate is normally quoted as 60 Hz (1 / 16.78 ms = 59.6 Hz which rounded up is 60 Hz).

Driving the VGA Port Using the Elbert V2 and Mimas V2 FPGA Development Boards

I haven’t done anything with an FPGA development board for some time.  My excuse is that I’m too busy doing other things!

Let’s use the FPGA development boards to drive a monitor via the VGA port on on the board.  VGA stands for Video Graphics Array.  VGA is basically a method of driving a computer monitor at a resolution of 640 x 480 pixels with either 16 or 256 colours.  The port itself is a 15 pin connector known as a D-type connector.

Wikipedia VGA entry

VGA Connector

On the Elbert V2 FGPA development board the VGA connector is at the top edge of the board in the middle:

On the Mimas V2 FGPA development board the VGA connector is also at the top of the board in the middle:

To use the board just connect a suitable colour monitor to the connector via the integral lead and turn on the Monitor.  
There is a demonstration file available to test all of the functions available on the Elbert V2 FGPA development board.  It is available from the link below.  Download it, extract it and ensure that the board is working correctly before continuing.  In order to save time we are going re-use some of the code available and I have found that it isn’t possible to write the code from scratch
So how does VGA work?  When first implemented most computer displays used cathode ray tubes to drawing a pixel on the phosphor screen.  The image is made up of multiple ‘pixels’ by drawing a single pixel on the screen at a time faster than the human eye can perceive.  The constant drawing of pixels was known as a beam.  The entire image displayed is known as a frame and the speed at which a frame is displayed is known as the frame rate.      
The position of the pixel is controlled by two signals known as H-Sync and V-Sync.  H-Sync is for the horizontal co-ordinate and V-Sync is for the vertical co-ordinate.
H-sync is a signal pulse which occurs every 31.77 µs and moves the position of the pixel to the left of the display.  The pulse is 3.77 µs long and the pulse is negative in polarity at TTL voltage levels moving from +5 volts to 0 volts.  Once the beam is at the left of the current line it moves to the right of the display.  The H-sync marks the start and stop of each line in the frame.  A 0.94 µs delay is introduced and then the H-sync pulse going low for 3.77 µs.  Another delay is introduced for 1.89 µs.  The 0.94 µs delay is known as the “Front Porch”, the 1.89 µs delay is known as the “Back Porch” *  The line of pixels is then drawn on the screen and this takes 25.17 µs.  A whole line is therefore displayed in 31.77 µs (0.94 µs + 3.77 µs + 25.17 µs + 1.89 µs = 31.77 µs).    

V-Sync is actually a signal pulse which moves the position of the pixel to the top of the display. The signal is pulsed every 16.78 ms or 0.01678 seconds which is known as the refresh rate.  The refresh rate is normally quoted as 60 Hz (1 / 16.78 ms = 59.6 Hz which rounded up is 60 Hz).

How to use an ACS712 breakout board to measure current

One of my good friends and colleagues is a little busy at the moment…actually he is always busy!  He asked me to design and develop some instrumentation using the arduino Due development board. The requirements of the device are:

  • Measure electrical current from 0 to 5 Amps with at least 1 mA resolution with at least 0.1% accuracy.
  • Measure voltage from 0 Volts to 500 Volts with 1 mV resolution with at least 0.1% accuracy
  • Measure temperature from 0 °C to 200 °C with 0.5 °C resolution with at least 0.1% accuracy.
  • Log the data to a microSD card.
  • Display the measurements in real time on an LCD display.
  • Communicate using wifi to an external computer.
This is all fairly easy to achieve particularly as there are now plenty of modules and shields available to perform most of these functions.  For the wireless communications I’m going to use an ESP2866 wifi module.  I could also use a module for the microSD card but I might realise my own circuit as part of the printed circuit board that I intend to design.  The hardest part of the circuit to implement (in my opinion) is the analogue instrumentation.  The resolution requested is quite fine and the accuracy may be difficult to achieve.  
Let’s discuss the current measurement section first.  We need a way of sensing electrical current flow in an external circuit that we attach to our data logger.  The sensing circuit shouldn’t interfere with the thing we are trying to measure and should be as low power but accurate as possible.  The classic way to measure electrical current is to force the electrical current to pass through a known value resistor and then measure the voltage across that resistor and then using Ohm’s law calculate the current. This is a very accurate and proven method.  The issues with it is that the circuit we are measuring is ‘loaded’ by the measurement or ‘shunt’ resistor which affects the external circuit slightly.  The shunt resistor needs to be a precision part which is unaffected by temperature.  That makes the ‘shunt’ resistor expensive.  Here is a simple shunt resistor current measurement circuit:

The circuit uses a ‘difference amplifier’ to measure the voltage developed across the shunt resistor. This voltage is then amplified and passed to an analogue to digital converter with is then in turn connected to a micro-controller and processed as required.  The circuit above provides a gain of 2. The issues with the above circuit is that the resistors must be their precise stated value and must not differ with temperature.  Any slight fluctuation in the supply voltage to the op amp or noise at the ground terminal will cause the measurement to be incorrect. 

Most difference amplifiers these days are made with precision resistors.  They can be bought as a single part with the circuit implemented within the silicon. The resistors are typically trimmed during manufacturing so that R2/R1 = R4/R3. The differential gain of the device can be calculated easily:

Av (Gain) = R2/R1 

The reference voltage (Vref) is added to the output voltage (Vo).

I have discussed difference amplifiers in a previous post and if more information is required please see that post – 

Another method of measuring current which is less invasive relies on the ‘Hall Effect’.  The Hall Effect is basically a science trick using some gold leaf and some contacts; when electrical current is passed through gold leaf a voltage appears that is directly proportional to the amount of current flowing.  It is a product of the magnetic field induced around the gold leaf.  It was named for it’s discoverer Edwin Hall in the year 1879 – an American Professor of Physics and very clever bloke!

Wikipedia Entry on the Hall Effect

Luckily I don’t have to fiddle around with bits of glass and gold leaf in order to make Hall effect sensors.  They are now available helpfully pre-made inside integrated circuits.  The most prevalent manufacturer in my experience is Allegro.  For this circuit I’m going to use on of their most popular devices the ACS712.  The device is a 0-5A hall effect device in an SOIC package that works happily on 3.3V and 5V supplies and outputs a small voltage in proportion to the current present on it’s input terminals.  This voltage can then be amplified or passed to an analogue to digital converter or micro-controller and processed and displayed.  The Allegro product page for the sensor is below:

ACS712 Product Page

The device itself can be bought from all good online electronics suppliers on it’s own or in a handy little development module.  I bought mine from hobby components but the module or breakout board can be bought from any of the following vendors:

Amazon Online

Cool Components

Hobby Components – currently on sale at £2.99

All that is needed is to connect it up to your micro controller of choice and prepare to make current measurements!  Here is the schematic for the breakout board:


All that is required is to make the following connections: 

VCC to +5V or +3.3V
GND to 0V
Out to an analogue pin on the micro-controller.
JP1 and JP2 go in series with the load to be measured.

I’m just using this board to prove a concept and check things work.  The circuit I intend to implement is below:

The circuit works by measuring the current using the Hall effect sensor.  The voltage output of the hall effect sensor is passed to an inverting amplifer which provides a gain of 3.1 – the voltage from the current sensor will be multiplied by 3.  This amplified voltage is then passed to a 24 bit analogue to digital converter which then will be connected to the SPI communications pins of the micro-controller.  The result of the measurement can then be displayed or communicated as required.  

I chose to use a 24 bit ADC because the circuit requires very good measurement accuracy. It needs to be able to measure current with mA precision or better if possible. I don’t say this often…lets do some maths!

According to the datasheet for the ACS712 typical provides 185 mV / A which means a voltage of 0.185 V is equivalent to 1 ampere of current flowing in the load.  With the amplification stage we will get 575 mV / A which gives a bit more resolution.  

The analogue to digital converter selected is of the 24 bit variety.  That means it converts the voltage presented at it’s input to 24 figure binary number.  This binary number is then sent to the micro-controller using a device specific communications protocol called serial peripheral interface or SPI.     
A full scale current measurement is equivalent to 1111 1111 1111 1111 1111 1111(b) which in decimal is 16777215.  That means we can measure between 0 Amps and 5 Amps in 298 * 10^-9 steps which is brilliant accuracy.  Lets say 300 * 10^-9 or 300 nano-Amp per division accuracy.

The calculation was as follows:

5 A / 16777215 = 2.9802 e^-7      

If we convert this number to e-9 we get 298.02 e^-7 (move the decimal place to left by two figures) and then round the figure up to a whole number we have 300 e^-9 or 300 nano-Amps per division.

In reality I sincerely doubt this level of accuracy is possible without excellent components, printed circuit board material and component layout.  All of which we will aim to achieve but realistically we will probably achieve 22 bit accuracy.

So lets now repeat the calculation with the more realistic 22 bit accuracy and see what happens:

22 bits = 1111 1111 1111 1111 1111 11(b)

which in decimal is equivalent to 4194303

5 A /  4194303 = 1.19 e^-6 rounded up that is 1.2 e^-6 or 1.2 micro-Amps per division accuracy which is still awesome and almost a thousand times better than the 1 milli-Amp accuracy requested. It’s important to try to improve on specifications where possible particularly when it doesn’t impact cost and design.  

Enough talking, let see the the module working…The circuit I implemented for testing is below:

The circuit above uses a difference amplifier to subtract the 2.5V offset which is inherent in the ACS712 module – I didn’t want the extra 2.5V present so I removed it.  The precision reference is present to ensure a stable measurement is made.  The output of the difference amplifier is then passed to an op-amp configured to provide 4.3 times gain which increases the resolution of the measurement. The output of the op-amp is then passed to the ADC input of an arduino R3 which has an integral 10 bit ADC.  Good enough to test the module.  I also added a 16×2 LCD display but I haven’t shown this on the diagram as I ran out of space on the page…

Here is the code I’m using to test the circuit:

#include <LiquidCrystal.h>

char ch;
int Contrast = 100;
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const int analogIn = A0;
int mVperAmp = 528; // use 100 for 20A Module and 66 for 30A Module
int RawValue = 0;
float ACSoffset = 450;
double Voltage = 0;
double Amps = 0;

// Define the number of samples to keep track of. The higher the number,
// the more the readings will be smoothed, but the slower the output will
// respond to the input. Using a constant rather than a normal variable lets
// use this value to determine the size of the readings array.

const int numReadings = 100;

int readings[numReadings]; // the readings from the analog input
int index = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average

void setup()
{
Serial.begin(9600);
Serial.println("Alex Current Meter Test");

analogWrite(6, Contrast);
// set up the LCD's number of columns and rows:

analogWrite(9, 28836);
// set the backlight of the LCD on

lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("I Meter test!!");

// initialize all the readings to 0:
for (int thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 0;
}

void loop()
{

// subtract the last reading:
total= total - readings[index];
// read from the sensor:
readings[index] = analogRead(analogIn);
// add the reading to the total:
total= total + readings[index];
// advance to the next position in the array:
index = index + 1;

// if we're at the end of the array...
if (index >= numReadings)
// ...wrap around to the beginning:
index = 0;

// calculate the average:
average = total / numReadings;

RawValue = average;

Voltage = (RawValue / 1023.0) * 5000; // convertaveraged raw value to mV
Amps = ((Voltage - ACSoffset)/ mVperAmp);

Serial.print("Raw Value = " ); // shows pre-scaled value
Serial.print(RawValue);
Serial.print("\t mV = "); // shows the voltage measured
Serial.print(Voltage, 3); // Display 3 digits after decimal point
Serial.print("\t Amps = "); // shows the voltage measured
Serial.println(Amps, 3); // Display 3 digits after decimal point
delay(0);

// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the calculated value of current:
lcd.print("Current: ");
lcd.print(Amps, 3);
lcd.print(" ");
 

}

The code is fairly self explanatory, it initialises some variables, the LCD display and the serial communications.  The program then reads in 100 samples from the ADC, averages those values and then converts them from bits to milli-volts and then to Amps accounting for the offset and gain set in the circuit.  The amount of offset may vary between implementations.  Check the value by measuring how much voltage is present at the A0 pin when no current is present (should be around 400 mV)

Here is a video showing the circuit in operation


UPDATE – 01-12-2015

I found that the accuracy of the hall effect sensor was not great so I did some more research and watched some excellent youtube videos by Julian Illett (An excellent engineer)

https://www.youtube.com/watch?v=UF5jrnXvTlM

https://www.youtube.com/watch?v=lisprJs5sNU

https://www.youtube.com/watch?v=etsIFUUhO6I

The last video implemented a capacitor (C2 in the schematic) change from 1 nF to 470 nF.  I changed this on my board and found it had a significant improvement.  I also added some averaging to the code which had a little improvement.

That is all for now – take care, Langster!   

Testing IoT Boat Part One

More than a few years ago, I bought myself a Remote Control boat, a Kyosho Wave Master: The WaveMaster is a semi scale model of an F-1 tunnel hull racing boat. Tunnel hulls work by trapping a cushion of air between the hull and water to reduce friction which allows the boat to travel even […]

Testing IoT Boat Part One

More than a few years ago, I bought myself a Remote Control boat, a Kyosho Wave Master: The WaveMaster is a semi scale model of an F-1 tunnel hull racing boat. Tunnel hulls work by trapping a cushion of air between the hull and water to reduce friction which allows the boat to travel even … Continue reading “Testing IoT Boat Part One”

Testing IoT Boat Part One

More than a few years ago, I bought myself a Remote Control boat, a Kyosho Wave Master: The WaveMaster is a semi scale model of an F-1 tunnel hull racing boat. Tunnel hulls work by trapping a cushion of air between the hull and water to reduce friction which allows the boat to travel even … Continue reading “Testing IoT Boat Part One”