Interfacing a Hall-effect current sensor with an Arduino

Current flow in a system is depends on load characteristics. Due to a faulty condition or controlling scheme, the current flow in the system might be changed. So having knowledge about the current flow in a system is important for both protection and controlling purposes.

There are various methods available for sensing current flow in a system. Usage of shunt resistors, current transformers and usage of Hall-effects sensors are some such available methods. This articles talks about usage of Allegro ACS712 sensor [1] with an Arduino development board for measuring current in a system. Allegro ACS712 sensor operates according to the Hall-effect principal and it can be used for both AC and DC current measurement. There is no need of auxiliary circuits for this sensor it is an immense advantage over the other available methods.

What is Hall Effect principle?

“The Hall-effect is the production of a voltage difference (the Hall voltage) across an electrical conductor, transverse to an electric current in the conductor and a magnetic field perpendicular to the current. It was discovered by Edwin Hall in 1879.”[2]

Allegro ACS712 sensor

This is a bi-directional measuring device and therefore this can be used for both AC and DC current sensing. The ACS712 sensor is designed for three current ranges 5A, 20A and 30A. The sensor consists of an integrated circuit which works according to the Hall-effect principal. This IC generates a voltage proportional to the current flowing in the circuit. Breakout board of current sensors based on this device also available in the market and they make your life easier.

Following graph show the variation of the output voltage with the current flow for 5A sensor [1].

Interfacing with Arduino

Connection configuration

T1 and T2 of the sensor should be connected in series with the current path which is need to sense. Out pin should be need to connect one of the analog input pin available in the Arduino. VCC and GND pins should be connected to 5V and GND pin of the Arduino respectively.


The sensor outputs an analog voltage correspondence to the current flow. Therefore to get the current reading from the Arduino. So we need to perform analog to digital conversion inside the Arduino and multiply with calibrating constant to get the actual value.

We need to use little bit of mathematics for the actual current value calculation. Adruino has 10 bit analog to digital converter register. So ADC value is in range of 0-1023. Then the actual sensor voltage output can be obtained from

OutputSensorVoltage = analogRead(sensorPin)*5.0/1023.0

From the graph and the datasheet,

At zero current, OutputSenosrVoltage = 2.5

Gradient of the graph = 185mV/A (given in datasheet as sensitivity)

So the equation of the graph is

OutputSensorVoltage = 0.185*Current + 2.5

Therefore current can be expressed as

Current = (OutputSensorVoltage – 2.5)/0.185

If the current flows in negative direction, current value will be negative.

Following is an example code which can be used for measuring current using the sensor. It will display the current measurement on serial monitor.




Arduino 6DOF Motion Sensor: The MPU6050 Inertial Measurement Unit

Arduino 6DOF Motion Sensor: The MPU6050 Inertial Measurement Unit

Arduino is an open source electronic prototyping platform build with the single desire to bring the immense power of microcontroller to the general public who wishes to incorporate some level of logic circuitry in their projects.  The most powerful feature of Arduino is its capability to handle various kinds of sensors with minimum or no change of its stock hardware. Plus the community that has grown over the years has made it even easier and faster for anybody to interface sensors with Arduino and do some seriously cool stuff.

Once of such amazing sensor that can be used with Arduino is the MPU-6050 Inertial Measurement Unit. Sounds unfamiliar? It should because it is a bit of an advanced sensor that is mainly used projects concerning orientation and motion. MPU-6050 is the world’s first 6DOF orientation measuring sensor on a chip. Built by the world famous InvenSense, a company specializing in motion sensing equipment.

If you have used motion sensors before or have researched about it then you will know that IMU boards having accelerometer and gyroscopes often are misaligned and needs a lot of pins or analog input channel from the microcontroller/PC. However the MPU6050 only needs 2 pins in most of the cases and 3 pins if you want to use the interrupt feature of Arduino.

If you have read so far you may be wondering what are IMUs, gyroscopes and accelerometers. For sake of keeping this article focused on the MPU6050 I have chosen not to go too much in details about the said topics.

However some important concepts are

1)   Gyroscope measure the rate of change of angular orientation i.e angular velocity with respect to a reference frame. Often MEMS gyro or digital gyros have ratings in dps (degree per second unit). The MPU6050 has ranges between ±250 to ±2000 dps. The more range you select the more the device will be sensitive to the change.

2)   Accelerometers measures rate of change of linear velocity not angular velocity. This is a common mistake made by people when using accelerometers. Accelerometers are used to find the change of liner acceleration the body experiences when a force is applied on it. Often the unit of measurement for this device is in G-force i.e multiple of acceleration due to gravity (g=9.81 m/s2). MPU6050 has user selectable accelerometer range between ±2g, ±4g, ±8g and ±16g.

3)   Accelerometer and Gyroscope when placed in one board then it is called Inertial Measurement Unit.

4)   For being a cheap chip it is quite versatile. It is very accurate, as it contains 16-bits analog to digital conversion hardware for each channel. Therefor it captures the x, y, and z channel at the same time.

You may be thinking many people have done orientation solution using only gyros like ITG-3000 series so why is the accelerometer needed? Why even the DMP is given?

The answer to these questions will require a lot of words which will not be the focus of this article. However the best answer to the above question is that gyroscope readings suffers from an error within a short amount of time. This is called drifting. To solve this problem accelerometer data is needed. Together with these two data we can get 6axis orientation data which will give greater amount of stability and finer control.

The DigitalMotionProcessor or DMP adds to the feature of 9 Axis Motion Fusion by taking data from an external magnetometer to calculate Euler angle and subsequently Quaternions. The key principle of DMP is that it will handle the heavy duty of calculating the Euler angle when all the input variables will be given. What you have got to do this take out the Euler angles from the MPU6050 using your microcontroller via the I2C bus preferably at 400Khz. The faster you read data the more accurate your calculations will be. Hence this chip has solved a major issue with IMUs. Other IMUs needs the processing power of the microcontroller which often take up a large space of already limited RAM of microcontrollers.  This often clogs up the processor and makes it difficult to make time sensitive applications.


IMU are widely used in projects where balancing or motion sensing is needed. For example Quadcopters (Multi Rotor Helicopters or more commonly known as UAVs) use this sensor to stabilize in automode while begin in air. Balancing robots use the orientation data to decide which wheel should get more power and which should get less in order to remain stable without falling down.

In order to use MPU-6050 you will need to buy a break-out board which makes it easy for Arduino to connect with the chip. A picture of such a board is given below


This particular board is called GY-521. It is quite famous and has a big community with a vast array of libraries to run it.

If you have experimented with other Arduino sensors like Parallex Ping Ultrasonic sensor, LDRs etc you will see that there is no analog output from this sensor. This chip communicates with Arduino using I2C or (read as I square C) communication protocol.  I2C bus one of the most common method of communication between varies microcontrollers, sensors etc. Please visit this link:  It is one of the best tutorials teaching the use of I2C with Arduino. I2C is also called Two-Wire or just Wire communication protocol by some chip manufacturing companies.

Don’t worry you don’t need to know too much of this protocol if you want to test the device Arduino has a library called Wire which pretty much takes care of the hard part of I2C. All you need to do is connect the sensor properly.

If you have a GY-521 then you can do the following test. Follow the instruction exactly and you will see get to see the full power of this sensor. Other boards are also compatible but since I have this particular board on hand I have done this experiment with it.



Hook up the sensor with your Arduino board. If you have gone through Nick’s tutorial then the connection scheme will appear easy to you.


The connection scheme is

  • Arduino’s +5V to Vcc of MPU6050
  • Arduino’s GND to GND of MPU6050
  • Arduino’s SCL (AN5 in UNO board) to SCL of MPU6050
  • Arduino’s SDA (AN4 in UNO board) to SCK of MPU6050
  • Arduino’s digital pin 2 (INT0) to INT of MPU6050

Don’t connect anything to AD0, XDA, XCL. AD0 determines the address of this device and XDA and XCL are used for connecting a secondary sensor (magnetometer) with MPU6050 for 9Axis Motion Fusion.

Once the connection is done connect the Arduino to your PC. The GY521 board should power up and the PowerUp LED should be lit as shown in the above figure.  Now go to and from there download their library. Instruction of setting up the library is given in the website.

Once the library for Arduino is set up now comes the part of visualization.  For this you will need the Processing language. You can download Processing for free in from their website. If you haven’t used Processing before you will find it identical to Arduino IDE. Don’t be alarmed, Arduino is based on Processing and for that reason both the IDEs looks alike.

Once Processing is setup and running you will need to install the Toxiclib Library. Go to this link and you should be able to find the required library

The procedure for setting up a Processing Library is same as that of setting up the Arduino library.  Now with the library installed go into the folder which contains “MPU6050_DMP6” folder. There will be another folder called “Processing” with a file called “MPUTeapot.pde”. THIS is the file for Processing just like a file with (.ino) extension is used to mean Arduino sketch.

Now open a new window of Processing and just drag MPUTeapot file into the window. Immediately you will see Arduino style coding.  Keep that window open and go back to Arduino. Now from the Example tab find out the library that you installed from i2Cdevlib. Open the MPU6050_DMP6 sketch.  Don’t just upload it yet, scroll down a few lines and you will see that some line resembling are commented out i.e lines having (//) before it.


If you want to see the graphical representation of the data from MPU6050 then you will need to uncomment/activate some of the lines. If you are feeling lazy just copy paste the following lines after “include <Wire.h>” line







Now verify the sketch and upload it into the Arduino board/ ATMEGA 328P microcontroller.

Now comes the final part (FINALLY!)

You will need to make a small adjustment in the Processing code. If you are using Windows then whenever you connect your Arduino board you will need to select the serial port or COM port to make Arduino talk with your PC. Make a note of which comport your Arduino is connected. In my case my Arduino UNO is connected to COM8. Now in the Processing code look for a line like the following picture


Change “COM6” to match your comport number for instance I changed mine to COM8 from COM6 i.e just change the number and keep other things untouched.

Now press the RUN button and as they say watch the magic.

If all goes well you will see a small window pop up which will have a arrow/ plane like structure. Now if you move the chip you will see that the plane will follow your movement i.e the using DMP you are getting very precise orientation data used to control the virtual arrow. Some screen shots are given below:


That’s it! You have successfully achieved communication between your orientation sensor and Ardunio board.

Don’t worry if you haven’t being successful. This kind of Arduino experiment is for advanced users and I strongly discourage beginners to trying this before getting warmed up to Arduino.


For more information regarding this sensor please visit the products official page and the following links

A few notes before ending this article

Try using Processing 1.51 it is the most stable version

If you have used MPU6050 the I recommend GY86 10DOF board for more accurate navigation

Reading the datasheet given by Ivensense on this MPU6050 specifically revision 4 of the datasheet.

I used Arduino IDE V1.0.5, it is the most stable of them all and supports all the libraries till to date


Interfacing DS18B20 temperature sensor to Arduino


In this hands-on article, we will discuss DS18B20 temperature sensor from Maxim Integrated company. We will hook up this sensor to Arduino through amazing OneWire bus. Then we will write code that will bring our digital thermometer to life, and print temperature back to our computer. We will write generic code that will work on every Arduino platform.

DS18B20 Programmable Resolution 1-Wire Digital Thermometer

I choose to present you this sensor for several reasons. First of all, availability. You can buy this sensor online for 2-3$ (One Wire Digital Temperature Sensor – DS18B20).
Another good thing about this sensor is programmable resolution. That means, we can choose precision over refresh time, and vice versa. If wired correctly, this sensor can be powered from data line. More informations about this sensor can be found in its datasheet:


If we take a glance at DS18B20 datasheet, we can see that this sensor has three pins:

1. GND – Supply ground

2. DQ – Data line

3. Vdd – Supply 3.0V to 5.5V

So we just connect those pins to Arduino, and we’re ready to go, right? Wrong.
Generally, before we work with any analog or digital electronics, we should read it’s datasheet.

Quote from DS18B20 datasheet:

“The DS18B20 uses Maxim’s exclusive 1-Wire bus protocol that implements bus communication using one control signal. The control line requires a weak pullup resistor since all devices are linked to the bus via a 3-state or open-drain port (the DQ pin in the case of the DS18B20).”

So, we will have to add weak pullup resistor on DQ bus line. For 1-5 sensors, 4.7k ohm resistor.

When we hook-up everything, it should look like this:


Now, we’re ready to do some code!


Before we start coding, we must add OneWire library to our Arduino IDE. You can download lastest library here:
Extract OneWire folder to libraries folder found in Arduino IDE folder. Now, write this code to new Arduino sketch. Explanations are in comments:


int SensorPin = 10; //Our sensor is connected to digital pin 10

//Initiate OneWire communication
OneWire ds(SensorPin);

void setup(void) {
//Initiate serial communication with our computer

void loop(void) {

float T = readT(); // call function to read from sensor
Serial.print(“Temperature is: “); // print out results to us
Serial.println(” deg.C”); // print out results to us


float readT(){
//returns the temperature from our sensor

byte data[12];
byte addr[8];

if ( ! {
return -300; // if there is no sensor on OneWire Bus, return -300 value

ds.write(0×44,1); // tell sensor to start converting
ds.write(0xBE); // tell sensor to start sending data

for (int i = 0; i < 9; i++) { // we receive data in this loop
data[i] =;


byte MSB = data[1];
byte LSB = data[0];

float raw = ((MSB << 8) | LSB); // move MSB left for 8 spaces, join that with LSB
float realTempC = raw / 16; // move decimal point left for 4 spaces, result our temperature
return realTempC;


Now, let’s test our device! Open Serial Monitor at 9600bps, and you should have readings like this:

Temperature is: 28.31 deg.C
Temperature is: 29.25 deg.C
Temperature is: 29.56 deg.C

That’s it! Have fun extending it.

You can find more information and examples for this topic at site:

Interfacing SirfStarIII GPS module sensor to Arduino


In this hands-on tutorial we will hook up a GPS module to Arduino prototyping platform, and write complete Arduino code, step by step, with brief explanations. GPS modules are unlikely to work inside buildings, so we will show you few possibilities with powering your Arduino with batteries.

For this tutorial, we will be using PMB-648 GPS (SirfStarIII chipset) module:

Don’t worry if you have other GPS modules, almost all of them use the same communications standard,  TTL or RS-232 asynchronous serial at 4800 bps. Do not worry about this right now, we will explain it into details later. Beautiful thing about this GPS module is that it has built-in antenna, do you do not have to worry about connecting one.

First of all, let’s take look at our PMB-648 specifications sheet:

On first page, bottom-right section of the page, we can see the pinout of this module. As we can see, this module supports two standards for communications, RS-232, and TTL. We will use TTL standard, because Arduino is compatible with it.

WARNING: you should not, at any circumstances, connect RS-232 pins to Arduino! RS-232 voltage range is much higher than Arduino voltages, you will destroy onboard microcontroller!

If you want to learn more about RS-232 or TTL, you can read about it here:


What we are trying to accomplish is to connect Arduino to GPS module, read from it, and then send read data from Arduino to our computer (GPS -> Arduino -> Computer).

In this purpose, Arduino will talk to GPS using SoftwareSerial communication, and Arduino will report to us using his Hardware Serial. Do not worry if you do not fully understand this concept at this time, we will be demonstrating it soon.

Now, let’s connect complete circuit!

First, connect 5v power supply from Arduino to GPS Vcc and GND pins.

Second, connect GPS TTL TX pin to Arduino digital pin 2.

And, that is all of wiring we need. Whole process is illustrated below:


PMB-648 GPS module has LED on his board. This LED will start blinking when you apply 5v to module. This LED can indicate if GPS is locked on satelites:

-   Blinking: searching for satelites;

-   Constantly on: locked on satelites.

There is no need to connect GPS TTL RX pin to Arduino, because we will only read from it. We do not have need to transmit data to GPS.

Notice: there are some configurations on GPS module that can be accessed through it’s TTL RX pin. For most of the time, default configurations are what we need.


Now, our task is to write some code to bring our masterpiece to life.

What we need to to is very, very simple. We want to set Software Serial communication on digital pins 2 and 3 (notice on schematics that we connected GPS TTL TX on pin 2), and we want arduino to print exactly the same data to us, on Arduino Serial monitor. Here is the complete code:

#include <SoftwareSerial.h>

SoftwareSerial GpsMod = SoftwareSerial(2,3);

void setup()

 void loop()
Serial.print(, BYTE);

In setup function, we initiated software serial communication with GPS module at 4800bps, as it is required on specifications page. We also initiated hardware serial communication with our computer.

In loop function, we are simply bridging data from GPS module, to computer.

After you upload your sketch and open serial monitor, you will see that your GPS module is sending data every one second. Data you are looking at is called NMEA codes.

NMEA reference manual  briefly explains this codes, and can be found here:

Also, a nice guide on how to decode NMEA codes is available here:

It is very straightforward and intuitive.

If you want to play with your GPS Module, you will probably want to go outside. Arduino has internal voltage stabilizer, so you can apply any voltage between 5V and 20V to DC Jack. Recommended voltages are in range between 7 and 12 volts. If you would like to read more about this, you can visit:

Sharp GP2D120 Distance Sensor Tutorial


The Sharp GP2D120 is a distance sensor from Sharp’s range of optoelectronic devices. Optoelectronic devices are transducers that work by converting light to electricity or vice versa.

The GP2D120 has two lenses in front; it works by emitting a focused beam of light through one. If there is an object in the sensor’s working range the beam reflects off that object and lands onto the collector (second) lens. This makes a triangle between the emitter, object and collector. The sensor then checks the angle of the reflected beam and uses it to identify how far the object is.

There are two types of inputs digital and analogue. Digital inputs are discrete signals in the form of HIGHs and LOWs. The combination of these HIGHs and LOWs indicates what the data is. Analogue signals are continuous signals in the form of voltage. The GP2D120 distance sensor gives an analogue output. It can detect objects within the range of 40mm to 300mm. When the sensor is turned on it takes 44 ms to start up and has a response time of 39 ms meaning that it updates its values every 39 ms. The average power consumption is 33 mA.

Like everything there are pros and cons for this sensor as well. The Sharp GP2D120 is cheap, light, compact, easy to program and accurate enough for most tasks. On the other hand it can only get a reading of one point of the object, any readings below 40mm are unreliable and there is no possible method of differentiating if the object is right in front of the sensor (0mm) or there is no object in front of the sensor.


The Tutorial



  1. Arduino Uno (but any other would work too as long as you can get it to communicate with the PC).
  2. Sharp GP2D120 distance sensor
  3. Arduino IDE



Setting up the Hardware

This tutorial assumes you have an Arduino connected to your computer for programming. Your sensor would have come a cable that consists of three wires; red, black and white. One end of the cable should have a JST female connector and the other end should be three bare wires. Go ahead and connect the JST female connector into your sensor; there is only one right way the cable will go in.

Following are what the three different wires are:

  • Red (VCC) – Connects to the positive terminal of the sensor
  • Black (GND) – Connects to the ground terminal of the sensor
  • White (VO) – Connects to the analogue output from the sensor

Ensure that your Arduino is powered off. Now insert the red wire into the +5V power pin and the white wire into the ground power pin of the Arduino. Insert the white wire into the A0 analogue pin. Plugging in the hardware is now complete. Let’s move on to the programming bit.

Programming the Arduino

First we define which pin the distance sensor is connected to:

#define ds_pin 0 // Pin to which the distance sensor is connected

TIP: Instead of writing the pin numbers in between the code #define them on top so if you want to check or decide to change the pin to which your device is connected you can quickly do it here.

int ds_value; // Integer to hold the sensor’s reading

The integer ds_value is the variable that we will use to store the sensors value.

To program template for an Arduino requires the following two functions:

void setup ()

      // This function runs immediately after the Arduino is turned on   and only runs once

void loop ()
      // This function keeps looping and is the main function to write               your code in


Go ahead and initialize the serial port with the following code in the setup loop:

Serial.begin (9600);   // Initiates serial communication at 9600 baud

Note: The arduino can communicate over the serial port with a lot of baud rates (bits per second). You can look these up in Arduino’s reference guide. Do keep this number in mind because when reading the serial port on your PC you will have to set it to that baud rate.

Let’s now enter the first bit of code for our loop function to read the distance sensor values

ds_value = analogRead (ds_pin);  // Reads the distance sensor

This distance sensor outputs an analogue voltage in the range of 0 – 3V (approx.) whereas the analogRead (); command takes the reference voltage to be 5V and gives the output in the range of (0 – 1024) i.e. a value of 5V read using analogRead (); gives the result of 1024. We therefore need to scale our ds_value. Since the maximum value we can get with our sensor is 3 the function will return a maximum value of


ds_scaledValue = ((float)ds_value / 615) * 1024;  // Calculates the scaled value

Finally, we output this value to the PC

Serial.println ((int)ds_scaledValue);  // Screams out the scaled value as integer


Your final code should look like this:

#define ds_pin 0       // Pin to which the distance sensor is connected
int ds_value;          // Integer to hold the sensor’s reading

float ds_scaledValue;  // Distance sensor’s scaled value

void setup ()
  Serial.begin (9600); // Initiates serial communication at 9600 baud

void loop ()
  ds_value = analogRead (ds_pin);  // Reads the distance sensor
  ds_scaledValue = ((float)ds_value / 615) * 1024; 
  // Calculates the scaled value

  Serial.println ((int)ds_scaledValue);  // Screams out the scaled value as integer
  delay (200);                  // Delay of 200ms

Running the Program

Finally! We’re all done. All we need to do now is run the system so go ahead and turn on your Arduino. Ensure that it is connected to the PC. Upload the program to the PC and press the serial monitor icon   run_program    in the top left.

You should now see your Arduino now sending values to you that are the scaled distance sensor values.

Calibrating the Sensor

The datasheet for the sensor will provide you with a graph that shows how the value of the sensor relates the distance between it and the object. These graphs are for an ideal sensor. Every sensor is different (several factors affect the sensors reliability e.g. how old it is, how clean the lens is, how reflective the object is) which is why you will have to calibrate your sensor yourself even if you have multiple new just unboxed sensors.

For example, if you are using the sensor to check if there is something between 50mm and 200mm of the sensor.

#define ds_pin 0    // Pin to which the distance sensor is connected
#define ds_scaledResolution 1024

#define ds_valueAt50 900     // The value the sensor returns at 50mm distance
#define ds_valueAt200 200    // The value the sensor returns at 200mm distance

int ds_value;          // Integer to hold distance sensor’s reading
float ds_scaledValue;  // Distance sensor’s scaled value

void setup ()
  Serial.begin (9600); // Initiates serial communication at 9600 baud

void loop ()
  ds_value = analogRead (ds_pin);     // Reads the distance sensor
  ds_scaledValue = ((float)ds_value / 615) * ds_scaledResolution;  // Calculates the scaled value
  if ((ds_scaledValue <= ds_valueAt50) && (ds_scaledValue >= ds_valueAt200)) // Checks if any object in range
    Serial.println (“Object detected!”);  // Screams if object found