MATLAB Projects

Hello friends, hope you all are fine and having fun with your lives. Today, I am going to combine all of my MATLAB Projects in this post. I have posted quite a lot of projects on MATLAB but they are not well arranged that's why are not easily accessible. So, today I finally thought to combine all my MATLAB Projects and post their links in this post so that you guys can easily access all of them in one place just like Arduino , PIC Microcontroller Projects. All these MATLAB Projects and tutorials are designed and written by our team and we have done quite a lot of work in compiling these projects as you all know MATLAB is the most difficult and vast educational tool.

Most of these MATLAB Projects are free to use and users can easily download their codes from the respective project but few of them are not free but we have placed quite small amount on them so that engineering students can buy them easily. If you got problem in any of these tutorials, then ask in comments of that respective project and I will try my best to resolve your problems as soon as possible. Moreover, I am also gonna add more MATLAB Projects in future so I will keep on adding their links in this post so that we have complete record in one place. :) As I always say, other bloggers are welcome to copy these codes but do mention our blog link in your posts and help us grow. :) So, let's get started with MATLAB Projects:

Basics of MATLAB

These are basic tutorials on MATLAB and are essential for beginner to must read them once and then move on to next tutorials. In these tutorials, I have just shown some tricks of using MATLAB, so must read them once.

MATLAB Projects - Coding

These are coding based MATLAB Projects. In these projects, I have designed algorithms in m file of MATLAB software. If you have problem in any of these projects then ask in comments and I will resolve them.

Embedded MATLAB Projects

Simulink Projects

Below are given MATLAB Projects designed in Simulink. Simulink is an awesome simulation tool available in MATLAB and is used for designing complex projects. Till now, I haven't posted much simulations but I have plans to post more simulations in near future:

Inverters Simulation

Image Processing

Image Processing is one of the best tool of MATLAB software. We can perform any kind of image processing in MATLAB. Below are given image processing projects in MATLAB software.

Speech Recognition in MATLAB using Correlation

Hello friends, hope you all are fine and having fun with your lives. Today, I am going to share a tutorial on Speech Recognition in MATLAB using Correlation. Speech recognition is used in almost every security project where you need to speak and tell your password to a computer and is also used for automation. For example, I want to turn my AC on or off using voice commands then I have to use Speech Recognition. I have to make the system recognize that whether I am saying ON or OFF. In short, speech recognition plays a vital role in voice control projects. In today's post, I am gonna show you How to do Speech Recognition in Matlab and the technique I have used in this project is known as cross correlation. You should also have a look at Eye Ball Detection in MATLAB.

Correlation is normally used in signal processing, where you need to compare two signals and need to find the similarity between them. It is also known as the dot product of those two signals. Correlation has many uses and you can read more about it on its Wiki Page. Correlation is also used for pattern recognition like you want to find some pattern in the signal then you can use Correlation. Anyways, in our project, we are using correlation to find similarities between our stored signals and the testing signal. So, let's get started with Speech Recognition in MATLAB using Correlation.

Speech Recognition in MATLAB using Correlation

  • First of all, download this complete project by clicking the below button:
  • Now in this package, you will find nine audio wav files.
  • Five of them are the recorded sounds that are already feed in MATLAB.
  • Two are test files that will be recognized by the code.
  • The remaining two are success and failure files which will run if you got the recognition or not.
  • Let me explain the code a bit. First of all, what we need to do is to upload the first five training audio files in the software so and then we need to test these fives files with the test files and we need to check which one is a maximum match.
  • Here's the complete code:
function speechrecognition(filename)
voice=wavread(filename);
x=voice;
x=x';
x=x(1,:);
x=x';
y1=wavread('one.wav');
y1=y1';
y1=y1(1,:);
y1=y1';
z1=xcorr(x,y1);
m1=max(z1);
l1=length(z1);
t1=-((l1-1)/2):1:((l1-1)/2);
t1=t1';
%subplot(3,2,1);
plot(t1,z1);
y2=wavread('two.wav');
y2=y2';
y2=y2(1,:);
y2=y2';
z2=xcorr(x,y2);
m2=max(z2);
l2=length(z2);
t2=-((l2-1)/2):1:((l2-1)/2);
t2=t2';
%subplot(3,2,2);
figure
plot(t2,z2);
y3=wavread('three.wav');
y3=y3';
y3=y3(1,:);
y3=y3';
z3=xcorr(x,y3);
m3=max(z3);
l3=length(z3);
t3=-((l3-1)/2):1:((l3-1)/2);
t3=t3';
%subplot(3,2,3);
figure
plot(t3,z3);
y4=wavread('four.wav');
y4=y4';
y4=y4(1,:);
y4=y4';
z4=xcorr(x,y4);
m4=max(z4);
l4=length(z4);
t4=-((l4-1)/2):1:((l4-1)/2);
t4=t4';
%subplot(3,2,4);
figure
plot(t4,z4);
y5=wavread('five.wav');
y5=y5';
y5=y5(1,:);
y5=y5';
z5=xcorr(x,y5);
m5=max(z5);
l5=length(z5);
t5=-((l5-1)/2):1:((l5-1)/2);
t5=t5';
%subplot(3,2,5);
figure
plot(t5,z5);
m6=300;
a=[m1 m2 m3 m4 m5 m6];
m=max(a);
h=wavread('allow.wav');
if m<=m1
    soundsc(wavread('one.wav'),50000)
        soundsc(h,50000)
elseif m<=m2
    soundsc(wavread('two.wav'),50000)
        soundsc(h,50000)
elseif m<=m3
    soundsc(wavread('three.wav'),50000)
        soundsc(h,50000)
elseif m<=m4
    soundsc(wavread('four.wav'),50000)
        soundsc(h,50000)
elseif m<m5
    soundsc(wavread('five.wav'),50000)
        soundsc(h,50000)
else
   {soundsc(wavread('denied.wav'),50000)}
   
end
  • Now if you read the code from start then you can see, first of all, I uploaded the test file which I want to compare with my samples.
  • After that, I uploaded all 5 samples and also get their correlation with the test sample.
  • Finally, in the end, I compared the results and on the basis of it I figured out which one is the correct speech file.
  • You will also get spectrum graphs of your sound files as shown in the below figure:
  • It was quite an easy project and I have done it within half an hour and I hope you guys will understand.
  • If you got any problems then ask in the comments and I will resolve them.
  • Here's the complete video demonstration for this project and I hope it's going to help you out in understanding it.
That's all for today, and I think you have understood How to do Speech Recognition in MATLAB using Correlation. Will meet you guys in the next tutorial soon. Till then take care !!! :)

Image Zooming with Bilinear Interpolation in MATLAB

Hello friends, hope you all are fine and having fun with your lives. Today, I am going to share a simple tutorial on Image zooming with bilinear Interpolation in MATLAB. We have seen many software in which there's an option of zooming an image. For example, if you have used paint or photoshop then you have seen that you can zoom your image quite easily by clicking a button. Today's we are gonna do the same thing but in MATLAB and we will have a look at the code behind this feature.

Now, when we are zooming some image then in fact we are increasing the pixels of that image and in order to do that we have to fill those extra pixels with the color of their neighbor pixel. This thing is know as interpolation. There are many different techniques for interpolation and the one we are gonna use for this tutorial is known as Bilinear Interpolation. Bilinear interpolation is simple type of linear interpolation in which we simply apply interpolation formula on both the x and y axis. So, let's have a brief overview of Bilinear Interpolation first and then we will move on to MATLAB implementation.

What is Bilinear Interpolation ?

  • As I explained earlier, Bilinear Interpolation is a simple interpolation technique in which we fill the gaps between pixels using the neighbor pixels.
  • For example, we have an unknown pixel in between four pixels, and let's say the unknown pixel is f(x,y) and it is surrounded by four pixels which are:
    1. Q11 = (x1y1).
    2. Q12 = (x1y2).
    3. Q21 = (x2y1).
    4. Q22 = (x2y2).
  • All these four neighbor pixels are known , now by using Bilinear Interpolation we can find the values of this unknown pixel.
  • Now, first of all, we will move in the x direction only.
  • The formula used for Bilinear Interpolation for x factor is:
  • Now after calculating these x formulas, now we will move in y direction and the formulas are:
  • Now using these formulas we can quite easily find our unknown pixel f(x,y) using Bilinear interpolation. These formulas are taken from Wiki Page of Bilinear Interpolation and you can read more details about it there.
  • Now we have seen the Bilinear Interpolation so now let's move and see How to do Image Zooming using this Bilinear interpolation in MATLAB.

Image Zooming with Bilinear Interpolation in MATLAB

  • You can download the complete code by clicking the below button but also read the post, as I have explained this code in this remaining post.

Download MATLAB Code for Image Zooming

  • In order to do image zooming with Bilinear Interpolation in MATLAB, first of all, what you need to do is to read an image file, which I have done using this simple formula:
im0=imread('TEP.jpg');
im=cast(im0,'int16');
imshow(cast(im,'uint8'));
[h,v,d]=size(im);
  • So, in this above code, what we did is , we simply read the image file which I have named as TEP.jpg
  • After that I have converted this image file into int16 and then to uint8 and finally I get the size of this image file using size command.
  • After that I have applied a simple algorithm and have zoomed my image using below code:
for i=1:h
    for j=1:v
      im1(1+(i-1)*fac,1+(j-1)*fac,:)=im(i,j,:); 
    end
       imshow(cast(im1,'uint8')); 
end
  • Now in the above loop what we have done is we simply enhanced our image and named it as im1, I have used a variable fac, which is factor, its user defined like if you want to zoom image by 2 then factor will be 2.
  • Now we have enhanced our image, next thing we need to do is to apply the bilinear Interpolation on this complete image and we will get the result.
  • Here's the complete code for Image Zooming with Bilinear Interpolation in MATLAB.
function bilinear_zoom(fac)

im0=imread('TEP.jpg');
im=cast(im0,'int16'); 
imshow(cast(im,'uint8'));
[h,v,d]=size(im);

for i=1:h
    for j=1:v
      im1(1+(i-1)*fac,1+(j-1)*fac,:)=im(i,j,:); 
    end
       imshow(cast(im1,'uint8')); 
end

%bilinear interpolation
for i=1:1+(h-2)*fac     %row number
    for j=1:1+(v-2)*fac %column number
    
       if ((rem(i-1,fac)==0) && (rem(j-1,fac)==0)) 
       else  
           h00=im1( ceil(i/fac)*fac-fac+1,ceil(j/fac)*fac-fac+1,:); 
           h10=im1( ceil(i/fac)*fac-fac+1+fac,ceil(j/fac)*fac-fac+1,:);
           h01=im1( ceil(i/fac)*fac-fac+1,ceil(j/fac)*fac-fac+1+fac,:);
           h11=im1( ceil(i/fac)*fac-fac+1+fac,ceil(j/fac)*fac-fac+1+fac,:);
           
           x=rem(i-1,fac); %coordinates of calculating pixel.
           y=rem(j-1,fac);  
          
           dx=x/fac; %localizeing the  pixel being calculated to the nearest four know pixels.
           dy=y/fac;
          
           b1=h00;    %constants of bilinear interpolation.
           b2=h10-h00;
           b3=h01-h00;
           b4=h00-h10-h01+h11;           
           im1(i,j,:)=b1+b2*dx+b3*dy+b4*dx*dy; %equation of bilinear interpolation.
         end
        end
  imshow(cast(im1,'uint8'));
end

imshow(cast(im1,'uint8'));
imwrite(cast(im1,'uint8'),'zoomed_pic.jpg');
  • Now if you check in the Bilinear Interpolation code, we have applied the same equations which we have discussed in the above section.
  • The Image I have used for this code is as follows:
  • Now in MATLAB window, I have given this command bilinear_zoom(2) , where fac = 2, so I am increasing my image by factor 2. So it will be zoomed by 2 times.
  • Its the image from my 555 Timer post but as I have posted it recently so this image was on my desktop thats why I used it. :P
  • The result obtained is as follows:
  •  Now you can see the image has been zoomed and is now looking big and because of Bilinear Interpolation in MATLAB we haven't lost the in between pixels.
  • Here's a video for this tutorial, which will give you better idea of How to do Image Zooming with Bilinear Interpolation in MATLAB.
That's all for today, I hope you have enjoyed this post. Will meet you guys in the next tutorials soon. Till then take care. :)

Automatically Connect with Wifi SSID using Arduino YUN

Hello Friends, hope you all are fine and having fun. In today tutorial i am going to elaborate How to Automatically Connect with Wifi SSID using Arduino YUN. If you recall one of my previous tutorials named Getting started with Arduino YUN , in which i gave a brief introduction about Arduino YUN, its working and features. In that tutorial, I have explained How to connect Arduino YUN with Wifi manually. A little problem encounters while connecting Arduino manually to available wifi networks that if wifi connection drops then, then Arduino will also disconnect automatically and if wifi connection is energized again, it will still remain disconnected unless you reconnect it by yourself. This thing has very serious drawbacks in industrial projects, where data is continuously uploaded through multiple servers and if at any stage connection drops and Arduino stops working then, this thing leads to drastic outcomes.

So there is serious need to design an algorithm in which Arduino automatically connects to the available wifi connections and should enables the server to upload data through it. This whole process is a bit lengthy and much complicated. So, i will elaborate all this in the coming tutorials. In today's tutorial i am going to restrict myself only How to get Available wifi SSID using Arduino YUN. First of all lets recall the basics of Arduino YUN. Arduino YUN has 2 micro processors embedded on the same board. First is the Arduino microprocessor and the second is Atheros micro processor. Atheros supports Linux server (commonly used in Apple computers). With both these on-board micro processors, we can do anything we want to do. The beauty of Arduino board is that it has built in wifi, Ethernet port, USB host and SD card slot. We can also upload data into Arduino through wifi without physically connecting it with computer. That's why Arduino boards are the most widely used micro processors now a days, and are able to handle multitasking industrial projects. Above was a little introduction about Arduino YUN and now lets get started with our today's tutorial.

Automatically Connect with Wifi SSID using Arduino YUN

  • First of all open the Arduino softeare. On toolbar click on the icon named "Tools" and a new window will open. Then go to the option "Board" and from the next opened window select the board "Arduino YUN".
NOTE:
  • Remember you must download the Arduino software version 1.5.5 + instead of 1.0.3 because Arduino sketches will be only compiled in 1.5.5 version which is specifically designed for Arduino YUN.
  • After selecting the board, you will load the given below code into Arduino Board.
#include <Process.h>
#include <FileIO.h>

String ESSID = "TEP";            
String Pass = "Pakistan";            
String Encrypt = "psk2";
          
void setup() {

Serial.begin(9600);  
delay(5000);    
FileSystem.begin();
delay(5000);
Bridge.begin();  
delay(5000); 
}

void loop() {
// put your main code here, to run repeatedly:
    WifiAuthentication();
}



void WifiAuthentication()
{
      uploadScript();
      delay(1000);
      runScript();
      delay(20000);
}
void uploadScript() 
{
  
      File script = FileSystem.open("/tmp/setupwifi.sh", FILE_WRITE);   
      script.print("#!/bin/sh\n");
      script.print("/sbin/uci set  network.lan=interface\n");
      script.print("/sbin/uci set  network.lan.proto=dhcp\n");
      script.print("/sbin/uci delete  network.lan.ipaddr\n");
      script.print("/sbin/uci delete  network.lan.netmask\n");
      script.print("/sbin/uci set wireless.@wifi-iface[0].mode=sta\n");
      script.print("/sbin/uci set wireless.@wifi-iface[0].ssid=" + ESSID + "\n"); 
      script.print("/sbin/uci set wireless.@wifi-iface[0].encryption=" + Encrypt + "\n");
      script.print("/sbin/uci set wireless.@wifi-iface[0].key=" + Pass + "\n");
      script.print("/sbin/uci commit wireless; /sbin/wifi\n");
      script.print("/etc/init.d/network  restart\n");
      script.close();  
      Process chmod;
      chmod.begin("chmod");      
      chmod.addParameter("755");  
      chmod.addParameter("/tmp/setupwifi.sh");
      chmod.run();
}

void runScript() 
{
      Process myscript;
      myscript.begin("/tmp/setupwifi.sh");
      myscript.run();
      Serial.println("Connected");
}
  • The above given code is a bit complicated and it consists of many steps. Now i am going to show all the steps through a block diagram and then i will try to explain every step one by one.
  • Using this code, the Arduino YUN board will automatically connected to the available SSID which is in our case is TEP. So you can give any other SSID there and it will connect to that one.
  • In the above block diagram, you can see that first of all Initialize Serial Port. When you will connect Arduino YUN with your computer through cable or as i described earlier that Arduino YUN also have built-in wifi so you can also connect Arduino YUN with computer through wifi.
  • Then you will load the code to Initialize Serial Port, which is the first step and also shown in the above block diagram.
  • In this project we have kept Baud rate of Arduino YUN 9600.
  • The next step in the block diagram is to 'Initialize File System' . In this step we will load 'File System' into our code as viewed in the code image given above.
  • Now in the next step we have to initialize the Arduino YUN Bridge. The block diagram representing the internal structure of Arduino YUN is shown in the image below:
  •  As i stated earlier in the beginning of the tutorial that Arduino YUN has 2 on-board micro processors and Arduino YUN is the intermediate source who performs communication between both micro processors.
  • The Bridge library facilitates communication between the two processors, giving Arduino sketches the ability to run shell scripts, communicate with network interfaces, and receive information from the AR 9331 processor.
  • The USB Host is connected to the ATmega 32u4, while the all external interferences(like Wifi, Ethernet, SD card) are connected to Linux micro processor.
  • The beauty of this board is that Bridge libraries also enables the Arduino micr processor ATmega to communicate with the other interferences, which are also connected with Linux microprocessor.
  • When bridge has been activated then, Arduino YUN enables its wifi and search for the nearby available wifi connections.
  • When it will get some available wifi connections in its surrounding then, from its algorithm, Arduino YUN will get the SSID from that available wifi connections.
  • The next thing which we have implemented in the code is to get SSID String. It is a built in function and also available in Arduino libraries that if it gets any available wifi connection near it, then it automatically gets strings from those connections.
  • When Arduino has searched for all the available wifi connections near it and after getting the SSID of available wifi connections, it sends all these SSID to serial port of Arduino YUN board.
  • After that Arduino YUN will automatically connect to that wifi connection whose SSID matches with the given SSID.
  • Now the end step is very important and it distinguishes Arduino YUN from all other Arduino boards, which is, After sending data to serial port it again starts the loop and got o step #4 and it again starts to search for available wifi networks.
  • This phenomenon can also be verified from the above shown block diagram.
  • At any stage, if wifi connection drops then the loop will again start and will search for available wifi connections, get their SSID and it will send these SSID to serial port and it will rehabilitate the connection within no time and no problem will occur at any stage of data execution.
Alright friends, that was all from today's post. It is a very basic and very important post and we have seen How to Automatically Connect with Wifi SSID using Arduino YUN. I hope you have learned something new in today's post. If you have any problem in understanding any step of this tutorial then, you can ask in the comments and i will try my best to resolve the issue. Follow us to get the codes and simulations straight in your inbox. For more tutorial and projects, stay tuned and until next tutorial Take Care !!! :)

Electronic Quiz Project with 8051 Microcontroller

Hello friends, hope you all are fine. In today's project, we are gonna design Electronic Quiz Project with 8051 Microcontroller. I have done this project recently in which we need to design a quiz project game using 8051 Microcontroller. It was quite a big project and we have to work quite hard to make it done. In this project we have used many components on which I have already post tutorials so that you guys first get introduction to those components. So, first of all you should read Interfacing of LCD with 8051 Microcontroller, after that you must check Interfacing of Keypad with 8051 Microcontroller and finally get your hands on Serial communication with 8051 Microcontroller. These tutorial are must to read because these are all gonna use in today's project.

So, before going in details of this project, let me first tell you that its not free because we have done quite a lot of work in designing it so it will be of $20. We have placed quite a small amount as mostly it will be downloaded by the engineers students.You can download it by clicking the above button, but before buying it must read the details and also check the video posted at the end of this tutorial so that you know what you are buying. So, let's get started with the details of this project.

Overview of Electronics Quiz Project

  • Let's first have some overview of Electronic Quiz Project with 8051 Microcontroller.
  • In this project, I have designed a quiz game which has two modes in total named as:
    • Single Player.Mode
    • Two player Mode
  • In the start of this project, using keypad you have to select the Mode i.e. you wanna start Single player Mode or Two Player Mode.
  • Now let's check the details of each mode seperately:
Single Player Mode
  • When you select the single player mode then only one player can answer the questions.
  • In order to answer the questions, you have to use keypad.
  • The questions will be displayed on LCD.
  • The questions are in the form of MCQs so ti will have four options.
  • So,whenever the question is displayed on LCD, you need to use keypad to select the correct answer.
  • Rite now, I have added 6 questions in its database, which you can change easily or can also add more questions.
  • In single run, it will ask 3 random questions from the user and will get the answers.
  • For each correct answer, it will add the 5 marks and for each wrong answer it will subtract 2 marks.
  • After attempting all the 3 questions, it will display the final marks on the LCD screen.
  • Now you need to press any button to restart the system.
  • Below is given the Block diagram for the algorithm of Single Player Mode.
Two Player Mode
  • In two player Mode, there will be a competition between two players, in which first player will reply the question using keypad while the second player will reply the question using Keyboard which will come to the system via Serial port.
  • The question will be displayed on the LCD and the laptop at the same time, the question coming to laptop is via Serial port so you need to open some Serial Monitoring if you have designed it in hardware while in Proteus I have used Virtual Terminal to display the question.
  • Now after the question is displayed, system will wait for the response from both the players.
  • Now among the two players, who will press the 0 button first will be able to answer the question.
  • If he gave the correct answer, then 5 marks will be added in his total marks and if he gave wrong answer then 3 marks will be deducted.
  • IF the selected person given the wrong answer then the system will move to second user and will ask for the answer from him.
  • Now if the second user give the correct answer then 5 marks will be added in his marks and he give wrong answer then no marks will be deducted.
  • Total of three marks will be asked and at the end of these questions, marks of both players will be displayed and who got the maximum marks will be considered as a winner.
  • Now if you press any key, the system will restart.
  • The complete block diagram for the algorithm of two player mode is shown below:
Components Used
I have used below components in designing this project:
  • 8051 Microcontroller (AT89C51)
  • Keypad
  • LCD (20 x 4)
  • Serial Communication
  • Laptop or PC
So, now let's have a look at the Proteus Simulation and working of Electronic Quiz Project with 8051 Microcontroller.

Electronic Quiz Project with 8051 Microcontroller

  • So, now we have the detailed overview of Electronic quiz project with 8051 microcontroller. Let's design its Proteus Simulation.
  • Design a circuit in Proteus as shown in below figure:
 
Programming Code
  • I have designed the programming code in Keil uvision 3 for Electronic Quiz Project with 8051 Microcontroller.
  • I am not gonna share the complete code here because its not free but you can buy it quite easily by clicking the below button for just $20.
  • But I am gonna explain the code in chunks so that you get some idea How I am doing this Electronic quiz project with 8051 Microcontroller.
  • First of all let's have look at lcd code. In my previous post I was writing character by character on LCD because it was quite a small project, but now I have to print quite a lot of string so that's why I have written a function to which you can give any string and it will print it on LCD. The function is as follow:
void writeline_lcd(char line[])
{
   		int i;
   		for(i=0;i<strlen(line);i++)
   		{ writedata(line[i]); } //write to lcd
   
}
  • Using this function, you can easily write complete string on LCD.
  • Next in order to send data to Serial Port I have used the below function:
void writeline_serial(char line1[])
{  
   int i;
   EA = 0; ES = 0;
   for(i=0;i<strlen(line1);i++)
   { SendByteSerially(line1[i]); } // SEND DATA TO PC 
   EA = 1; ES = 1;
}
  • For storing the questions I have used the below function:
void Ask_Question(void)
{
	int q = 13;
	writecmd(0x01);
	
	//randomize question
	while(!(q<7 & q>-1))
	{
		q = (TL1%6);
		if(q1==1 & q==1)  { q = 6; }
		if(q2==1 & q==2)  { q = 4; }
		if(q3==1 & q==3)  { q = 5; }
		if(q4==1 & q==4)  { q = 6; }
		if(q5==1 & q==5)  { q = 2; }
		if(q6==1 & q==6)  { q = 3; }
	}

	switch(q)
	{
	case 1:  q1=1; writeline_lcd("3,8,15,24,35..."); newline2(); writeline_lcd("51  48  46  42"); Return();
			 if(mode=='1') { writeline_serial("3,8,15,24,35...   options are (1)51  (2)48  (3)46  (4)42"); } break;
	case 2:  q2=1; writeline_lcd("6,14,18,28,30..."); newline2(); writeline_lcd("32  46  42  28"); Return();
			 if(mode=='1') { writeline_serial("6,14,18,28,30...   options are (1)32  (2)46  (3)42  (4)28"); } break;
	case 3:  q3=1; writeline_lcd("4, 1, 0, 1, 4..."); newline2(); writeline_lcd("1   3   9   0"); Return();
			 if(mode=='1') { writeline_serial("4, 1, 0, 1, 4...   options are (1)1  (2)3  (3)9  (4)0"); } break;
	case 4:  q4=1; writeline_lcd("-1, 4, 1, 6, 3..."); newline2(); writeline_lcd("8   10   5   7"); Return();
			 if(mode=='1') { writeline_serial("-1, 4, 1, 6, 3...   options are (1)8  (2)10  (3)5  (4)7"); } break;
	case 5:  q5=1; writeline_lcd("10,21,33,46,60..."); newline2(); writeline_lcd("88   73   65   75"); Return();
			 if(mode=='1') { writeline_serial("10,21,33,46,60...   options are (1)88  (2)73  (3)65  (4)75"); } break;
	case 6:  q6=1; writeline_lcd("1-1+1-1+...inf=?"); newline2(); writeline_lcd("0   1   1/2   -1"); Return();
			 if(mode=='1') { writeline_serial("1-1+1-1+...inf=?   options are (1)0  (2)1  (3)1/2  (4)-1"); } break;
	}
	
	q_no = q;
}
  • This same function is also used for asking the questions, I simply call this function when I need to ask the question.
  • These are the main functions used in this project. Another important function is the cchecking answer function, which I am not sharing here. this function is used to check the reply i.e. the answer is correct or not.
  • After that there is another function which is result function. This function calculate the result and display it on LCD.
  • Now once you have the code compile it and get the hex file.
  • Upload that hex file in your 8051 Microcontroller and run your simulation.
  • The first screen you will get is as follow:
  • After a delay of some seconds, it will ask for Mode Selection as follows:
  • Now, you need to give 0 if you want to select Single Player Mode or 1 if you want to Select Two Player Mode and the game will start.
  • I am not adding more images as the post will become quite long so I have made a video given below which will give you detailed working of this project.
So, that's all about Electronic quiz project with 8051 Microcontroller, I hope you have enjoyed this post. So let's meet in the next tutorial. Till then take care !!! :)

Power Factor Measurement Using Microcontroller

Buy This Project Hello friends, hope you all are fine and having fun. Today's post is about Power Factor Measurement using Microcontroller in Proteus ISIS. As usual, I have this project simulation in which I have to simulate a power factor measuring project using atmega microcontroller. So, I use atmega8 microcontroller and the used Proteus ISIS as the simulating software. Power Factor Measurement isn't that difficult but its a quite tricky and in today's post we are gonna cover it in full detail.

There are many ways for power factor measurement and today's the method we are gonna use is called zero crossing detection. We will first detect the zero crossing of our signal and then we are gonna do the power factor measurement based on the detection of zero crossing of our voltage and current signal. Seems bit difficultdon't worry we are gonna do everything and in quite full detail so stay with me and enjoy the tutorial. But before going into the details of power factor measurement, let's first discuss the basics of power factor measurement because before that you wont understand a bit.

We have designed this simulation after quite a lot of effort so its not for sale but has a quite small cost of $20 so that engineering students can buy it easily. You can buy the simulation along with hex file and code by clicking on the above button and it will lead you to Product page of this product. So, let get started with it.

Basics of Power Factor

  • In AC circuits, there are total three types of loads which are normally bear by an AC current, named as:
    • Resistive Loads.
    • Capacitive Loads.
    • Inductive Loads.

We are all quite well aware of these and if you are not then I must say you wont read further and must first get some basic knowledge about these loads. Among these three loads Resistive loads are known as the most decent loads as they don't mess up with the current and just simply let the current pass through it and that's why there's no such power loss in these types of loads. But when it comes to Capacitive or Inductive loads. they are quite disturbing types of loads and hence they don't let the current easily pass through them and slightly distort the current signals. In case of Capactive loads, the current waveform got ahead of the voltage waveform and hence got a lead angle. In other words, current waveform leads the voltage waveform. While in case of Inductive loads, the scenario is quite the opposite. In Inductive loads, current waveform lags the voltage waveform. The below figure shown the difference between these loads output.

  • In the above figure, Red waveform is showing the current wave, while the green waveform is showing the voltage wave. So its quite obvious from above three figures that in case of resistive load there's no angle difference but in case of capacitive load, current waveform leads the voltage waveform while in Inductive load current waveform lags the voltage waveform and in this case I have used a constant angle of 60 degrees for both capacitive and inductive loads.
  • Now because of this angle difference there's quite an energy loss which is not quite good for any system so the best scenario for any system is that this angle should be 0 which is the case of resistive loads.
  • Now question is why we are reading this stuff while we are actually interested in power factor measurement so yes now I am coming towards it.
  • Power Factor is simply the cosine of this leading or lagging angle. In simple words, if you get this leading or lagging angle between current and voltage waveform, which in the above figure is 60 degrees, and then take the cosine function of that angle, you will get the Power factor for your system.
  • So, if we calculate the power factor for the above waveform, for which the leading or lagging angle (both) are 60 degrees, then we get:

Power Factor = Cos ( 60 degrees )

Power Factor = 0.5

  • So, the power factor of our above system is 0.5 which is quite bad.
  • Now, whats the meaning of this 0.5 power factor, it means that our system's efficiency is 50% and the energy dissipation is also 50% so our system's efficiency is as well 50%.
  • So, if we want to improve our systems' efficiency, then we need to increase the Power Factor of our system.
So, now we have seen the basics of power factor and have got quite an idea about what is it so now let's start with how to measure power factor using Microcontroller in Proteus ISIS.

Power Factor Measurement with Zero Crossing Detection

  • There are many methods available for Power Factor measurement and in this post we are gonna use the zero crossing detection in order to measure it .
  • As we all know, the voltage and current waveform are basically the sine waves so they must cross the zero point at some time.
  • And what we need to do is to detect the zero crossing of both these waves. So, first of all we are gonna do this in Proteus.
  • So, design a circuit in Proteus for Power Factor Measurement as shown in below figure:
 
  • In the above circuit design, I have used two voltage sources which are U2 and U3, I have considered U2 as the voltage transformer while the U3 as the current transformer, when you are designing the actual circuit in hardware then you need to use the current and voltage transformer.
  • The reason why we need to use CT and PT is because the normal voltage is normally of 220V or 110V which we can't directly give to our microcontroller because it will burn our microcontroller.
  • So, we need to lower this voltage level and needs to bring it to such level which is easily operatable by microcontroller, which in normal case is below 5V.
  • So, now I suppose you have used the CT PT and you are getting your current and voltage waveforms in the order of 5V but now again there's another issue that the voltage we are getting is AC while our microcontroller works on DC so we need to find some way to convert this AC into DC.
  • So,in order to do, I have used this 8 pin amplifier LM358 as a comparator.
  • What LM358 is doing ?? Its simply comparing the voltage coming at its inverting pin to the voltage at its non inverting pin and whenever both voltages match it will send a HIGH pulse to the output.
  • You can see clearly that I have placed a GND on the non inverting pin of LM358 so whenever we get zero crossing on the inverting side it will send us a HIGH pulse at output.
  • That's how we are converting our AC signal into DC signal as well as detecting the zero crossing. Let's have a look at these waveform in Oscilloscope.
  • The below two waveform are the current and voltage waveform, red one is current while the green one is voltage and I have placed a lagging angle of 30 degrees that's why current waveform is lagging the voltage waveform.
  • While the above two waveform are the output of LM358 and we can see clearly they are giving the high peaks when the lower waveform cut their zero axis.
  • So that's how we are doing the zero crossing detection.
  • We have got the zero crossing detection and now what we are gonna do in programming is to first detect the zero crossing of current waveform and then we will start counting the time until we get the zero crossing of voltage waveform.
  • So, basically what we are gonna do is we are gonna count the time difference between current wave and voltage wave zero crossing.
  • When we got the time difference between these two waves, we can get the angle quite easily using the below formula.
  • We have got the time difference and we have already know the frequency of our system which is normally 50 HZ or 60Hz.

Power Factor Measurement Using Microcontroller in Proteus

  • Now we have already detected the zero crossing so now next thing is to calculate the time difference which we are gonna do in our microcontroller.
  • So, in order to do the time calculation, first of all we will detect the zero crossing of current wave.
  • Then we will start a timer which will start counting and we will stop this counting when we get the voltage curve.
  • So, in order to do these tasks, I have used the below code:
void pf_func(){
while(1)
{
       if ( PINC.4==1 )
       {
           TCNT1=0;
           TCCR1B = 0x01;
           break;
       }
       else {
               continue;
             }
}
while(1){
     if ( PINC.3 == 1 ){
     TCCR1B = 0x00;
     g=TCNT1;
     break;
}
else {
continue;
}
}
}
  • Now, when we detect the zero crossing of current waveform, we simply start the timer and start counting and when we get the zero crossing of voltage waveform, we simply stop the counter and we get the total time difference between the current waveform and the voltage waveform.
  • Now, next thing we need to do is to calculate the power factor, which is now quite easy because we already got the time difference.
  • So, what I do in order to do that is simply used the below simple code:
int powerfactor(){
k=0;
// To complete number of counts
g=g+1; //Value from the timer
//To convert into seconds
pf=(float)g/1000000;
//To convert into radians
pf=pf*50*360*(3.14/180);
//power facor
pf = cos(pf);
//power factor into percentage
k=abs(ceil(pf*100));
return k;
}
  • So, that's how we are calculating the Power factor.
  • We have done quite a lot of effort to design this simulation and code so its not for free but you can getit easily just for a price of $20.
  • Now when you get the code then make your hex file and upload it in Proteus.
  • Now run your Proteus simulation and you will get something like this:
  • In the above figure, current waveform leads the voltage waveform by 30 degrees and that's why we are getting a power factor of 0.87 which is 87%.
  • Now let me reduce the difference between current and voltage waveform to 0 and we will get a power factor of 1 as shown below:
  • Now, you have seen as we reduced the distance between current and voltage waveform the power factor has increased and as the angle between current and voltage waveform is 0 so its 100%.
That's all for today, I hope you have enjoyed today's post on Power Factor Measurement. You can buy the complete simulation along with hex file and the complete code by clicking on below button.

Buy Power Factor Simulation

So, buy it and test it and hopefully you will get something big out of it. So that's all about Power Factor Measurement using Atmega. I will post it on Arduino as well quite soon and may be on PIC Microcontroller as well. So, till next tutorial take care !!! :)

How to use 18B20 in Proteus ISIS

Hello friends, hope you all are fine and having fun with your lives. In today's post we are gonna have a look at How to use Temperature Sensor 18B20 in Proteus ISIS. I will use Arduino board as a microcontroller and will connect the temperature sensor with it and then will display the code on LCD. I have already posted the same tutorial in which I have done Interfacing of Temperature Sensor 18B20 with Arduino but in that project I have used the real components and designed the hardware. But today, I will just show you the simulation so that you could test the simulation first and then design it in hardware.

Temperature Sensor 18B20 is the most commonly used temperature sensor. Its a one wire sensor means it sends data through a single wire and we can connect multiple sensors with a single wire, that's why its quite efficient and easy to use as well. I have also posted a tutorial on How to Interface LM35 sensor with Arduino in Proteus ISIS which is another temperature sensor so give it a try as well and let me know which one you think is better. Anyways let's get started with temperature sensor 18B20 in Proteus ISIS.

How to use 18B20 in Proteus ISIS ???

  • First of all, get these components from Proteus components list as shown in below figure:
  • Now design the circuit as shown in below figure:
  • As you can see in above simulation, we have used Arduino UNO board along with LCD and 18B20 temperature sensor.
  • 18B20 in Proteus can't detect the real temperature but we can change the temperature by pressing + and - buttons.
  • So, now we have interfaced the temperature sensor and the LCD with Arduino. Next we are gonna design the code for Arduino and will upload it in Arduino baord.
Note:
  • Now download these three libraries, one is "one wire" library which is the protocol for 18B20 temperature sensor, next is the Dallas Temperature sensor library which is the actua library for temperature sensor 18B20 and uses one wire library. Third library is the Crystal LCD library which is used for displaying character on LCD.
  • So, download all these three libraries by clicking on below buttons and then paste them in your libraries folder of Arduino software.

Download One Wire LibraryDownload Dallas Temperature LibraryDownlaod Liquid Crystal Library

  • Now after adding these libraries, open your Arduino software and paste the below code into it.
    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include <LiquidCrystal.h>

    #define ONE_WIRE_BUS 6
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
 
    void setup(void)
    {
    Serial.begin(9600);
    Serial.println("Welcome to TEP !!!");
    Serial.println("www.TheEngineeringProjects.com");
    Serial.println();
    sensors.begin();

    lcd.begin(20, 4);
    lcd.setCursor(5,0);
    lcd.print("Welcome to:");
    lcd.setCursor(1,2);
    lcd.print("www.TheEngineering");
    lcd.setCursor(4,3);
    lcd.print("Projects.com");
    delay(5000);
    }

    void loop(void)
    {
    sensors.requestTemperatures();
    Serial.print("Temperature : ");
    Serial.println(sensors.getTempCByIndex(0));
    //lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Temperature: ");
    lcd.print(sensors.getTempCByIndex(0));
    lcd.print("C");
    delay(1000);
    }
  • Now get your hex file from Arduino and upload it to your Proteus Arduino board and hit the RUN button.
  • If everything goes fine then you will something like this at the start:
  • After a delay of around 5 sec you will start receiving the Temperature sensor 18B20 values on your LCD as shown in below figure:
  • Now you can see the value shown in the temperature sensor is the same as in LCD.
  • So, now by clicking the + and - buttons on temperature sensor, you can increase and decrease the value of temperature and same will be changed in LCD.
That's how you can do simulation of Temperature sensor 18B20 in Proteus ISIS. Its quite simple and easy to use. That's all for today, hope you get some knowledge out of it.

Color Detection in Images using MATLAB

Hello friends, hope you all are fine and having fun with your lives. In today's tutorial, we are gonna see Color Detection in Images using MATLAB. In the previous tutorial, I have posted about How to Detect Circles in Images using MATLAB in which we have detected objects based on their geometrical figure means either they are circle or not but today we are gonna distinguish objects based on their color i.e. whether they are red colored or green colored etc. Its a quite simple tutorial and comes in the basic category. We will first detect the color and then will create a boundary around that object and will also show its XY coordinates as well.

Image processing is an important tool of MATLAB. We can quite easily do the image processing in it using Image Processing toolbox so you need to make sure that your MATLAB must have Image processing toolbox before running this code. You should also have a look at these MATLAB Image Processing Projects. So, let's start with the project.

Color Detection in Images using MATLAB

  • In order to do the Color Detection in Images using MATLAB, first thing we are gonna need is the image itself. :P
  • So, I designed an image in paint which has different shapes in different colors as shown in below figure:
  • As you can see in the above figure, there are different shapes in different colors so now we are gonna detect these objects on the basis of their color.
  • Now use the below code and add it in your MATLAB m file, if you are new to m File then have a look at How to Create m File in MATLAB.
  • If you wanna protect your code in m File then you should read How to Protect code in m File.
    data = imread('TEP.jpg');
    diff_im = imsubtract(data(:,:,2), rgb2gray(data));
    %Use a median filter to filter out noise
    diff_im = medfilt2(diff_im, [3 3]);
    diff_im = im2bw(diff_im,0.18);
    
    diff_im = bwareaopen(diff_im,300);
    
    bw = bwlabel(diff_im, 8);
    
    stats = regionprops(bw, 'BoundingBox', 'Centroid');
    
    % Display the image
    imshow(data)
    
    hold on
 
    for object = 1:length(stats)
        bb = stats(object).BoundingBox;
        bc = stats(object).Centroid;
        rectangle('Position',bb,'EdgeColor','r','LineWidth',2)
        plot(bc(1),bc(2), '-m+')
        a=text(bc(1)+15,bc(2), strcat('X: ', num2str(round(bc(1))), ' Y: ', num2str(round(bc(2)))));
        set(a, 'FontName', 'Arial', 'FontWeight', 'bold', 'FontSize', 12, 'Color', 'black');
    end
    
    hold of
  • Now, run your m file and if everything goes fine then you will get an image as shown in below figure:
  • You can see in the above figure, we have only detected the shapes with green color.
  • The + sign indicates the center of each detected shape.
  • X and Y are the x,y coordinates of the center point of each shape which are shown in black for each detected shape.
  • Now, let's detect the red color in above figure, so in order to do so what I need to do is to simply change the third value in imsubtract function from 2 to 1.
  • The complete code for red color detection in MATLAB is shown below:
    data = imread('TEP.jpg');
    diff_im = imsubtract(data(:,:,1), rgb2gray(data));
    %Use a median filter to filter out noise
    diff_im = medfilt2(diff_im, [3 3]);
    diff_im = im2bw(diff_im,0.18);
    
    diff_im = bwareaopen(diff_im,300);
    
    bw = bwlabel(diff_im, 8);
    
    stats = regionprops(bw, 'BoundingBox', 'Centroid');
    
    % Display the image
    imshow(data)
    
    hold on
 
    for object = 1:length(stats)
        bb = stats(object).BoundingBox;
        bc = stats(object).Centroid;
        rectangle('Position',bb,'EdgeColor','r','LineWidth',2)
        plot(bc(1),bc(2), '-m+')
        a=text(bc(1)+15,bc(2), strcat('X: ', num2str(round(bc(1))), ' Y: ', num2str(round(bc(2)))));
        set(a, 'FontName', 'Arial', 'FontWeight', 'bold', 'FontSize', 12, 'Color', 'black');
    end
    
    hold off
  • Now, when you run this code in MATLAB, you will get the output as shown in below figure:
  • Now instead of detecting the green shapes, it has now detected the red shapes in MATLAB.
  • And have also shown their x,y coordinates in black color.
  • Now, finally let's detect the blue color, in order to do, you now just need to change the third parameter to 3 and it will detect the blue color as shown in below figure:
  • That's all for today, and I think its quite an easy one as I mentioned earlier this one is quite basic tutorials. Thanks for reading and I hope it will help you in some ways. :)

Detect Circles in Images Using MATLAB

Hello friends, hope you all are fine and having fun with your lives. In today's post we are gonna see How to detect Circles in Images using MATLAB. It's quite a simple and basic tutorial but quite helpful as today I was working on a project in which I need to do so but all the codes available online were for detection and tracking of circles in live images. So, I thought to share this one on our site. I have also posted another tutorial Color Detection in Images using MATLAB, so I think its better if you check that one as well.

We all know about MATLAB, which is a great tool for image processing and quite easy as it has a strong Help section. I haven't posted much tutorials on MATLAB in my blog so from now on I am gonna post tutorial on MATLAB as I get many requests about it. If you have any requests then use our Contact form and send them to us and I will try my best to postrelated tutorials. I personally prefer OpenCV over MATLAB, when it comes to image processing but in OpenCV there's not much flexibility as in MATLAB. Anyways, let's start our tutorial which is How to Detect Circles in Images using MATLAB.

Detect Circles in Images Using MATLAB

  • First of all, you are gonna need an Image, in which you are gonna find circles so I used this image of a bike.
  • As we can see there are two circles in the above image, which are two tyres, so we are gonna detect them now.
  • So, copy the below code and paste it in your MATLAB m file.
ImagePath='TEP.jpg'; %Give Path of your file here
Img=imread(ImagePath);

Img=im2bw(Img(:,:,3));  
Rmin=70;
Rmax=100;  
[centersDark, radiiDark] = imfindcircles(Img, [Rmin Rmax], ...
                                        'ObjectPolarity','bright','sensitivity',0.90)
imagesc(Img);
hold on
viscircles(centersDark, radiiDark,'LineStyle','--');
hold off
  • Now, when you run this code you will get something as shown in below figure:
  • As you can see in the above figure, both the circles are now detected and are marked with red and white line.
  • The command, I have used for detecting these circles is imfindcircles , where Rmin and Rmax are the minimum and maximum radius of the circles.
  • It will detect only those circles which will lie in this range and other circles will be ignored.
  • Moreover, the last parameter is for setting the sensitivity of circle detection, which I have given is 0.90.
  • It will also give the center of these circles along with their radii in the command window as shown in below figure:
  • As, we have detected two circles so the command window is showing the X, Y coordinates of both these circles along with their radii.
  • Now test it and also change the minimum and maximum ranges and you will see you are gonna detect more circles.
It was quite easy but if you have problem in it then ask in comments and I will try my best to solve them. That's all for today, will meet in next tutorial. Till then take care !!! :)

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 !!! :)

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