USB Communication between Android and Arduino

Hello friends, hope you all are fine and having fun with your lives. In today's post, I am going to share How to do  USB Communication between Android and Arduino. I have designed many projects before in which I have interfaced Android and Arduino and communicated between them but in those projects I have used either Wifi or Bluetooth as a mode for communication. But recently I got a project in which I have to do USB Communication between Android and Arduino, they have this restriction of using USB. So, I have to work on it and I got it working successfully. You should also have a look at How to Install Android Studio. and Getting Started with Android.

So, today I thought to share it with you guys. It isn't much difficult but will need a little patient. When I started working on it I couldn't find any data on it online and I have to work a lot to make it work. So that's why I am sharing it so that others can get it work easily. When I was starting this project then I have a bit confusion that whether to use the USB Host shield of Arduino or to use the usb cable through which we connect Arduino with computer. After a little research I got the idea that simple USB will work fine so I go with it. I have explained this tutorial in detail. First I have done the Arduino side because that one is quite easy and after that I touched the Android side that's a bit complex and you must have the prior knowledge of it if you wanna make it work. So, let's start this project. :)

Circuit designing for Monitoring Incoming Data

  • First of all, I have used the OTG cable for interfacing Android with Arduino, which is shown in below figure:
  • From the above figure, you have clearly got the idea that why I have used this cable, one side of this cable, which is mini usb, will be inserted in the Android mobile while the other side, which is the female usb port, will be plugged with the usb cable of Arduino, as shown below:
  • I have connected the two cables in the above figure, now one end of this cable is gonna inserted in the Android mobile while the other side will be plugged in Arduino and in this way we will do the USB communication between Android and Arduino.
  • But there's some problem, we need some way to display the data in Arduino, which we are getting from Android. So for that reason I have interfaced another Arduino with this Arduino and I am doing serial communication between these two Arduinos.
  • So, in simple words, Android is plugged with first Arduino via USB and the first Arduino is connected with second Arduino via serial port. so, when Android will send the data to first Arduino then first Arduino will send that data to second Arduino, which we can easily see on the Serial Terminal. So here's the circuit diagram of two Arduinos.
  • Now you can have the idea in above figure that the two arduinos are communicated via pin # 2 and 3 which I have made Software Serial, now with the pins they are sending data from first Arduino to second Arduino. Now let's have a look at the coding of both Arduinos.

Programming Code for Arduino

  • As in the above section, we have connected two Arduinos via Serial communication in which we used software serial.
  • Next thing we need to do is to write the code for both of them, so simply copy the below code and upload it in both of your Arduino boards.
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2,3);

void setup()
{
  Serial.begin(9600);
  Serial.println("www.TheEngineeringProjects.com");

  mySerial.begin(9600);
  mySerial.println("www.TheEngineeringProjects.com");
}

void loop() 
{
  if (mySerial.available())
    Serial.println(mySerial.read() - 48);
  if (Serial.available())
    mySerial.println(Serial.read() - 48);
}
  • Above code is quite simple and I am simply sending any data I am receiving on the Serial port to software serial, so when I get the data from Android via USB, I will receive that data and then will forward it to Software Serial on which my second Arduino is connected, which will receive that data and then show it over to Serial Terminal.
  • Now let's have a look at Android side code, which is a bit complicated.

Programming Code for Android

  • You must have the prior knowledge of Android, if you wanna make it work so if you know the basics of Android then you know that there are two main files designed in Android, which are Java file and XML file.
  • So, first of all create a project in Android and place the below code into its XML File:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidusbhostarduino.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://www.TheEngineeringProjects.com/"
        android:textStyle="bold" />

    <ToggleButton
        android:id="@+id/arduinoled"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textOn="ON"
        android:textOff="OFF" />

</LinearLayout>
  • Next thing we need to do is to add the USB permission in the manifest file, so paste this  code in your manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.theengineeringprojects.dani" >


    <uses-feature android:name="android.hardware.usb.host" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
            </intent-filter>

            <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
                android:resource="@xml/device_filter" />
        </activity>
    </application>

</manifest>
  • Now the last thing, you need to do is to add the code in java file so copy the below code and paste it in your jave file:
package com.theengineeringprojects.dani;

import java.nio.ByteBuffer;

import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbRequest;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class MainActivity extends ActionBarActivity implements Runnable{

    private static final char CMD_LED_OFF = '1';
    private static final char CMD_LED_ON = '2';

    SeekBar bar;
    ToggleButton buttonLed;

    private UsbManager usbManager;
    private UsbDevice deviceFound;
    private UsbDeviceConnection usbDeviceConnection;
    private UsbInterface usbInterfaceFound = null;
    private UsbEndpoint endpointOut = null;
    private UsbEndpoint endpointIn = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        buttonLed = (ToggleButton)findViewById(R.id.arduinoled);
        buttonLed.setOnCheckedChangeListener(new OnCheckedChangeListener(){

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                if(isChecked){
                    sendCommand(CMD_LED_ON);
                }else{
                    sendCommand(CMD_LED_OFF);
                }
            }});

        usbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
    }

    @Override
    public void onResume() {
        super.onResume();

        Intent intent = getIntent();
        String action = intent.getAction();

        UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
        if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
            setDevice(device);
        } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
            if (deviceFound != null && deviceFound.equals(device)) {
                setDevice(null);
            }
        }
    }

    private void setDevice(UsbDevice device) {
        usbInterfaceFound = null;
        endpointOut = null;
        endpointIn = null;

        for (int i = 0; i < device.getInterfaceCount(); i++) {
            UsbInterface usbif = device.getInterface(i);

            UsbEndpoint tOut = null;
            UsbEndpoint tIn = null;

            int tEndpointCnt = usbif.getEndpointCount();
            if (tEndpointCnt >= 2) {
                for (int j = 0; j < tEndpointCnt; j++) {
                    if (usbif.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                        if (usbif.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_OUT) {
                            tOut = usbif.getEndpoint(j);
                        } else if (usbif.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_IN) {
                            tIn = usbif.getEndpoint(j);
                        }
                    }
                }

                if (tOut != null && tIn != null) {
                    // This interface have both USB_DIR_OUT
                    // and USB_DIR_IN of USB_ENDPOINT_XFER_BULK
                    usbInterfaceFound = usbif;
                    endpointOut = tOut;
                    endpointIn = tIn;
                }
            }

        }

        if (usbInterfaceFound == null) {
            return;
        }

        deviceFound = device;

        if (device != null) {
            UsbDeviceConnection connection =
                    usbManager.openDevice(device);
            if (connection != null &&
                    connection.claimInterface(usbInterfaceFound, true)) {
                usbDeviceConnection = connection;
                Thread thread = new Thread(this);
                thread.start();

            } else {
                usbDeviceConnection = null;
            }
        }
    }

    private void sendCommand(int control) {
        synchronized (this) {

            if (usbDeviceConnection != null) {
                byte[] message = new byte[1];
                message[0] = (byte)control;
                usbDeviceConnection.bulkTransfer(endpointOut,
                        message, message.length, 0);
            }
        }
    }

    @Override
    public void run() {
        ByteBuffer buffer = ByteBuffer.allocate(1);
        UsbRequest request = new UsbRequest();
        request.initialize(usbDeviceConnection, endpointIn);
        while (true) {
            request.queue(buffer, 1);
            if (usbDeviceConnection.requestWait() == request) {
                byte rxCmd = buffer.get(0);
                if(rxCmd!=0){
                    bar.setProgress((int)rxCmd);
                }

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            } else {
                break;
            }
        }

    }

}
  • Now hit the Enter button on your Android Studio and if everything goes fine then you will get a screen as shown below on your mobile:
  • Here's a simple button, when you press this button, it will show ON and will send the data which you wanna send for example, in my case I am sending character "1" and "2" on button press.

USB Communication Between Android and Arduino

  • Now let's do the usb communication between Android and Arduino, I hope till now you have configured your Android Mobile and both the Arduinos so their overall picture will look something like:
  • You can clearly see in the above figure that the Android Mobile is connected with Arduino, which is further connected with second Arduino and US of Second Arduino is connected with computer, where I am checking the coming data from Android in Serial Terminal.
  • Now when I press the button on Android app, it will send 1 or 2 to Arduino, which is shown in below figure:
  • I have pressed the toggle button on Android many times thats why I have got many 1 and 2 in Serial Terminal.
  • So, that's how I am receving data from Android to Arduino. Now instead of sending 1 and 2, you can send any kind of data from Android to Arduino. I will post more tutorials on it in which I will be sending some data like GPS coordinates from Android to Arduino plus I will also post the 2 way communication i.e. receving data in Android from Arduino.

The Arduino part is easy but the Android part is bit difficult so if you need help then ask in comments and I will help you out. That's all for today, will meet you guys in coming tutorials. Take care !!! :)

How to get Hex File from Arduino

Hello friends, hope you all are fine and having fun with your lives. In today's post, I am gonna share How to get Hex File from Arduino. It's quite a simple post and I have already explained it many times in my posts but still, I am getting a lot of messages regarding it that's why I thought to write a separate post for it. First of all, let's have a little introduction about it. If you have worked on PIC Microcontrollers or Atmel etc then you have seen that you always get hex files from their compilers and then you burn that hex file in the respective Microcontroller using their programmer or burner. But that's not the case with Arduino. In Arduino boards, you simply plug it with your computer and you hit the Upload button and the code automatically gets upload in Arduino boards. It doesn't create any hex file. You should also have a look at Arduino Library for Proteus in which you can upload this hex file.

So, now the question arises that why do we need the hex file in the first place, when we can upload the code without it? The answer to this question is, there are many cases when a hex file is required. For example, instead of using the Arduino board you just want to use the ATmega328 or Attiny microcontroller then the easiest way is to write the code in Arduino and then get its hex file and upload it in your microcontroller, which makes the task quite easy. Another example is Proteus simulation, when you want to simulate your Arduino board in Proteus software then you need to get the hex file so that you can upload it to your Arduino board. Another case is freelancing, when you are working on some project as a freelancer, then there are many cases when you don't wanna send your code to the client, instead you want to send the hex file to him so that he can test and verify the code, in such cases it also required. So let's get started with how to get hex file from Arduino.

  • Here's the video in which I have shown How to get the hex file from Arduino, I hope it will help:
Where To Buy?
No.ComponentsDistributorLink To Buy
1Arduino UnoAmazonBuy Now

How to Get Hex File from Arduino ???

  • First of all, open your Arduino software and write your code and test it.
Note:
  • If you haven't bought your Arduino UNO yet, then you can buy it from this reliable source:
  • Once you are confirmed that your code is ready and you want to generate the hex file, then click on the File option in the above menu and then Preferences as shown in below figure:
  • In the above figure, I have used the simple blink example and I am gonna generate its hex file.
  • Now when you click on the Preferences, a new window will pop up.
  • In this new window, tick the compilation option as shown in the below figure:
  • After ticking it, now click on the OK button and this dialog box will close.
Note:
  • By ticking this option you are allowing the Arduino software to show verbose outputs in the output panel present at the end of Arduino software, which has a black background.
  • So, you can also tick the upload option but then you need to upload the code to get these output commands.
  • Now hit the compile button as we tick the compilation option, so it will compile the code and will give you all the commands as shown below:
  • Now you can see clearly in the above figure that there are many commands in the black portion, these are the verbose outputs that Arduino is giving us.
  • The last line of these verbose outputs, which I have also highlighted is the link to hex file, which in our case is:

C:UserszainAppDataLocalTempbuild7243111610766241365.tmp/Blink.cpp.hex 

  • Now, remove the name of the hex file from this link and it will become:

C:UserszainAppDataLocalTempbuild7243111610766241365.tmp

  • Paste this link in the computer address bar and this folder will open up.
  • In that folder search for your respective file and you easily get the hex file of your code.
Note:
  • Actually, while uploading the code to Arduino boards, Arduino software creates the hex file of the code in the temporary folder and once the code is uploaded then it deletes that hex file.
  • That's why, we don't get the hex file, but by clicking the option you can easily get the hex file and then can use it for any purpose.

That's all for today, and I think it was quite an easy tutorial but still if you having questions then ask in the comments and I will resolve them. till next tutorial, take care!!! :)

Intelligent Energy Saving System

Hello friends, hope you all are fine and having fun with your lives. Today, I am going to share a complete project with you guys. Its an Intelligent Energy Saving System which I designed around two years ago. So, today I thought to share it so that others could also get benefit. In this project, I have used Arduino UNO board for programming purposes. Its not much complicated project but is the basic for many complex projects.

Energy, is a small word, but is the problem of whole world. Particularly when we are talking about electrical energy. IF you consume more electrical energy then you will get quite huge bill at the end of the month. :P So, there's always work done on reducing the consumption of electrical energy and also we compare energy costs from different providers. As a human, suppose you turn ON your room fan, then normally you forget to turn it OFF and thus your bill keeps on increasing. So in order to avoid this, automation is the only tool which comes in handy. Like there must be such system which automatically detects whether someone is still in the room or not and if there's no one then lights got OFF automatically. In this way, you can quite easily reduce your electricity cost. This same concept is presented in this project, let's have a complete look over it. :)

Overview of Intelligent Energy Saving System

  • In this project, we have designed a complete room and used two inductive loads i.e. bulbs and one fan.
  • Now the purpose of this project was to save the energy so we used two IR sensors for counting.
  • Now, if there's no one present in the room then the loads will automatically turn OFF and when someone will enter in the room then the loads will automatically turn ON.
  • Moreover, we have also added a counter functionality in it i.e. the project will also count the number of people present in the room.
  • All these parameters will also display on the LCD attached with Arduino.
Components Used

I am mentioning here the components used in designing this project. I am not giving the exact values as you will get them in the circuit diagrams. Here's the list:

  • Arduino UNO
  • IR Sensors
  • 16 x 2 LCD
  • 100W Bulbs
  • 12V Fan
  • 2 Relay Board
  • 7805 (IC Regulator)
  • LED (Indication)
  • Resistance
  • Capacitors

Circuit Diagrams of Intelligent Energy Saving System

Suppose you are designing this project then the first thing you are gonna need is the circuit diagrams for the project so here I am gonna show you all the circuit diagrams step by step so let's start:

1: Interfacing of Arduino with LCD
  • First thing we are gonna need is the interfacing of Arduino with LCD. LCD used in this project is 16 x 2.
  • I have first designed the simulation in Proteus as its always better to design the simulation before going into real hardware.
  • Now upload the below code into it, just to test that whether its working fine or not:
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup()
    {

    lcd.begin(16, 2);
    lcd.print("www.TheEngineer");
    lcd.setCursor(0,1);
    lcd.print("ingProjects.com");
    }
    void loop() {}
  • Now run it and if everything's gone fine then you will get something as shown in below figure:
Note:
2: Circuit diagram of 2 Relay Board
  • Next thing we are gonna need is the two relay board. Using these relays we are gonna turn ON or OFF our loads.
  • Here's the circuit diagram for 2 relay board.
  • As you can see in the above figure, I have used two relay board, where both the relays are controlled bt simple logic operators.
  • Now instead of these logic operators, you need to give Arduino Pins here.
  • I have made the first relay ON while the second relay is OFF.
  • In the above figure, relay outputs are open so you can place anything here as its gonna act as switch. So, in our case the loads will be placed after this relay.
3: Circuit Design of Buzzer
  • Next circuit design which we need to understand is the buzzer circuit design.
  • Its quite simple and similar to 2 relay board. I have also published a detailed post on How to Design a Buzzer in Proteus ISIS, which will be quite helpful.
  • Here' I am gonna explain it lightly, so let's have a look at the circuit diagram of buzzer:
  • You can quite easily understand the above figure, where I have shown both the ON and OFF states of buzzer.
4: Circuit Diagram of IR Sensor:
  • In this project, I have used two IR sensors, both are placed on the door one after another. You can read more about the designing of IR Sensor on my post Circuit Diagram of IR Sensor using 555 Timer.
  • I have named them Entering IR Sensor and Leaving IR Sensor.
  • The logic behind these two sensors is that, when someone enters in the room then he will first pass the Entering IR Sensor and then will hit the Leaving IR Sensor and if someone is leaving the room then he will first pass the Leaving IR Sensor and then will cut the Entering.
  • So, in this way I am counting the persons if someone entering in the room I simply increment and if someone's leaving then I decrement.
  • Now, if number of people in the room becomes zero then I turn OFF all the lights and the fan, and if there even one person in the room then I turn ON the lights and fan.
  • Here's the circuit diagram of IR Sensor:
  • IR transmitter and Receiver are not available in Proteus so that's why I have used the button so when you press the button, its like someone cut the beam of IR sensor, and you will get below result:
 
5: Complete Circuit Diagram of Intelligent Energy Saving System
  • Now that we have designed the individual circuit diagrams, next thing we are gonna do is the assembly of complete project.
  • So, here's the complete circuit diagram of this project:
  • As you can see in the above figure, I have used two IR Sensors. The first IR Sensor is for entering in the room while the IR sensor is for leaving the room.
  • Next is the buzzer circuit which is also quite simple and I have explain in detail above.
  • LCD will display the no of people in a room and will also display either the bulb is ON or OFF, and also about Fan status.
  • I haven't shown the relay circuit in above figure as it will not fit in the space and I think you guys can place it easily.

Programming Code for Intelligent Energy Saving System

  • The code designed for this project is developed in Arduino software.
  • Code is as follows:
#include <LiquidCrystal.h>
#include <OneWire.h>
#include <DallasTemperature.h>
 
#define ONE_WIRE_BUS 8
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

float celsius, fahrenheit;

int Sensor1 = A0;
int Sensor2 = A1;

int Bulb = A5;
int Fan = A4;
int Buzzer = A3;

int Counter = 0;
int Sen1Check = 0;
int Sen2Check = 0;

void setup(void) 
{
    Serial.begin(9600);
    digitalWrite(Bulb, HIGH);
    digitalWrite(Fan, HIGH);
    digitalWrite(Buzzer, HIGH);
    pinMode(Sensor1, INPUT);
    pinMode(Sensor2, INPUT);
    pinMode(Bulb, OUTPUT);
    pinMode(Fan, OUTPUT);
    pinMode(Buzzer, OUTPUT);
    
    
    lcd.begin(20, 4);
    lcd.setCursor(0, 1);
    lcd.print("Temp = ");
    lcd.setCursor(0, 0);
    lcd.print("Counter = ");
    lcd.setCursor(12, 0);
    lcd.print("Persons");
}

void loop() 
{
  CheckEntry();
  CheckLeaving();
  lcd.setCursor(7, 1);
  sensors.requestTemperatures();
  lcd.println(sensors.getTempCByIndex(0));
  lcd.setCursor(12, 1);
  lcd.print(" degC");
  lcd.setCursor(10, 0);
  if(Counter >= 0){lcd.print(Counter);}
  if(Counter < 0){Counter = 0;}
  
  if(Counter > 0)
  {
      digitalWrite(Bulb, LOW);
      digitalWrite(Fan, LOW);
      digitalWrite(Buzzer, HIGH);
      lcd.setCursor(0, 2);
      lcd.print("Fan : ON ");
      lcd.setCursor(0, 3);
      lcd.print("Bulb : ON ");
  }
  
  if(Counter < 1)
  {
      digitalWrite(Bulb, HIGH);
      digitalWrite(Fan, HIGH);
      digitalWrite(Buzzer, HIGH);
      lcd.setCursor(0, 2);
      lcd.print("Fan : OFF");
      lcd.setCursor(0, 3);
      lcd.print("Bulb : OFF");
      
  }
  

}


void CheckEntry()
{
    if(((digitalRead(Sensor1) == LOW) || (Sen1Check == 1)) && (Sen2Check == 0))
    {
        while(digitalRead(Sensor1) == LOW);
        Sen1Check = 1;
     
        if(digitalRead(Sensor2) == LOW)
        {
            Counter++;
            Sen1Check = 0;
            while(digitalRead(Sensor2) == LOW);
        }
    } 
}


void CheckLeaving()
{
    if(((digitalRead(Sensor2) == LOW) || (Sen2Check == 1)) && (Sen1Check == 0))
    {
        while(digitalRead(Sensor2) == LOW);
        Sen2Check = 1;
       
        if(digitalRead(Sensor1) == LOW)
        {
            Counter = Counter - 1;
            Sen2Check = 0;
            while(digitalRead(Sensor1) == LOW);
        }
    } 
}
  • Coding isn't much difficult for this project, but still if you get into some trouble ask in comments and I will check it out.
  • Here's the complete video for this Intelligent Energy Saving System, which will explain all about the project.
That's all for today. I hope I have helped you guys in some way. Till next tutorial, take care ALLAH HAFIZ :)

Design a Buzzer in Proteus ISIS

Hello friends, hope you all are having fun and enjoying life. Today's post is quite a simple one and is about designing of circuit diagram of buzzer in Proteus ISIS. Buzzer is quite a common electrical component which is used in almost every Embedded Systems project. For example, you have seen a simple UPS, it gives a beep each time the light goes off or it has depleted its battery. Buzzer is normally used for given some indication and normally this indication is kind of a warning.

Proteus has a builtin component for buzzer and its an animated component means it gives a sound (beep) when its turned ON. So, I am gonna use that one and will give you an actual beep on it. So, it won't be much difficult and quite a simple procedure. In this post, I am not gonna interface it with any Microcontroller i.e. Arduino or PIC Microcontroller but if you want then you can quite easily control it using any of them. You simply need to give pulse to it and you can control it. If I get time then I will post the control of buzzer with Arduino. So, let's start with it.

Design a Buzzer in Proteus ISIS

  • First of all, get components from the Proteus library as shown in below figure:
 
  • Now after selecting these components, design a circuit diagram in Proteus as shown in below figure:
  • In the above circuit, I have used an optocoupler PC817 in order to control the buzzer.
  • The optocoupler is controlled by a simple logic operator, now when you change the logic operator from 1 to 0 the buzzer will turn on.
Note:
  • Optocoupler is working here on inverse logic i.e. when we send 1 then its OFF and when we send 0 then its ON.
  • If you are designing it on hardware then you can use PC817 Optocoupler.
  • So now if everything's fine then simply run the simulation and then click on the logic operator and you will get the below results:
  • You can see in the above figure, there are two states.
  • In the Buzzer ON state LED is OFF but the buzzer will be ON and you will hear a beep like sound, which obviously can't be heard here in the image. :)
  • While in the OFF state LED is ON but the buzzer will be OFF and you wont hear anything.
That's quite a simple tutorial and quite easy to understand but still if you have any problem, then ask in comments. Till next tutorial, take care and have fun.

NRF24L01+ with Arduino - Response Timed Out

Hello friends, hope you all are fine and having fun with your lives. Today I am going to share a problem and also its solution with you guys. A few days ago, I bought new NRF24L01 modules as they were needed for a project. So, today when I started working on them, I encountered a very strange problem. When I interfaced my NRF24L01 with Arduino and uploaded the transmitting and receving codes in them, I couldn't get anything on my serial terminal as I explained in my previous post Interfacing of NRF24L01 with Arduino. That was quite strange for me as I have worked on this module many times and it never troubled me before. So I keep on working on it but no luck. I even changed my RF modules as I thought may be they are faulty modules but still no luck. :(

So, the next thing came to my mind is to upload the Getting Started example from the RF24 library which I have also given in my previous post Interfacing of NRF24L01 with Arduino, and now when I checked the serial terminal, I got this error:

  • Failed, response timed out.

The screenshot of this response is as follows:

As you can see in the above figure, in the last lines we are getting error that "Now sending 4679...failed. Failed, response timed out." So, that was the problem which I encountered almost for half an hour and then I finally realized what I am missing and how to solve it. Before going to the solution, let me first tell you the types of this modules.

Types of NRF24L01 Module

  • When I encountered this problem, and instead of lot of efforts and not being able to resolve it, I finally thought of using the old module, so I searched for it and luckily I found one of them.
  • So, now I plugged this new module with another Arduino and I checked the properties of both these modules (i.e. the old one and the new one) and for that I simple uploaded the below sketch in both of my Arduino boards and opened the serial terminal.
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"

RF24 radio(9,10);

const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };

typedef enum { role_ping_out = 1, role_pong_back } role_e;

const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"};

role_e role = role_pong_back;

void setup(void)
{
 
    Serial.begin(57600);
    printf_begin();
    
    radio.begin();
    radio.setRetries(15,15);
    
    radio.openReadingPipe(1,pipes[1]);
    
    radio.startListening();
    
    radio.printDetails();
}

void loop(void)
{
}
  • In this sketch, I simple print the details of NR24L01 module, so I uploaded the above sketch in both the Arduinos, one with old NRF24L01 module and the one with new NRF24L01 module, and I got the below response.

  • Now I got the reason that why I am not getting the response for the same code, which worked on the old one, because the old module model was NRF24L01 while this new module is NRF24L01+ which is slightly different from NRF24L01.
  • So that's the reson why I was constantly getting the Failed, response timed out error for this module. So, now lets have a look on how to resolve this issue.

How to resolve "Failed, response timed out" for NRF 24L01+ with Arduino

  • So, now one thing I knew that my module is NRF24L01+ and not NRF24L01 so I need to interface NRF24L01+ with Arduino. :)
  • So, I started looking online and get its datasheet which helped a lot and finally I got the thing.
  • NRF24L01+ draws more current than NRF24L01 while starting up and Arduino couldn't provide that required current to it. That's the reason NRF24L01+ failed to initialize and couldn't send or receive the response.
  • So, in order to remove this issue, I simply placed a Capacitor of 100uF between 3.3V and GND of Arduino and it did the magic. :)
  • Detailed circuit diagram is as follows:
  • So, that's the simple solution which kept me on for around an hour and then I finally got it.
  • As you can see in above figure, its exactly the same circuit diagram and the only addition is the capacitor placed between 3.3V and the GND.
  • After that I uploaded both the codes for receiver and transmitter which I have already posted in my old post Interfacing of NRF24L01 with Arduino and it worked like charm. :)

That's all for today, will meet you guys in the next tutorial soon. Take care!!! :)

Interfacing of LM35 with Arduino in Proteus ISIS

Hello friends, I hope you all are fine and enjoying yourself. Today I am going to share a new project titled Interfacing of temperature sensor LM35 with Arduino UNO in Proteus ISIS. So far, I have only worked on temperature sensor DS18B20 for temperature measurements and I have also uploaded a tutorial on Interfacing of Temperature Sensor 18B20 with Arduino.

Recently I got a chance to work on a project regarding temperature sensing but the condition of this project was that to use only LM35 for temperature detection. Then, I get to know much about LM35, its operating conditions and features. So I thought I should also upload its tutorial as it will also be advantageous for engineering students. Because learning new things is always a charm.

An excellent thing about LM35 is that it's quite cheap as compared to other temperature sensors. And as it's cheap, that's why it's not very reliable, if you personally ask me then I will prefer DS18B20 over LM35 because of its accurate readings. Now, let's move towards its interfacing and its practical applications. First of all, let's have a quick look at the introduction of LM35 and then we will design it in Proteus ISIS.

Where To Buy?
No.ComponentsDistributorLink To Buy
1LM35AmazonBuy Now
2Arduino UnoAmazonBuy Now

Introduction of LM35 Temperature Sensor

  • LM35 is an embedded sensor, used to measure the temperature of its surroundings and is famous because of its low cost.
  • Its output is generated in the form of an Electrical signal and this electrical signal is proportional to the temperature, which it detects.
  • Lm35 is much more sensitive than other temp measuring devices (not accurate).
  • The internal circuitry of this embedded sensor is sealed inside a capsule.
  • LM35 is a 3 pin IC and it is used for temperature detection. The physical appearance of LM35 is shown in the image given below:

  • As you can see in the above image that LM35 is a 3 pin IC:
    1. The first pin is Vcc, so it should be connected to 5V.
    2. The center pin is its Data Pin and LM35 gives its output when it measures temperature.
    3. The third pin is GND and should be connected to the ground of the battery/source.

LM35 Arduino Interfacing

  • As my today's tutorial is about interfacing LM35 with Arduino so let's start it.
  • I have connected LM35 with Arduino microcontroller and it is shown in the image given below:

  • As you can see in the above image, I have connected an LM35 sensor with Arduino UNO.
  • The VCC pin of LM35 is connected to +5V of the Arduino board.
  • Since LM35 generates an analog value at its output pin that's why I have connected this pin to the 'A0' pin of the Arduino board.
  • This pin of Arduino board is used to receive analog data from an external source.
  • And the last pin is connected to the GND pin of the Arduino board.

Arduino Code for LM35

  • After connecting the circuit, now upload the below code to your Arduino board.
#define TempPin A0

int TempValue;

void setup()
{
  Serial.begin(9600); // Initializing Serial Port
}
void loop()
{
  TempValue = analogRead(TempPin); // Getting LM35 value and saving it in variable
  float TempCel = ( TempValue/1024.0)*500; // Getting the celsius value from 10 bit analog value
  float TempFarh = (TempCel*9)/5 + 32; // Converting Celsius into Fahrenhiet

  Serial.print("TEMPRATURE in Celsius = "); //Displaying temperature in Celsius
  Serial.print(TempCel);
  Serial.print("*C");
  Serial.print("    |    ");

  Serial.print("TEMPRATURE = "); // Displaying Temperature in Fahrenheit
  Serial.print(TempFarh);
  Serial.print("*F");
  Serial.println();
  
  delay(1000);

}

LM35 Arduino Simulation in Proteus ISIS

  • Now let's do this project in Proteus. Proteus also has an LM35 sensor in its database which we are going to use here.
  • Moreover, we also know about Arduino Library for Proteus V2.0, so using that library we are going to interface LM35 with Arduino in Proteus ISIS.
  • First of all, design the same circuit as shown in the above figure in Proteus software as shown below:
  • It's the same circuit as we designed before, the only addition is the virtual terminal. We are using it to check the values.
  • It's simply like the Serial Monitor we use in Arduino software.
  • So, now using the above code, create the hex file and upload it in Proteus.
  • Now hit run and if everything goes fine then you will get results as shown in the below figure:
  • You can see the Virtual Terminal is showing the same value as shown on the sensor which is 33 in Celsius and later I converted it to Fahrenheit.
It's quite simple and I have also commented on the code but still if you find trouble then ask in comments and I will resolve them. Will meet in the next tutorial, till then take care!!! :)

3 Level Cascaded H Bridge Inverter

Buy This Project

Hello Friends, i hope you all are fine and enjoying. Today i am going to share my new project tutorial which is 3 level cascaded H bridge Inverter. I also have explained inverters in detail in one of my previous tutorial which was Introduction to Multilevel Inverters. In this tutorial i am going t o explain a new application of cascaded H-bridge inverters and we will design a 3-level cascaded H bridge Inverter through it.

Before going to that, first of all lets recall some basics of Inverters from our previous posts. Inverters or commonly known as power inverters and A dc-to-ac converter whose output is of desired output voltage and frequency is called an inverter. Inverters are also called as counter devices of rectifiers. Rectifiers are those devices which are used to convert Alternating current (AC) into Direct Current (DC). Based on the type of operation, inverters can be divided into 2 major classes named as:

  • Voltage Source Inverter (VSI)
  • Current Source Inverter (CSI)

A voltage controlled inverter or VSI is one in which independent controlled ac output is a Voltage waveform. On the other hand, a current source inverter or CSI is one in which independent controlled ac output is Current waveform. Since my today's tutorial title is 3-level cascaded H-bridge inverter, A three level inverter is better than a two level inverter and the reason is that in 3 level inverter, we are dealing with three output voltage or current levels and the beauty of these type of inverters is that, they give better output and current sinusoidal waveforms and Threshold values are much better. Now i am done with the introduction and basics of inverters, now lets move towards the actual working of my project tutorial. You can also buy the complete simulation of this project and we have kept very small price for it which is only $10, only to meet our design costs.

 

3 level Cascaded H-Bridge Inverter

  • We have designed the 3 level cascaded H-bridge inverter in MATLAB Simulink and the complete diagram of the circuit is shown in the image given below:
  • The above figure seem like a complex one but it is very simple to understand and has a large no of applications. So lets explain each and every parameter one by one.
  • In the first stage, signal comes to a common junction and in MATLAB it is known as 'Bus Selector'. It can accept no of inputs and outputs simultaneously. It has 1 input signal and 2 output signals.
  • The output from this junction is going to 2 blocks named as 'A9' and 'A10'.
  • In order to explore these blocks, you can simply double click on the and a new window will open. That window is shown in the image given below:
  • Every block is infact a H-bridge( it contains 4 small blocks which are arranged in H form). It needs a DC supply to operate and at input and output we have apply scopes to monitor its input and output waveforms.
  • Now if you want to explore it more then simply go to any small box, double click on it and a new window will open, which is shown in the image below:
  • When you will double click on that small box then a new and very informative window will open which will represent, what is fabricated in that small box.
  • If you carefully read the top lines then it reads that a gto transistor is fabricated in parallel with a series RC circuit. GTO means a Gate Turn Off transistor.
  • GTO is a special type of transistor and a high power semi conductor device. The difference between a GTO and any other type of transistor is that the other transistors need a Gate pulse to turn ON and when you will remove the Gate pulse they will still remain in ON state.
  • To turn it OFF you have to apply some alternate means like apply reverse voltage and when transistor tends to go into other direction we remove these reverse voltages.
  • Unlike any other type of transistor, the beauty of GTO is that it can be turned ON & OFF only through gate control, which makes it a very important electrical component to implement.
  • In ON state, GTO has some particular values of Resistance and Inductance.
  • In OFF state, it has infinite internal impedance and no current passes through it in OFF state.
  • Now in the circuit we have arranged 6 blocks. We have 3 sets of blocks and each set contains 2 thyristor blocks arranged in parallel with each other.
  • In input supply from source is coming to every block in 3 sets. The output from each block goes to a ideal voltage measurement block representing as VC.
  • When you will run the simulation, and to monitor the output voltage results, you will double click on this block and it will be giving complex values.
  • After these voltage measurement blocks, we have Fourier analyzer block. This block Fourier analyzes the input signal over a running window of one cycle of fundamental frequency component.
  • First and second output returns the Magnitude and Phase angle of the signals under consideration respectively. Here we are dealing with fundamental harmonic component so, i have kept its value 1.
  • All this can be seen in the image shown below:
  • If you have connected all the blocks in their exact positions and all the connections are OK then, when you will run the simulation and the waveforms on the scope will like:

OUTPUT WAVEFORMS

  • The output results of scope#1 are shown in the image given below:
  • You can see that in the above image, we have output square waves of three different colors which are green, yellow and pink.
  • As i explained earlier that we are designing a 3 level inverter and we will be dealing with 3 output waveforms, which verifies our conclusion.
  • The output graph of scope#3 is shown in the image given below:
  • If you look closely then, the output graph of scope#1 is similar to that of scope#3 but the output curves of scope#3 are bit contracted.
  • The output graph of the scope#2 is shown in the image given below:
  • The output of scope#2 represents sinusoidal square waves and bu taking the mean of every part of square wave, we can generate a AC curve.
  • The output of scope#5 is similar to that of scope#2 and it is also shown in the image given below:
  • The output of scope#5 is s bit purified and much similar to sinusoidal AC signal.
Alright friends, that's all from my today's post. It was a bit lengthy but very technical and easy to understand. I hope you have learned something new today. If you have any questions regarding this, then don't feel shy to ask and i will try my best to make you understand the problem. Stay tuned for more project tutorials. Until next tutorial Take Care !! :)

11-Level 3-Phase Capacitor Clamped Inverter

Buy This Project

Hello friends, hope you all are fine and enjoying. Today i am going a new project tutorial which is 11-level 3-phase Capacitor Clamped Inverter. In my previous post 11 Level 3-phase Cascaded H-Bridge Inverter, we have designed the simulation of 3 phase 11 level inverter but the only difference was the method used in that project was cascaded H Bridge but today we are gonna see How to design an 11 level 3 phase inverter using clamped capacitors.

Now i am going to share a new and advanced bulk of knowledge about inverters with you people. Since we are going to design a 3-phase capacitor clamped inverter so, we need to design some algorithm which should be able to invert DC into AC at some High voltages and after inverting these DC voltages into AC, we will create a phase sequence and most importantly phase polarity between these three phases so they should be able to feed the load and must supply load current. It is a very interesting but a bit complicated project and now-a-days it has got a large no of industrial applications. The study about inverters and their implementation is the back bone of Modern Renewable Energy and it is the future of Power Generation. It is a MATLAB simulation based project so, any kind of hardware is not included in this tutorial. So what actually we are going to do is to design the complete simulation of the project and we will discuss every component and also each sub-component which will be used in Simulink MATLAB. So let's get started with 11 Level 3 Phase Capacitor Clamped Inverter:

11-level 3-Phase Capacitor Clamped Inverter

  • Capacitor Clamped inverters are commonly known as Flying Capacitor Technology and they were first purposed by Meynard and Foch.
  • Flying Capacitor includes no of series combination of Capacitor Clamped Inverter Switching Cells and these capacitors are used to get high voltages.
  • The general concept related to flying capacitor is that it can charge up to one-half of the DC voltages and then within the circuit they can automatically increase or decrease the voltages, according to our requirement.
  • The block diagram of the complete simulation of capacitor clamped inverter in MATLAB is given in the image below:
  • The complete block diagram of the Capacitor 3-phase clamped inverter is shown above. In this image, you can notice that we have 30 input pulses numbered as no.1 to no.30 .
  • So we can say that we have 30 DC input pins and these DC voltages will be inverted to get High Voltage AC.
  • If you double click on any input pulse then, a new window will open and it will be showing that source from which we are gaining input DC voltages.
  • We are gaining DC voltages from DC generators and a no of generators are connected in parallel to get HIGH voltage DC.
  • The block to which all the inputs are connected is in fact a Capacitor Clamped Bank.
  • In this bank, no. of capacitors are connected in series. Since a charged capacitor behaves as a voltage source and these capacitors are connected in series and their voltages adds up and in this way we get, HIGH voltages.
  • To look inside the block then double click on the block and a new window will open and it will be showing all the components which are fabricated in that block.
  • The internal structure of the block for capacitor clamped inverter is shown below in image:
  • In the above shown image, you can see that within the block, we have a no. of sub-blocks which are connected with each other.
  • To see what is in that small box, double click on that and a new window will open, which will be showing the internal structure of the each small box.
  • The internal structure of sub-block is shown in the image given below:
  • In the above given figure you can see that, in every block we have a MOSFETS which are connected with antiparallel diodes for capacitor clamped inverter.
  • Ideal IGBT or GTO transistors can also be used but as I explained the properties of MOSFET in the beginning, that we give pulse to its base and it becomes operational.
  • Once MOSFET has been triggered it keep conducting and in order to stop it, we will have to provide reverse voltage on its base to bring it to rest state.
  • Since we are going to generate High Voltages 3-phase AC, so we have applied 3 big blocks and from each block, only one phase will be generated.
  • After each big block, we have a summing junction on which voltages arrives and then we have applied two different types of voltage measuring devices.
  • One device measures the phase voltages of inverted AC voltages. It can also be seen from the above given block diagram that the meter on the above side, measures phase voltages of all the three phases appearing on the summing junction.
  • Now if you look closely then, you will observe that only one wire from each summing junction is coming to the meter and we also know that in order to measure phase voltages, we also need a neutral wire.
  • We can get neutral wire from common ground of the system and the voltage difference between a phase and a neutral wire will give us Phase voltages.
  • The below meter measures line voltages. Line voltages means the voltage difference between 2 phases. In our system we have three phases which are A, B and C respectively.
  • To measure line voltages, this meter measures potential difference between phases and NO neutral wire is included in it.
  • The line voltages will be AB, BC and CA.
  • The Phase voltages and Line voltages have much difference between them and each have their own applications.
  • For example to run the single phase House-Hold load we need phase voltages (voltage difference between a phase and a neutral wire).
  • Whereas in industries, we need Line voltages to run the 3-phase load.
  • Now run the simulation of this capacitor clamped inverter, and after completion now click on the scope for Line Voltages and you will get the below results:
  • Now for Phase voltages of capacitor clamped inverter, click on the scope for phase voltages and you will get the below results:

APPLICATIONS

All type of Inverters have a large no of applications and now a days they are focus of Research and modern studies. Inverters have also made us able to get power from Renewable energy sources like solar panels, wind mills etc. Some industrial based applications of inverters are given below:
  • The biggest advantage of inverters are that they give good power quality.
  • Due to good power quality motors can reach at High speed at High voltages without producing any harmonics.
  • They are used in power supply circuits.
  • Now-a-days inverter Air Conditioners are also available in market and due to their High Efficiency and low power rating their demand is much High.
  • ECU( electrical control unit) which carries out in-vehicle control also carries inverted circuits and it's demand is also accelerating these days.
Alright friends, that was all from today post. I hope you have learned something new today. If you have any question then don't hesitate to ask in comments. Stay tuned for more beneficial project tutorials. Until next tutorial Take Care !!! :)

Circuit Diagram of IR Sensor using 555 Timer

Hello everyone, hope you all are fine and having fun with your lives. Today's tutorial is quite simple and we will have a look at circuit diagram of IR sensor using 555 Timer. There are different types of IR sensors available in the market. IR is abbreviation of infrared and so they use infrared ray for detection of objects. There are many types of IR sensors with different functionality, but in all of them infrared rays are omitted from transmitter and are received by the receiver. and using these ray we can say whether an object is placed in the path or not.

Today we are gonna see how to design your own IR sensor using 555 Timer. We can also interface these IR sensors quite easily with any microcontroller like PIC Microcontroller , Arduino etc. I was also thinking of designing it in Proteus but Proteus doesn't have the IR leds in it so I couldn't do it. IR sensors available in market are quite costly ranging from 10$ to 100$ obviously they are also excellent in efficiency but in engineering cost efficiency also plays an important role so today we are gonna have a look at circuit diagram of IR sensor using 555 timer which will cost you just $2. Before going into the details, lets first have a look at types of IR sensors.

Types of IR sensors

  • There are normally two types of IR sensors available in market.
First Type of IR Sensors:
  • First type is transceiver IR sensor which has both transmitter and receiver in it. This type of IR sensor is used to detect the distance of object from the sensor.
  • In this type of IR sensors, rays are omitted from the transmitter and are reflected back after hitting some object and are captured by the receiver.
  • On the basis of the time taken by these rays to reflected back, we calculate the distance of the object from the sensor.
Second Type of IR Sensors:
  • In these types of IR sensors, transmitter and receiver are not on same chip but on seperate pieces.
  • These types of IR sensors are used for detection of object.
  • For example we need to count people entering in some room then we will place this IR sensor on the door of that room with transmitter on one end and receiver on the other.
  • So, now when some one will enter through the door , he will cut the IR beam and thus the IR light wont be received by the receiver and thus the sensor will know that someone entered.
  • These types of IR sensors are also used in electronic devices like TV remote etc.
In this tutorial we are gonna design this second type of IR sensor using 555 timer. so, lets get started.

Circuit Diagram of IR Sensor using 555 Timer

  • So, here we are gonna design the second type of IR sensor using 555 timer.
  • In this sensor we need to design both the transmitter and the receiver.
  • So, lets get started the transmitter.
  • Design the below circuit on some circuit board:
  • In the above circuit diagram of IR sensor, I have clearly mentioned all the values of components so that you can easily design it. Moreover there are two leds used in it, these are not simple leds. There are IR leds which emits IR rays. the range of this sensor will depend roughly on the number of leds you are gonna use here, as I used two leds.
  • So, now lets have a look at circuit diagram of receiver side.
  • On this side we have use IR led but that one is receiving and will received that IR rays coming from the transmitter IR leds.
  • These are quite simple in designing and you can design it without any trouble. Before going into PCB, its better if you first design them on some wero board or bread board.
  • Here's a manufactured piece of the above given circuit diagrams. The one with two leds is the transmitter and the other one is receiver.
 
  • The image is a bit blur, coz I was in a bit of hurry but they work perfectly fine. :)
  • That's all for today, will see you guys in the next tutorial. Till then take care!!!

LM317 Calculator

[LM317TEP] Hello friends, I hope you all are doing great. Today, I am going to share our new online tool which is named as LM317 Calculator. I am quite excited while posting this LM317 Calculator, as I was trying for a long time to post it but couldn't done it because of few problems. Anyways, its here now and is ready to be utilized. Its nothing but a simple LM317 Calculator. I have included two LM317 calculators posted above, one will be used to calculate the Vout while the other will be used to calculate the resistance (R1). You should have a look at Introduction to LM317, if you don't know much about it. LM317 is an IC regulator which is used to regulate the output voltage and its output voltage is regulated depending on the values of both the resistances attached at its output. Here's our first simple but awesome tool. :)

LM317 Calculator

  • First of all, let me give you some basic information of its circuit design.
  • You can check the basic circuit of LM317 in below figure:
  • You can see that we have Vin which is input voltage and then we have R1 = 510 ohm which is normally a fixed resistance and finally we have R2 which is a variable resistance.
  • Now, by changing the value of this variable resistance, you can change its output, this calculator will be used to calculate those values depending on the values of other two variables:
  • So here are these LM317 Calculators:
  •  The simple formula used for calculating the output voltage of LM317 is shown below:
  • Normally it is not required to use very specific output voltage and normally a predefined combination of resistors is used. Here's a list of normally available resistors, the output voltages for these resistor combination is shown in below table:
  • I have also designed a Proteus Simulation of LM317 which you can download from LM317 Voltage Regulator in Proteus.
  • Here's a screenshot of its working and you can see that the output voltage is quite less than input voltage:
So, that's all about LM317 Calculator. I hope you are gonna enjoy those tools. If you have any questions then you can ask in comments. Have a good day. Take care !!! :)
Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir