Ultrasonic Sensor Simulation in Proteus
Hello friends, a few days ago I posted an Ultrasonic Sensor Library for Proteus, using which one can easily simulate ultrasonic sensor in Proteus. The post was highly praised by the reader and I have received quite good feedback from the followers. So, I thought of sharing some more examples related to it so that users can get a complete understanding of how to use Ultrasonic sensors in Proteus. Today, we are gonna have a look on different Ultrasonic Sensor Simulation in Proteus. If you haven't read the previous post then first have a look at it because without the installation of Ultrasonic Sensor Library in Proteus, you won't be able to use these examples. Ultrasonic Sensor is used widely in Embedded Systems.
Today, I am gonna share three examples of Ultrasonic Sensor Simulation in Proteus, which will be enough for you guys to get the overview of this sensor. I have also attached these simulations below and you can easily download them but as I normally advise, it's better to design these simulations by yourself and write your own code as it will help you understand it more clearly. If you don't make mistakes, you won't learn from it. I am gonna share below three examples of Ultrasonic Sensor:
Note:
- Other Proteus Libraries are as follows:
- I have also posted more examples on Ultrasonic Sensor Simulation in Proteus, have a look at them and you will get complete understanding of this sensor.
- Moreover, for hardware implementation of Ultrasonic Sensor with Arduino, check below posts:
Ultrasonic Sensor Simulations in Proteus using Button
- In this tutorial, we are gonna use three buttons and using these buttons we will control our ultrasonic sensor.
- Think of these buttons as three obstacles, which are placed at different distances, if we hit the first button then first obstacle is reached, if we hit second then second obstacle and same as for third.
- So, open your Proteus ISIS and if you have already installed ultrasonic library for Proteus then design your Ultrasonic Sensor Simulation in Proteus as shown in below figure:
- Now open your Arduino software and paste below code in it and get your hex file to upload in this simulation.
Note:
const int pingPin = 7; const int echoPin = 6; void setup() { Serial.begin(9600); } void loop() { long duration, inches, cm; pinMode(pingPin, OUTPUT); digitalWrite(pingPin, LOW); delayMicroseconds(2); digitalWrite(pingPin, HIGH); delayMicroseconds(10); digitalWrite(pingPin, LOW); pinMode(echoPin, INPUT); duration = pulseIn(echoPin, HIGH); inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100); } long microsecondsToInches(long microseconds) { return microseconds / 74 / 2; } long microsecondsToCentimeters(long microseconds) { return microseconds / 29 / 2; }
- After adding the hex file in this simulation, hit the RUN button and if everything goes as expected then you will get a simulation as shown in the below figure:
- You can download this simulation along with Arduino code and the hex file by clicking below button:
Download Ultrasonic Sensor simulation in Proteus Using Button
Ultrasonic Sensor Simulations in Proteus as Proximity Switch
- I have explained the first example in detail so I am not gonna much explain this one.
- In this example, we are using the Ultrasonic Sensor as a Proximity Switch, whenever any obstacle comes in the way of ultrasonic sensor, it will automatically give an indication.
- As you can see from the figure below that we are using a variable voltage source for the analog pin of ultrasonic sensor.
- So, first of all design a simulation as shown in the below figure:
- Now upload the Arduino hex file for this example, which is attached below along with the code and this simulation.
- After uploading the hex file, hit the RUN button and if everything is in your favor, then you will see results similar to below figure:
- As you can see in the above figure, we are sending a Ping from Ultrasonic Sensor and in the programming code we have placed an alarm at a specified distance, so whenever any object comes in that range, our program will give us Alarm, you could also use Buzzer in Proteus.
- You can download this Proteus Simulation along with Arduino Code and hex file by clicking on this below button:
Download Ultrasonic Sensor Simulation in Proteus As Proximity
Ultrasonic Sensor Simulations in Proteus using Switch
- Here's the third and last example of Ultrasonic Sensor simulation in Proteus.
- In this simulation, we are using a switch and controlling the Ultrasonic with that Switch.
- There are total four states for that Switch, which determines what should be the voltage on the analog pin of Ultrasonic Sensor.
- I have also placed a oscilloscope in this simulation which will give you the voltage state for this switch, to get you an idea what's the voltage pattern coming to ultrasonic sensor, its mainly just for understanding and testing.
Note:
- Now upload your Arduino hex file in it and hit the RUN button and you will see something like this:
- As you can see above, the virtual terminal is showing the distances while the oscilloscope is giving us state of switch, play with it and you will learn more and if still confused then ask in comments.
- You can download the Proteus simulation of this example along with Arduino hex file and code by clicking on the below button.
Download Ultrasonic Sensor Simulation in Proteus Using Switch
That's all for today, hope you guys have learn something today, if you have any problem or question, do ask in comments and I will try my best to resolve them. Take care :)
Ultrasonic Sensor Library for Proteus
Hello friends, hope you all are fine and having good health. In today's post, I am going to share an Ultrasonic Sensor Library for Proteus. A few days ago, I posted a tutorial on Arduino Library for Proteus, and today I am going to share the new Ultrasonic Sensor Library for Proteus. Using this library, you can easily interface Ultrasonic Sensors with different Microcontrollers like Arduino, PIC Microcontroller etc.
First of all, let's have a brief introduction to ultrasonic sensor. In an ultrasonic sensor, there are two nodes available, one is the transmitter while the other is the receiver. The transmitter sends an ultrasonic wave and this wave strikes any hindrance present in front of it and then bounces back. This bounced ultrasonic sensor is then captured by the receiver and on the basis of the time taken by this wave to return, the sensor calculates the distance of that obstacle from that sensor.
The Ultrasonic sensor is usually used for detecting the obstacle in the path and also to find the distance between the sensor and the obstacle. The ultrasonic sensor normally used is HC-SR04, which we have designed in this library. Let's get started with Ultrasonic Sensor Library for Proteus, in this library we have used an extra pin on the ultrasonic sensor, which is an analog pin. The voltage on that pin is used to detect how close an object is because it's a simulation and we can't place an actual object in front of the simulated sensor. Moreover, you should also have a look at this Home automation Project using XBee & Arduino, I have used this ultrasonic sensor in that project.
I hope you are going to enjoy this library. This library is designed by our team after a lot of effort, if you have any feedback to improve, please let us know. So, let's get started with Ultrasonic Sensor Library for Proteus and its interfacing with Arduino.
Note:
- Other Proteus Libraries are as follows:
- Moreover, for hardware implementation of the Ultrasonic Sensor with Arduino, check below posts:
- I have also posted more examples of Ultrasonic Sensor Simulation in Proteus, have a look at them and you will get a complete understanding of this sensor.
Ultrasonic Sensor Library For Proteus
- First of all download this Ultrasonic Sensor Library for Proteus, by clicking on the below button.
Ultrasonic Sensor Library for Proteus
- In this ultrasonic sensor library for Proteus, you will find three files which are:
- UltrasonicTEP.IDX
- UltrasonicTEP.LIB
- UltrasonicTEP.HEX
- Now, place these three files in the library folder of your Proteus software.
Note:
- Now start your Proteus software and in the components list, search for the Ultrasonic sensor and place it in your workspace as shown in the below figure:
- Now we have our ultrasonic sensor in Proteus but if you run it then it won't work as we haven't yet added any functionality in it.
- So, in order to add the functionality double click this ultrasonic sensor and open its properties.
- In properties, select the Program File section and browse to UltrasonicTEP.HEX file and upload it as shown in below figure:
- Now our ultrasonic sensor is ready to be used.
- Now let's make a simple example for an ultrasonic sensor, so that you get an idea of how to use it in Proteus.
Ultrasonic Simulation in Proteus
- After adding the Ultrasonic Sensor Library for Proteus, open your Proteus ISIS software or restart it, if it's already open.
- Now search for the below components in the Proteus Components Library and add them in your workspace as shown in the below figure.
Components Used
Here's the list of components, which I have used for designing this Proteus Simulation:
Proteus Simulation
- After adding these components, now design a simulation as shown in the below figure:
- Now in this example, I am receiving data from Ultrasonic Sensor and then printing this data over Virtual Terminal in Proteus, if you are not much familiar with Virtual Terminal, then read How to use Virtual Terminal in Proteus ISIS.
- Now open your Arduino software and paste the below code in it and compile it to get the hex file, read Arduino Library for Proteus to know how to get the Arduino Simulation in Proteus.
- You must also read How to get the hex file from Arduino Software.
const int pingPin = 7; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 6; // Echo Pin of Ultrasonic Sensor
void setup()
{
Serial.begin(9600); // Starting Serial Terminal
}
void loop()
{
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(10);
digitalWrite(pingPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}
- It's quite a simple code and is self-explanatory, if you still got some trouble then ask in the comments and I will reply to them. I have simply used the ping example in Arduino Examples and slightly modified it.
- After getting the hex file, now upload it to Arduino in Proteus by clicking the properties.
- Click on the Start button and if everything's gone fine then you will see an output as shown in the below figure:
- As you can see in the above figure, the virtual terminal is showing distance values, now this value depends on the variable resistance attached to the ultrasonic sensor.
- As you change the value of the variable resistance, the voltage on that particular pin will also change and on the basis of that, you will get the distance in inches and centimeters on the virtual terminal.
- Arduino code and hex file along with the Proteus Simulation for this ultrasonic example are attached below. You can download it by clicking on the below button but I would suggest you to design it on your own, it will help you in learning.
- You should also have a look at these Arduino Projects for Beginners.
Download Code and Proteus Simulation
That's all for today, in the coming post I am gonna share some more examples of how to use ultrasonic sensor in Proteus. Till then take care and have fun.
Logical Gates in Ladder Logic for PLC
In the previous post Logical Gates in Ladder Logic for PLC, we had an overview of what is Ladder Logic programming and we have also implemented three basic Logical gates in Ladder Logic form. Today, we are gonna have a look at some complex Logical Gates in Ladder Logic for PLC. So, I hope till now you guys have basic knowledge of Ladder Logic and can implement complex logical gates in it. If you haven't read the previous post then must read because without that knowledge you won't understand this post.
In today's post we are gonna implement few complex logical gates. Its not gonna be much difficult if you have the basic concepts. I am just pointing out few important points here. While implementing any gate in ladder logic, always consider rung as an electrical line having HIGH voltage at one end and LOW voltage at the other, while the inputs are simple switches. Voltage will be supplied to the output only when switch is closed i.e. input is HIGH, otherwise the output will remain OFF. You should also have a look at Introduction to Logic Gates.
You have seen in previous post, while implementing OR gate we have used a second switch in parallel which ends at the first rung so overall its a single rung having two inputs in parallel so input can come either from first switch or from second one. So, now let's start implementing some complex logical gates in Ladder Logic for PLC. Today, we are gonna implement these logic gates:
- NAND Logical gate in Ladder Logic for PLC
- NOR Logical gate in Ladder Logic for PLC
- XOR Logical gate in Ladder Logic for PLC
- XNOR Logical gate in Ladder Logic for PLC
NAND Logical gate in Ladder Logic for PLC
- NAND gate is another type of logical gate, which is normally used. NAND gate is nothing but a simple NOT of AND gate. In simple words, if we add a NOT gate in front of AND gate, we get NAND gate. The truth tablel of NAND gate is shown in the below figure:
- It is quite obvious from the truth table of NAND gate that the output will be OFF only when both the inputs will be ON otherwise output will remain ON. So, now lets implement this gate in ladder logic programming.
- The below image shows the implementation of NAND logical gate in Ladder Logic form:
- Now, if you understand the above figure, then its quite obvious. We have used both inputs in normally closed form so when both inputs are OFF the output will be ON. If we get X0 ON then in still we will get the HIGH voltage from X1. If we make X1 ON then we get HIGH voltage from X0, but if we get both X0 and X1 ON then our Y0 will get OFF. Again we are using inputs in normally closed form so when our actual input is OFF then our X0 is closed. :)
NOR Logical gate in Ladder Logic for PLC
- In NOR gate, we simple place a NOT gate in front of OR gate. Its truth table is shown in below figure:
- From the truth taable of NOR gate, its quite obvious that its output will be ON when both of its input goes OFF otherwise the output will remain ON. Lets implement this NOR logical gate in Ladder Logic diagram.
- The below figure shows the NOR logical gate in ladder logic diagram:
- If you got the ladder logic form of NAND gate, then its not gonna be much problem. Simple two normally closed inputs are placed in series, so now when any of them gets ON, then output will get OFF.
Note:
- If you have noticed, whenever NOT gate is involved somewhere, we use normally closed inputs.
XOR Logical gate in Ladder Logic for PLC
- The truth table of XOR gate is shown in below figure:
- From the truth table, we can get this thing that, output will ON only when the inputs are in opposite states and output will be OFF when inputs are in same state.
- The ladder logic implementation of XOR gate is shown in below figure:
- Now it has gone a little complex but lets understand how's its working. We have placed X0 and X1 in series and also in parallel, but in first string X0 is normally open and X1 is normally closed while in second string X0 is normally closed and X1 is normally open.
- Now, what we need to do is if both inputs are in same state we need to turn OFF the output. That's what we are doing in above logic diagram. Let's say X0 and X1 both are OFF then the normally open switches will be OFF and they wont let the HIGH voltage pass and hence our Y0 will remain OFF. And if both are ON then the normally closed will be OFF and again Y0 will remain OFF.
- Now if X0 is ON and X1 is OFF, then the first string will connect and our output will ON, and if X0 is OFF while X1 is ON then our second string will connect and will make our output ON. Quite simple and easy.
XNOR Logical gate in Ladder Logic for PLC
- Last but not the least XNOR gate, if we add NOT gate in front of XOR gate we get XNOR gate, let's have a look at its truth table below:
- So, in XNOR gate, we get our output ON when both inputs are in same state otherwise its OFF. Let's implement it in ladder logic form below:
- Now in this ladder logic diagram, we are getting introduced with a new symbol, till now we have used normally open output but here for the first time, we are using normally closed output Y0.
- It's exactly the same logic as we used for XOR gate, but the only difference is ere we are using normally closed output. So, simple when the output is gets ON, its actually OFF and when it gets OFF its actually ON ;)
- I hope now you got the clear concept of How to do programming using Ladder Logic and what's its difference with Microcontrollers like Arduino or PIC Microcontroller etc.
That's all for today, hope I have conveyed some knowledge. If you are new to PLC programming then you won't get it in the first attempt so my suggestion is give it some time, read it again and again and you will feel better :) I am not gonna post more about Ladder Logic designing, instead in the next post we are gonna have n overview of PLC simulation software in which we design this ladder logic diagrams. Till then take care and have fun :)
Introduction to Ladder Logic for PLC
Hello everyone, I hope you all are doing great. In today's tutorial, I am going to share the detailed fIn the previous post, we have seen Introduction to PLC, which was quite simple and has the basic introduction to PLC. To day we are gonna have a look at Getting Started With Ladder Logic For PLC. Ladder Logic, also named as Ladder Logic Programming, is the programming language for PLCs. Its normally considered as the most difficult language among the engineers because of its complex structure, but if you ask me then I will say its the most interesting programming language.
Ladder Logic is different from the usual programming language of Microcontrollers like Arduino, PIC Microcontroller etc. Microcontrollers programming usually compiled from top to bottom i.e. the compiler first capture the first statement and then moves downward till it reaches the end line but that's not the case with Ladder Logic Programming for PLC. In ladder logic, the compiler moves from left to right and it gets all the lines at the same time. It seems bit difficult to understand at first but be with me and you will get it at the end. :)
Introduction to Ladder Logic
Ladder Logic is a programming language used for PLC as C for Microcontrollers. Ladder logic is a combination of rungs. Each rung is executed from left to right. For example, have a look at the below figure, a single rung of ladder logic is shown in it.
- In the above figure, a single rung of ladder logic is shown. Now as I mentioned earlier, each rung is executed from left to right, so the above rung will also do the same behavior.
- There are two symbols mentioned in the above rung, one is X0 and the other is Y0. X0 is placed on the left side while Y0 is placed on the right side.
- We have seen in our previous tutorial Introduction to PLC, that X always indicates input and Y indicate output, so in short the above rung has input on the left side while output on the right side.
- So combining all the above discussion, we come to the conclusion that input will be executed first and then output will be executed, as shown below. (I hope you got the basic theory now :) )
- So now the thing is, if we only consider the above rung, the output Y0 will be ON only if input X0 will be ON. If X0 is OFF then Y0 will also be OFF. Consider this rung as a voltage wire as shown in below figure:
- So, now the output will be ON only when it has HIGH and LOW but input is acting as a switch and in normal condition, its OFF so HIGH is not reaching to output so it will remain OFF, as we turn ON the input X0, it will be like the switch is closed and HIGH will pass through the X0 and will reach Y0 and Y0 will turn ON. I tried my best to explain it as simple as I can but still having confusion, ask in comments.
- Now let's have a look on different logical gates i.e. AND gate, OR gate, NAND gate etc, we normally create in ladder logic.
1. Logical AND in Ladder Logic for PLC
- We all know about the Logical AND gate, in AND gate we get output only if both the inputs are HIGH, otherwise OUTPUT remain OFF.
- The below figure shows the same logical AND gate designed in Ladder Logic diagram:
- Now in the above figure Y0 will be ON when both X0 and X1 are ON, otherwise Y0 will be ON, again consider inputs as switches.
- Its a simple 2 input AND logic, we can add as many inputs as we want in it. For example, below image shows a four input AND gate.
2. Logical OR in Ladder Logic for PLC
- In Logical OR gate, output goes ON when any of the inputs is ON, lets implement it in our ladder logic form.
- The below figure shows the ladder logic form for OR gate:
- If you check the above figure, if X1 goes ON then our connection will connect and Y0 will be ON, similarly, if X0 is OFF and X1 is ON then again Y0 will be ON because now voltage is coming from X1. Again consider inputs as switch.
3. Logical NOT in Ladder Logic for PLC
- In logical NOT gate, output is always opposite to input, if input is HIGH then output will be LOW and vice versa.
- In order to implement NOT gate, we have to consider another type of input, the input which we are using till now is normally open input, means it is open (OFF) in its normal condition and gets closed (ON) when input is supplied, but in ladder logic there's another type of input also present named as normally closed input.
- Normally closed input is closed (ON) in its normal condition and goes open (OFF) when it gets actual input.
- So, using this normally closed input, we can quite easily implement this Logical NOT gate in ladder logic as shown in below figure:
- In the above figure X0 will be ON in normal condition and hence, Y0 will also be ON and when we get actual input then X0 will get OFF and our Y0 will also be OFF.
So, that was all for today. As you have got the basic knowledge of Ladder Logic, so now its time to have a look at How to design
Logical Gates in Ladder Logics for PLC. Thanks for reading. :)
Introduction to PLC
Hello friends, I hope you all are fine and enjoying good health. Today's tutorial, as the name shows, is on Introduction to PLC. PLC is an abbreviation of Programmable Logic Controller. Recently I worked on a project in which I have to design a Automated coffee Mixing Machine Using PLC. It worked quite good and I had a great time while working on it. After completing that project, it occurred to me that I haven't posted any tutorial on PLC. So I thought of starting this tutorial. This tutorial is not gonna cover in single post so my plan is to divide it in parts.
Today. I am gonna give an overview about PLC. We will have a look on basics i.e. what is PLC? Why we use PLC instead of microcontroller like Arduino or PIC Microcontroller? What's its advantages and disadvantages? I will try to cover all about the basics. After reading this tutorial, you must have a look at Introduction to Ladder Logic for P L C, Ladder Logic is programming language for PLCs.
There are different types of PLCs available in the market manufactured by different companies, so its impossible to cover all of them. In this tutorial, I am gonna discuss Fatek PLC as I have worked on it during my project. The model I have used is Fatek PLC Fbs-20MA. The reason I used this model because it was cheap and has enough input/output ports sufficient for my project. That's why I preferred it as its engineers' task to optimize the cost as well. Let's get started with PLC.
What is PLC?
Its a basic question, which is normally asked by all the starters so I am gonna reply it first for the newbies.
- PLC is nothing but an advanced form of Microcontroller. It is usually used in industries because of its flexibility and ease of use.
- It can be attached quite easily with computer via serial port as well as usb port.
- PLC is used when we need to automate anything just like microcontroller. We attach our sensors and actuators etc with PLC and then insert some programming code in it and let it do its job.
- You have seen automated lifts, they all are operated with PLC.
- We can use timers, counters, registers in PLC and can get any kind of output from it.
- We can program PLC with different languages and the most commonly used language for PLC is named as Ladder Logic.
Internal Overview of PLC
What's inside PLC, which makes it so cool ? That's a good question and normally engineers wonder about it. PLC can be divided into 3 sections, which are as follows:
- Power Supply - Thissection provides power to the PLC, in my case it is operated on 220V AC, so when I provide 220V AC to my PLC, it got activated and start performing functions.
- Centeral Processing Unit (CPU) - Its the actual brain of PLC, it is further divided into several parts i.e. RAM, ROM, EEPROM, microcontroller etc. The programming code is uploaded in this CPU and according to that program, it performs its functions.
- Input / Output Section - This section is the one from where PLC communicates with the external world. We can attach sensors to the inputs of PLC and can operate our motors, actuators etc from the outputs of PLC.
Types of PLCs
- There are different types of PLCs available in the market manufactured by different companies.
- Few famous PLC companies are Siemens, Mitsubishi, Fatek etc.
- Moreover, they are also available in different sizes and functions. The one I used has 14 inputs and 8 outputs. It doesn't support analog inputs as I don't require them.
- There are PLCs available with analog inputs or you can also buy cards which are interfaced with the PLC and make them capable to work on analog inputs.
- Another function which is not available in my PLC is the Serial communication, but such models are available which supports serial communication.
- So in short, there are several models of PLC available in the market and you have to consider your project demands while buying a PLC.
Why use PLC instead of microcontrollers?
- Microcontroller is normally used in small products, where you need to control some sensors or some motors etc but when we talk about big automated plants in industries then PLC is always preferred over microcontroller.
- The reason for preferring PLC over microcontroller in big projects is because of its flexibilty and ease of use. PLC can be programmed frequently with computer, suppose you have an automated system and you find some bug in it which you wanna remove, then what you need to do is simply attach a computer with the PLC of that plant and make changes in the code, which isn't possible with the microcontroller.
- Moreover, PLC has lot of memory, you can add any size of data in it.
- PLC is also long life as compared to microcontroller.
- Last but not the least, PLC has built in cards to control heavy AC voltages, you can get any kind of voltage from PLC i.e. 220V AC etc but if you wanna get such voltages from microcontrollers then you have to add some extra circuitry.
- In short, in all industrial automated plants, PLC is used.
Getting Started With PLC
I think now you have the idea about PLC, so now I am getting started with PLC. I am gonna explain the functioning of Fatek PLC as I have used that one but if you are using another model of PC then no need to panic as all PLCs have same functionality. So, it doesn't matter which one you are using. If you check the below image then you will see I have marked three sections in it.
- Section 1 is indicating the status of input pins. If inputs are off then this section will remain as shown in above figure, but if any of the inputs get high, then the respective pin indicator will also glow into red, which indicates that this pin is ON. It helps while you are writing programming code for the PLC.
- Section 2 indicates the status of PLC. If PLC is powered up then the POW led will go red, if you have uploaded the code in PLC and start it then the RUN led will go red and if your code has some error then ERR led will go red.
- Section 3 indicates the status of output pins, it will tell you which output is currently ON.
In the below image, I have indicated Section 4 and 5, these are the input/ output section. If you have a look at it closely then you can see there are two rows of screws, where you plug your wires for inputs and outputs and above them, they are also labelled with white color. So, it goes like that, first row of labelling is for first row of screws and second row is for second row of screws.
- Section 4 is the inputs pins section, so if you check above there are inputs from X0 to X13, which makes it overall 14 inputs. Moreover, there are two pins labelled as + 24V and - 24V, which PLC is providing us, so if you wanna give any input to this PLC you have to make sure that its 24V, otherwise PLC not gonna recognize it.
- Section 5 is the output pins section. and you can see there are total 9 outputs starting from Y0 to Y8, now you are getting confused with C0 to C6. C pins are actually the voltage setter, let me explain, in projects there are different outputs are required like your motor is running at 12V DC while your solenoid valve is running at 220VAC. So, there's a need to set these voltages at the output. Here C pins are used. Suppose you need to give 12V output at Y0 and Y1 then give this 12V at C0 and when Y0 or Y1 is ON then they will give 12V at output. In short, when output gets ON it is actually connecting with their respective C pin.
- Lastly, check the Port 0 in the above image, this is the port where you plug your serial wire inPLC and connect it with your computer in order to upload the programming code.
That's all for today. I hope you got the basic idea of Programmable logic controller and now its time to have a look at Introduction to Ladder Logic for P L C, ladder logic is programming language for PLC. Your feedback are warmly welcome. In the next tutorial, I am gonna cover about ladder logic and will show you how to program a PLC. Till then Take care and have fun.
Tutorial1: Earn with Freebitco.in
Hello friends, hope you all are fine and having fun. Today, I am going to share a new kind of tutorial, which is about online earning. We all know that engineering students are rich with knowledge but they are not much well with earning while studying so I have thought a bit on this issue and finally I decided to share some topics using which one can earn online quite easily. Before going into details, I wanna clear one thing that it won't be that much but still it will be enough to spend a month. So, follow all my tutorials carefully and if you follow them step by step then I am sure that you can earn big. Moreover, you should also have a look at this new Tutorial2: Earn with PrimeDice , its another great site through which you can earn BTC.
So, let's move on to our today's earning trick. First of all, I want you to have a quick look at bitcoin, which is a digital currency and it worth quite a lot. One bitcoin is equal to around 400$ so you can have the idea how much does it cost. So, today I am gonna share a trick using which you can earn really big money but don't need to get rushy because slow and steady wins the race.
Earn with Freebitco.in
- Its a great site from where you can earn bitcoins quite easily and hourly.
- It gives you 0.00000519 BTC every hour, which is quite low but you can earn big from it by playing a game which is Multiply BTC.
- So, first of all, create an account on this freebitco.in site by clicking here.
- After that Claim your free BTC every hour.
- Don't play this game yet as its not worth it.
- Keep on getting free BTC unless you got around 0.00015000 BTC or more.
- Now the real fun begins, now simply click on Multiply BTC game. It will look like as shown in below figure:
- In this game, hit the Auto Bet and then click on ON Lose.
- In ON LOSE, tick the second option which says, increase bet by and make it 100%.
- One more thing to change is BET ODDS, make it 3 instead of 2.
- Now hit the Start Auto Bet button and let the game begin.
- You are gonna win BTC, its a slow process but its free. :)
So, that's all for tutorial one and I hope you got something out of it. I will come with more exciting earning tricks soon.
Introduction to Multilevel Inverters
Hello friends, today's tutorial is about Introduction to multilevel inverters, which is quite a wide field so I am not gonna discuss everything here. I will post more about it in my coming tutorials. Today, I am going to through some light on the multilevel inverter, i.e. how they operate and will also discuss their types in detail. So, let's start it.
An inverter, also named a power inverter, is an electrical power device that is used to convert direct current (DC) into alternating current (AC). Using a few control circuits and switches, one can get AC at any required voltage and frequency. Inverter plays exactly the opposite role of rectifiers as rectifiers are used for converting alternating current (AC) into direct current (DC). There are different types of inverters available these days. You should also have a look at Pure Sine wave Inverter Design with code and Modified Sine Wave Inverter Design with code. I think you are gonna like that one. Few most commonly used inverter types are:
- Square wave inverters
- Modified sine wave inverters
- Multilevel inverters
- Pure sine wave inverters
- Resonant inverters
- Grid-tie inverters
- Synchronous inverters
- Stand-alone inverters
- Solar inverters
We have designed a 3 level Diode Clamped Multilevel Inverter in Simulink MATLAB, which you can buy by clicking on the lower button. As it's mostly used by the engineering students that's why we have placed a very small price of $10 so that they can buy it easily and we also get rewarded for our efforts.
Buy MATLAB Simulink Simulation
Introduction to Multilevel Inverter
- A multilevel inverter is a power electronic device that is capable of providing desired alternating voltage level at the output using multiple lower-level DC voltages as an input.
- Mostly a two-level inverter is used in order to generate the AC voltage from DC voltage.
Now the question arises what’s the need of using a multilevel inverter when we have a two-level inverter. In order to answer this question, first, we need to look at the concept of the multilevel inverter.
Concept of Multilevel Inverter
First, take the case of a two-level inverter. A two-level Inverter creates two different voltages for the load i.e. suppose we are providing Vdc as an input to a two-level inverter then it will provide + Vdc/2 and – Vdc/2 on output. In order to build an AC voltage, these two newly generated voltages are usually switched. For switching mostly PWM is used as shown in Figure 2.1, reference wave is shown in the dashed blue line. Although this method of creating AC is effective but it has few drawbacks as it creates harmonic distortions in the output voltage and also has a high dv/dt as compared to that of a multilevel inverter. Normally this method works but in few applications, it creates problems particularly those where low distortion in the output voltage is required.
PWM voltage output of a two-level inverter
The concept of multilevel Inverter (MLI) is a kind of modification of a two-level inverter. In multilevel inverters we don’t deal with the two-level voltage instead in order to create a smoother stepped output waveform, more than two voltage levels are combined together and the output waveform obtained in this case has lower dv/dt and also lower harmonic distortions. The smoothness of the waveform is proportional to the voltage levels, as we increase the voltage level the waveform becomes smoother but the complexity of the controller circuit and components also increases along with the increased levels. The waveform for the three, five and seven level inverters are shown in the below figure, where we clearly see that as the levels are increasing, the waveform becoming smoother.
A three-level waveform, a _ve-level waveform and a seven-level multilevel waveform, switched at fundamental frequency
Multilevel Inverter Topologies
There are several topologies of multilevel inverters available. The difference lies in the mechanism of switching and the source of input voltage to the multilevel inverters. Three most commonly used multilevel inverter topologies are:
- Cascaded H-bridge multilevel inverters.
- Diode Clamped multilevel inverters.
- Flying Capacitor multilevel inverters.
1. Cascaded H-bridge Multilevel Inverters
This inverter uses several H-bridge inverters connected in series to provide a sinusoidal output voltage. Each cell contains one H-bridge and the output voltage generated by this multilevel inverter is actually the sum of all the voltages generated by each cell i.e. if there are k cells in an H-bridge multilevel inverter then a number of output voltage levels will be 2k+1. This type of inverter has an advantage over the other two as it requires fewer components as compared to the other two types of inverters and so its overall weight and price are also less. Below Figure shows a k level cascaded H-bridge inverter.
One phase of a cascaded H-bridge multilevel inverter
In a single-phase inverter, each phase is connected to a single dc source. Each level generates three voltages which are positive, negative and zero. This can be obtained by connecting the AC source with the DC output and then using different combinations of the four switches. The inverter will remain ON when two switches with opposite positions will remain ON. It will turn OFF when all the inverters switch ON or OFF. To minimize the total harmonic distortion, switching angles are defined and implemented. The calculations for the measurement of switching angle will remain the same. This inventor can be categorized further into the following types:
- 5 levels cascaded H Bridge Multilevel Inverter
- 9 levels cascaded H Bridge Multilevel Inverter
In 5 level cascaded H Bridge Multilevel Inverters, Two H Bridge Inverters are cascaded. It has 5 levels of output and uses 8 switching devices to control whereas in 9 level cascaded H Bridge Multilevel Inverters, Four H Bridge Invertors are cascaded. It has 9 output levels and use and use 16 switching devices.
Applications of Cascaded H-bridge Multilevel Inverters
Cascaded H Bridge Multilevel Inverters are mostly used for static var applications i.e., in renewable resources’ of energy and battery based applications. Cascaded H Bridge Multilevel Inverters can be applied as a delta or wye form. This can be understood by looking at the work done by Peng where he used an electrical system parallel with a Cascade H Bridge. Here inverter is being controlled by regulating the power factor. Best application is when we used as photovoltaic cell or fuel cell. This is the example of Parallel connectivity of the H Bridge Multilevel Inverter.
Example of 3 phase Wye Connection
H Bridge can also be used in car batteries to run the electrical components of the car. Also, this can be used in the electrical braking systems of the vehicles.
Scientists and engineers have also proposed the multiplicative factor on Cascade H Bridge Multilevel. It means that rather than using a dc voltage with the difference in levels, it uses a multiplying factor between different levels of the multilevel i.e., every level is a multiplying factor of the previous one.
Advantages of Cascade H Bridge Multilevel Inverters
- Output voltages levels are doubled the number of sources
- Manufacturing can be done easily and quickly
- Packaging and Layout are modularized.
- Easily controllable with a transformer as shown in the Fig 2.5
- Cheap
Cascaded Inverter with transformer
Disadvantages of Cascade H Bridge Multilevel Inverters
- Every H Bridge needs a separate dc source.
- Limited applications due to a large number of sources.
2. Diode Clamped Multilevel Inverters
Diode clamped multilevel inverters use clamping diodes in order to limit the voltage stress of power devices. It was first proposed in 1981 by Nabae, Takashi and Akagi and it is also known as a neutral point converter. A k level diode clamped inverter needs (2k – 2) switching devices, (k – 1) input voltage source and (k – 1) (k – 2) diodes in order to operate. Vdc is the voltage present across each diode and the switch. Single-phase diode clamped multilevel inverter is shown in the figure below:
One phase of a diode clamped inverter
The concept of diode clamped inverter can better be understood by looking into a three-phase six-level diode clamped inverter. Here the common dc bus is shared by all the phases, use five capacitors and six levels. Each capacitor has a voltage of Vdc and same is the voltage limit of switching devices. One important fact should be noted while considering the diode clamped inverter is that five switches will remain ON at any time. Six level, three-phase dc clamped multilevel inverter is shown in the figure below.
Six level three phase inverter
Outputs of each phase can be understood by the following table. Here reference voltage is the negative Vo. Condition 0 means switch is OFF and vice versa. Output waveforms of six level dc clamped inverter is shown below:
Waveform of Six Level Inverter
Vab is the voltage due to the phase lag b and a voltage.
Applications of Diode Clamped Multilevel Inverters
The most common application of diode clamped multilevel inverter is when a high voltage Dc and Ac transmission lines are interfaced. This can also be used in variable speed control of high power drives. Static variable compensation is also an application of diode clamped multilevel inverters.
Advantages of Diode Clamped Multilevel Inverters
- The capacitance of the capacitors used is low.
- Back-to-back inverters can be used.
- Capacitors are precharged.
- At fundamental frequency, efficiency is high.
Disadvantages of Diode Clamped Multilevel Inverters
- Clamping diodes are increased with the increase of each level.
- The DC level will discharge when control and monitoring are not precise.
3. Flying Capacitor Multilevel Inverters
The configuration of this inverter topology is quite similar to previous one except the difference that here flying capacitors is used in order to limit the voltage instead of diodes. The input DC voltages are divided by the capacitors here. The voltage over each capacitor and each switch is Vdc. A k level flying capacitor inverter with (2k – 2) switches will use (k – 1) number of capacitors in order to operate. The figure below shows a five-level flying capacitor multilevel inverter.
A Flying Capacitor Multilevel Inverter with five voltage levels
If we compare above figures, it shows that the number of switches, main diodes and DC-bus capacitors are same in both the cases. The only difference between the two topologies is that the previous one uses clamping diodes in order to limit the voltage while this topology uses flying capacitors for this purpose, and as capacitors are incapable of blocking the reverse voltage, which diodes do, the number of switches also increases. Voltage on each capacitor is differing from the next as it has a ladder structure. Voltage difference between two back to back capacitors determines the voltage in the output frame.
Advantages of Flying Capacitor Multilevel Inverters
Static var generation is the best application of Capacitor Clamped Multilevel Inverters.
- For balancing capacitors’ voltage levels, phase redundancies are available.
- We can control reactive and real power flow.
Disadvantages of Flying Capacitor Multilevel Inverters
- Voltage control is difficult for all capacitors.
- Complex startup.
- Switching efficiency is poor.
- Capacitors are expensive than diodes.
So, that was all about Multilevel Inverters and their topologies. I hope you guys have understood this concept in detail. Please let me know if you have any questions. Till next tutorial, take care and have fun !!! :)
Black Litterman Approach in MATLAB
Buy This Project
This post is the next part of our previous post Financial Calculations in MATLAB named as Implementation of Black Litterman Approach in MATLAB, so if you haven't read that then you can't understand what's going on here so, its better that you should first have a look at that post. Moreover, as this code is designed after a lot of our team effort so its not free but we have placed a very small cost of $20. So you can buy it easily by clicking on the above button.In the previous post, we have covered five steps in which we first get the financial stock data, then converted it to common currency and after that we calculated the expected returns and covariance matrix and then plot the frontiers with and without risk free rate of 3%. Now in this post, we are gonna calculate the optimal asset allocation, average return after the back test, calculation of alphas and betas of the system and finally the implementation of black-litterman approach. First five steps are explained in the previous tutorial and the next four steps for Implementation of Black Litterman Approach in MATLAB are gonna discuss in this tutorial, which are as follows:
- Step 6: Calculate Optimal Asset Allocation
- Step 7: Average Return after the back test
- Step 8: Calculation of Standard Deviation
- Step 9: Calculate alphas & betas of the system
- Step 10: Implementation of Black Litterman Approach
You may also like to read:
Step 6: Calculate Optimal Asset Allocation
In this part of the problem,I calculated the optimal asset allocation in the different years by choosing a constant required return. I chose the constant required return equal to 0.01 and used the highest_slope_portfolio function and plot the graphs. The code used in MATLAB is shown in the below:
ConsRet=0.010
for w=1:10
[xoptCR(:,w), muoptCR(w), sigoptCR(w)] = highest_slope_portfolio( covmat{1,w}, ConsRet , estReturn(w,:)', stdRet(w,:) );
End
The result for this part is shown in the Figure 3. For a constant required return of 0.01, portfolio turnover for each year has increased approximately by 2%.
Figure: Optimal asset allocation for constant return of 0.01
Step 7: Average Return after the back test
In this part of the assignment, it was asked to perform a back test for the optimized portfolios and calculate the average return and the standard deviation for this portfolio. Average return is the average of expected return for the corresponding year and it is calculated by the below code in MATLAB, where w is varying from 1 to 10 to calculate for all the 10 years.
BTreturn(w,:)=estReturn(w,:)*xoptCR(:,w);
Results obtained after the back test for the optimized portfolios for average return are shown in table3 below:
Average Return after the back test |
1st year |
0.1158 |
2nd year |
0.0889 |
3rd year |
0.0797 |
4th year |
0.0628 |
5th year |
-0.0660 |
6th year |
-0.4323 |
7th year |
-5.1212 |
8th year |
-0.6820 |
9th year |
0.2891 |
10th year |
0.1691 |
Table : Average return after the back test
Step 8: Calculation of Standard Deviation
The standard deviation of the rate of return is a measure of risk. It is defined as the square root of the variance, which in turn is the expected value of the squared deviations from the expected return. The higher the volatility in outcomes, the higher will be the average value of these squared deviations. Therefore, variance and standard deviation measure the uncertainty of outcomes. Symbolically,
Where,
- S = Standard Deviation
- E(r) = Expected return
- p(s) = Probability of each scenario
- r(s) = Holding-price return in each scenario.
- s = number of scenarios.
- n = Maximum number of scenarios.
Matlab code for calculating the standard deviation after the back test is shown below:
BTstd(w,:)=sqrt(stdRet(w,:).^2*(xoptCR(:,w).^2));
The results of standard deviation for the 10 years are as follows:
Standard Deviation after the back test |
1st year |
0.2942 |
2nd year |
0.1833 |
3rd year |
0.1799 |
4th year |
0.1733 |
5th year |
0.4026 |
6th year |
1.5834 |
7th year |
16.1279 |
8th year |
2.1722 |
9th year |
1.0430 |
10th year |
0.4949 |
Step 9: Calculate Alphas & Betas of the system
In this part, it was asked to use a broad stock index for testing and check whether our portfolio is in line with the CAPM prediction:
Hence, first of all I retrieved the historical data for ticker ^FTLC using the function hist_stock_data as I done in the first part of the assignment. The MATLAB code for retrieving the data is shown below:
FTLC= hist_stock_data('01111993','01112013','^FTLC','frequency','m');
LRFTLC=diff(log(FTLC.Close));
After that I calculated the expected return of one unit of each asset based on the model which gave me the total covariance matrix for the single and multi indexed model. Finally, I calculated the alpha and beta for the model. The MATLAB code used for performing these actions is shown below:
for i = 1:7
mdl_si{i} = LinearModel.fit(LRFTLC, logRet(:,i), 'linear');
mdl_ret_s(i) = mdl_si{i}.Coefficients.Estimate(1:2)' * [1; 12*mean(LRFTLC)];
mdl_cov_s(i) = mdl_si{i}.RMSE^2;
alpha_s = [mdl_si{i}.Coefficients.Estimate(1), alpha_s];
beta_s = [mdl_si{i}.Coefficients.Estimate(2), beta_s];
end
As a result, alphas and betas of the system are obtained which are shown in the table below:
Aplha |
Beta |
0.0068 |
0.1748 |
0.0057 |
0.0335 |
0.0050 |
0.0528 |
0.0063 |
0.0552 |
0.0030 |
0.0249 |
0.0035 |
0.0083 |
0.0047 |
0.0289 |
Table: Alpha & beta of the model
Step 10: Implementation of Black Litterman approach
In this part, I have finally implemented the Black Litterman approach on the data available. Black Litterman approach involves the below steps:
Few MATLAB Projects:
- The Covariance Matrix from Historical Data
- Determination of a Baseline Forecast
- Integrating the Manager’s Private Views
- Revised (Posterior) Expectations
- Portfolio Optimization
The code used for implementing the black litterman approach is shown below and the results obtained as a result of Black Litterman approach are shown in the below figure. Risk aversion is take as 1.9 while the precision is 0.3.
gamma = 1.9;
tau = .3;
for w=1:10
ind=[(w-1)*12+1 (w+10)*12];
logRet2=logRet(ind(1):ind(2),:);
for i=1:7
OplogRet(:,i)=logRet2(i,:).*xoptCR(i,w)'*100;
end
covmatOP{1,w}=12*cov(OplogRet);
end
for w=1:10
Opweig(:,w)=xoptCR(:,w);
Pi{w}= gamma *covmatOP{1,w}* Opweig(:,w);
end
figure
for w=1:10
title('BL');
hold on;
bar(Pi{w})
hold on;
end
Figure: Bar graph for Black-Litterman approach
That's all for today, hope it will help you all in some way. If you have any questions then ask in comments and I will try my best to resolve them.
Financial Calculations in MATLAB
Buy This Project
Hello friends, today I am gonna share a MATLAB project related to finance which I have named as Financial Calculations in MATLAB. As this project is the outcome of our team efforts so its not free and you can buy it quite easily for just $20 by clicking on the above button. In finance studies, there are lot of calculations are required to be done so MATLAB plays a very important role in finance calculations and showing the pattern in graphical form. In this project, I am first gonna take the Historical Stock Data from web search online so in order to run this program, your computer must have internet access. After getting the historical stock data of 7 different markets or sectors, now there's a need to convert them into same currency so that we can compare it with each other. So, I took US$ as a common currency and convert all others to this currency.
After that I calculated Expected Returns & Covariance Matrix for all these data for the last 10 years and finally plot them. Moreover, I have also plotted the frontiers with risk free rate of 3% so that the ideal and realistic conditions can be compared. So, here are the overall steps we are gonna cover in this project:
- Step 1: Getting Historical Stock Data
- Step 2: Conversion of currencies
- Step 3: Calculate Expected Returns & Covariance Matrix
- Step 4: Plotting 11 different frontiers in one figure
- Step 5: Plotting frontiers with risk free rate of 3%.
These are the first five steps of this project. The next five steps are discussed in
Implementation of Black-Litterman Approach in MATLAB.
You may also like to read:
Step 1: Getting Historical Stock Data
- First of all, I chose 7 financial stock indices for different markets or sectors. So, I used a function named hist_stock_data. The syntax of this function is as follows:
Stocks = hist_stock_data('X', 'Y', 'Z', 'frequency', 'm')
- X is the starting date and is a string in the format ddmmyyyy.
- Y is the ending date and is also a string in the format ddmmyyyy.
- Z is the Ticker symbol, whose historical stock data is needed to be retrieved.
- M denotes that the function will return historical stock data with a frequency of months.
Hist_stock_data function retrieves historical stock data for the ticker symbol Z between the dates specified by X and Y. The program returns the stock data in a structure giving the Date, Open, High, Low, Close, Volume, and Adjusted Close price adjusted for dividends and splits. I used 7 sectors and retrieved their data using this function. The commands used in MATLAB are:
snp500 = hist_stock_data('01111993','01112013','^GSPC','frequency','m');
NDX=hist_stock_data('01111993','01112013','^NDX','frequency','m');
GSPTSE=hist_stock_data('01111993','01112013','^GSPTSE','frequency','m');
DAX = hist_stock_data('01111993','01112013','^GDAXI','frequency','m');
CAC40=hist_stock_data('01111993','01112013','^FCHI','frequency','m');
FTAS=hist_stock_data('01111993','01112013','^FTAS','frequency','m');
SSMI=hist_stock_data('01111993','01112013','^SSMI','frequency','m');
Step 2: Conversion of currencies
The first two values were in US dollars, while third one was in CAD dollars, fourth and fifth values were in Euros, sixth were in GBP and the last one was in Swiss France. Hence, there was a need to convert all these currencies into one currency as instructed. I converted all of them into US dollars. In order to convert them, I first defined the exchange rate between these currencies and the US dollars using the below code:
GBP2USD=1.6;
EURO2USD=1.34;
CAD2USD=0.95;
SF2USD=1.08;
After defining the exchange rate, I applied it to all the currencies using the below code:
GSPTSE=CurrencyConvert(GSPTSE, CAD2USD);
DAX=CurrencyConvert(DAX, EURO2USD);
CAC40=CurrencyConvert(CAC40, EURO2USD);
FTAS=CurrencyConvert(FTAS, GBP2USD);
SSMI=CurrencyConvert(SSMI, SF2USD);
Now all the currencies for the financial stock indices for 7 sectors are obtained in US dollars.
Step 3: Calculate Expected Returns & Covariance Matrix
In this part, we calculated the expected returns and covariance matrix in annual steps for a period of 10 years. I used the data for 7 markets or sectors were obtained in the first step and calculated their expected returns and covariance matrix. The expected rate of return is a probability-weighted average of the rates of return in each scenario. We may write the expected return as:
Where,
- p(s) = Probability of each scenario
- r(s) = Holding-price return in each scenario.
- s = number of scenarios.
- n = Maximum number of scenarios.
First of all, I initialized a column matrix and filled it with the above data and took log of each data separately by using MATLAB commands as follows:
covmat=cell(1,11);
ret=flipud([log(SSMI.Close) log(FTAS.Close) log(CAC40.Close) log(DAX.Close) log(GSPTSE.Close) log(snp500.Close) log(NDX.Close)]);
Further, I calculated the differences between adjacent elements of each data using the diff command in MATLAB.
logRet=[diff(ret(:,1)) diff(ret(:,2)) diff(ret(:,3)) diff(ret(:,4)) diff(ret(:,5)) diff(ret(:,6)) diff(ret(:,7))];
Expected return is nothing other than a guaranteed rate of return. However, it can be used to forecast the future value of a market, and it also provides a guide from which to measure actual returns. Hence to calculate the expected return, I first take two indices with w as a variable where w = 1:10 and calculated these indices for all the values of w and finally took mean value of each data with these two indices as follows:
ind=[(w-1)*12+1 (w+10)*12];
estReturn(w,:)=[mean(logRet(ind(1):ind(2),1)) mean(logRet(ind(1):ind(2),2)) mean(logRet(ind(1):ind(2),3)) mean(logRet(ind(1):ind(2),4)) mean(logRet(ind(1):ind(2),5)) mean(logRet(ind(1):ind(2),6)) mean(logRet(ind(1):ind(2),7))];
The above values calculated for all the 10 times and hence it is placed within a for loop. estReturn gives us the estimated return for a single month and now there’s a need to convert it to annual return, which is accomplished by below command, simply by mutilpying it with 12.
estReturn(w,:)=estReturn(w,:)*12;
After the calculation of expected return annually, I used the command var(X) to calculate the variance of the data. Although it was not asked to calculate in the problem but in order to calculate the covariance, it is required to first obtain the data such that each row of the matrix becomes an observation and each column is a variable. The command used for the calculation of variance is as shown below:
stdRet(w,:)=sqrt(12*var([ logRet(ind(1):ind(2),1) logRet(ind(1):ind(2),2) logRet(ind(1):ind(2),3) logRet(ind(1):ind(2),4) logRet(ind(1):ind(2),5) logRet(ind(1):ind(2),6) logRet(ind(1):ind(2),7)]));
Finally, I used the MATLAB command cov(x) to calculate the covariance of the data. The syntax used is:
Y = cov(X)
Where,
- X = Matrix of data whose covariance is required.
- Y = Covariance of data X.
As x is a matrix of data in our case where each row is an observation, and each column is a variable, cov(X) is the covariance matrix. Results for the expected return and covariance matrix are shown in the below tables.
Expected Return |
SSMI |
FTAS |
CAC40 |
DAX |
GSPTSE |
SNP50 |
NDX |
1st year |
0.0625 |
0.0373 |
0.0524 |
0.0632 |
0.0700 |
0.0848 |
0.0644 |
2nd year |
0.0954 |
0.0531 |
0.0762 |
0.0846 |
0.0884 |
0.0921 |
0.1290 |
3rd year |
0.0872 |
0.0506 |
0.0972 |
0.0940 |
0.0915 |
0.0763 |
0.1004 |
4th year |
0.0742 |
0.0457 |
0.0814 |
0.0925 |
0.0747 |
0.0610 |
0.0835 |
5th year |
0.0006 |
-0.0064 |
0.0122 |
0.0147 |
0.0321 |
-0.0058 |
0.0110 |
6th year |
-0.0112 |
0.0007 |
-0.0039 |
0.0103 |
0.0537 |
-0.0055 |
0.0115 |
7th year |
-0.0144 |
-0.0069 |
-0.0356 |
0.0115 |
0.0494 |
-0.0148 |
-0.0307 |
8th year |
-0.0314 |
-0.0034 |
-0.0573 |
-0.0041 |
0.0295 |
-0.0048 |
-0.0080 |
9th year |
0.0081 |
0.0180 |
-0.0209 |
0.0359 |
0.0454 |
0.0198 |
0.0470 |
10th year |
0.0431 |
0.0529 |
0.0228 |
0.0907 |
0.0644 |
0.0575 |
0.1007 |
Table 1: Expected Returns for 10 years
Covariance Matrix for 1st year |
SSMI |
FTAS |
CAC40 |
DAX |
GSPTSE |
SNP50 |
NDX |
0.0334 |
0.0191 |
0.0285 |
0.0324 |
0.0168 |
0.0190 |
0.0196 |
0.0191 |
0.0201 |
0.0234 |
0.0271 |
0.0155 |
0.0169 |
0.0257 |
0.0285 |
0.0234 |
0.0434 |
0.0444 |
0.0211 |
0.0226 |
0.0380 |
0.0324 |
0.0271 |
0.0444 |
0.0609 |
0.0252 |
0.0280 |
0.0527 |
0.0168 |
0.0155 |
0.0211 |
0.0252 |
0.0268 |
0.0198 |
0.0342 |
0.0190 |
0.0169 |
0.0226 |
0.0280 |
0.0198 |
0.0234 |
0.0379 |
0.0196 |
0.0257 |
0.0380 |
0.0527 |
0.0342 |
0.0379 |
0.1411 |
Covariance Matrix for 2nd year |
SSMI |
FTAS |
CAC40 |
DAX |
GSPTSE |
SNP50 |
NDX |
0.0318 |
0.0179 |
0.0273 |
0.0322 |
0.0162 |
0.0185 |
0.0235 |
0.0179 |
0.0180 |
0.0213 |
0.0258 |
0.0151 |
0.0161 |
0.0269 |
0.0273 |
0.0213 |
0.0404 |
0.0427 |
0.0209 |
0.0219 |
0.0390 |
0.0322 |
0.0258 |
0.0427 |
0.0590 |
0.0255 |
0.0279 |
0.0503 |
0.0162 |
0.0151 |
0.0209 |
0.0255 |
0.0265 |
0.0193 |
0.0367 |
0.0185 |
0.0161 |
0.0219 |
0.0279 |
0.0193 |
0.0230 |
0.0394 |
0.0235 |
0.0269 |
0.0390 |
0.0503 |
0.0367 |
0.0394 |
0.1014 |
Covariance Matrix for 3rd year |
SSMI |
FTAS |
CAC40 |
DAX |
GSPTSE |
SNP50 |
NDX |
0.0314 |
0.0181 |
0.0280 |
0.0320 |
0.0164 |
0.0186 |
0.0237 |
0.0181 |
0.0181 |
0.0214 |
0.0261 |
0.0152 |
0.0160 |
0.0270 |
0.0280 |
0.0214 |
0.0397 |
0.0433 |
0.0212 |
0.0224 |
0.0399 |
0.0320 |
0.0261 |
0.0433 |
0.0579 |
0.0259 |
0.0282 |
0.0509 |
0.0164 |
0.0152 |
0.0212 |
0.0259 |
0.0266 |
0.0194 |
0.0371 |
0.0186 |
0.0160 |
0.0224 |
0.0282 |
0.0194 |
0.0227 |
0.0395 |
0.0237 |
0.0270 |
0.0399 |
0.0509 |
0.0371 |
0.0395 |
0.1014 |
Step 4: Plotting 11 different frontiers in one figure
In this part, it was asked to plot the 11 different frontiers in one figure. The concept of efficient frontier was introduced by Harry Markowitz and it is defined as if a portfolio or a combination of assets has the best expected rate of return for the level of risk, it is facing, then it will be referred as “efficient”.
Few more MATLAB Projects:
In order plot them, I used the below code in MATLAB, I used different markers for different plots so that they could be distinguished from one another quite easily. Moreover, I used the command legend in order to show the respective years for which the graphs are plotted. RF is a variable which indicate the risk-free rate and as it is asked to operate under efficient frontier that’s why risk-free rate is equal to zero.
RF=0;
for w=1:10
[xopt(:,w), muopt(w), sigopt(w)] = highest_slope_portfolio( covmat{1,w}, RF, estReturn(w,:)', stdRet(w,:) );
end
mker=['o' '+' '*' '.' 'x' 's' 'd' '^' '>' '<']
figure
for w=1:10
plot (sigopt(w), muopt(w) ,'Marker', mker(w));
hold on;
plot (0, RF, 'o');
hold on;
RF_p1 = [0 sigopt(w) 2* sigopt(w)];
opt1_p = [.02 muopt(w) (2 * muopt(w) - RF) ];
line(RF_p1, opt1_p );
end
legend('Year 1994', 'Year 1995', 'Year 1996', 'Year 1997','Year 1998','Year 1999','Year 2000', 'Year 2001', 'Year 2002', 'Year 2003')
In this code, first of all I used highest_slope_portfolio function. This function finds the portfolio with the highest slope.
Results are shown in the below figure annually:
Figure 1: Graph for 11 different efficient frontier
Step 5: Plotting frontiers with risk free rate of 3%
The plot in Part (c) was about the efficient frontier with risk rate equal to zero i.e. operating in an ideal condition while in this part, it was asked to plot the same graphs but this time include a risk-free rate of 3%. Hence I used the same code as for the previous part but only this time I used RF = 0.03 as I needed to include a risk free rate of 3%. The code used in MATLAB for this part is shown below:
RF=0.03; %the risk free rate
for w=1:10
[xoptRF{w}, muoptRF(w), sigoptRF(w)] = highest_slope_portfolio( covmat{1,w}, RF, estReturn(w,:)', stdRet(w,:) );
end
figure
for w=1:10
plot (sigoptRF(w), muoptRF(w) ,'Marker', mker(w));
hold on;
plot (0, RF, 'o');
hold on;
RF_p1 = [0 sigoptRF(w) 2* sigoptRF(w)];
opt1_p = [.02 muoptRF(w) (2 * muoptRF(w) - RF) ];
line(RF_p1, opt1_p );
end
legend('Year 1994', 'Year 1995', 'Year 1996', 'Year 1997','Year 1998','Year 1999','Year 2000', 'Year 2001', 'Year 2002', 'Year 2003')
The result for this part i.e. after including a risk-free rate of 3% is shown in the figure below. If the Figure 1 and Figure 2 are closely examined then one can see the clear difference. When the risk-free rate was considered zero, all the expected estimate graphs were in positive direction depicting the profit annually while after adding a risk-free rate of 3%, few of the graphs went in the negative direction depicting the loss in those years. Hence adding the risk factor may cause the business to get deceased and it may even cause it to decline continuously which results in disaster.
Figure 2: Graph for 11 different efficient frontier for risk-free rate of 3%
That's all for today, in the coming post, I will calculate more financial terms like Optimal asset allocation, average return, standard deviation and much more, so stay tuned and have fun.
Arduino Lilypad Simulation in Proteus
Yesterday, I have posted a new Arduino Lilypad / Nano Library for Proteus in which we have seen how to add that library into Proteus so that you could be able to use these boards in Proteus. That was quite easy. Today I am gonna post a small project in which we will see how to use that library and produce an Arduino Lilypad simulation in Proteus. In this Arduino Lilypad simulation in Proteus, I am gonna use obviously he Arduino Lilypad board along with few LED lightsand will make them blink. Its also quite easy and you can also download the simulation and the hex file at the end of this project but I would suggest you to do it yourself so that you learn something out of it.
Before starting this project, you must have first integrated the Arduino Lilypad Library as without it you wont be abe to do this project. So, if you haven't downloaded it yet then you should read the previous post Arduino Lilypad / Nano Library for Proteus first. Lets get started with this project.
Arduino Lilypad Simulation in Proteus
- Now I assue that you have already downloaded the Arduino Lilypad Library for Proteus and are ready to use it within Proteus.
- So open Proteus ISIS and get these components from the Proteus components library as shown in below figure:
- After getting these components, draw a circuit in Proteus as shown in the below figure:
- You can clearly see in the above figure, the Arduino Lilypad Simulation in Proteus. After that you need to write a code for Arduino Lilypad so that you could get the hex file for it.
- In this project, I have used three LED lights and make them ON and OFF using the switch button. If the button is not pressed then the LEDs will remain ON and when you hit the button , the LEDs will go OFF.
- Copy the below code and paste it into the Arduino software and compile.
int analogPin = A0;
int ledCount = 3;
int ledPins[] = {
2, 3, 4};
void setup() {
// loop over the pin array and set them all to output:
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
pinMode(ledPins[thisLed], OUTPUT);
}
}
void loop() {
// read the potentiometer:
int sensorReading = analogRead(analogPin);
// map the result to a range from 0 to the number of LEDs:
int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);
// loop over the LED array:
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
// if the array element's index is less than ledLevel,
// turn the pin for this element on:
if (thisLed < ledLevel) {
digitalWrite(ledPins[thisLed], HIGH);
}
// turn off all pins higher than the ledLevel:
else {
digitalWrite(ledPins[thisLed], LOW);
}
}
}
- After compiling this code, get the hex file of code. The hex file and this simulation file is also given at the end of this post so you can download it from there.
- Now upload this hex file into this Arduino Lilypad and hit the RUN button
Note:
- If everything's goes fine then as youhit the run button, the LEDs will get ON as shown in the below figure:
- Now, when you press the button, these LEDs will go OFF as shown in the below figure:
- That's all, you have successfully implemented the Arduino Lilypad simulation in Proteus. :)
- In order to download this simulation and the hex file, click on the below buttons.
Download Proteus Simulation