Interfacing of Seven Segment with Arduino in Proteus
Hello friends, today we are gonna have a look on how to interface Seven Segment with Arduino in Proteus. In my last post, I have posted an Arduino Library for Seven Segment Display, which is designed by our team and is quite basic in functionality. So, if you haven't checked that post then first of all check that one and download the Arduino Library for Seven Segment Display as I am gonna use that library in today's post. Moreover, in order to run this library you are also gonna need to download Arduino Library for Proteus, using this library you will be able to use Arduino board in Proteus so also read that post and download this library and install it in your Proteus.
Again I am mentioning that its the first library designed by our team so its in basic stages, it has few functions and will only display the numeric on the seven segment display which is normally required. I am planning on adding more examples in the library for future use, which will increase the functionality. Anyways that's a future talk, let's start today's post.
What is Seven Segment Display?
Let's first have a look at what is Seven Segment Display. Seven Segment display is nothing but an electronic device used for displaying the numeric data. It's a complex form of LED matrix and is normally used in clocks, LCD displays, calculators etc where there's a need to display the numeric data. It has total seven leds in it which you can also count from above image and by turning these LEDs ON or OFF we can display any numeric on it. For example, have a look at the below image. In this image I have shown numeric 0 on seven segment. Now in order to do so, I just simply turn OFF the centered LED and turn ON all the corner LEDs and it becomes 0.
How does Seven Segment Work?
Now, let's have look at how it works. So, we have seen that Seven Segment is named seven segment because it has total seven LEDs on it so now what we need to do is to control these seven LEDs, also named as segments, and then we can display any character on it. There are two types of seven segments available in the market and named as:
- Common Cathode
- Common Anode
They both work exactly the same and has only a slight difference. They both has total seven pins and each pin is used to control each led and they have an extra pin which is named as Common Pin. In Common Cathode you have to GND this Common Pin, while in common Anode, you have to give +5V to this Common Pin. Have a look at this below image, we have labelled leds with respect to the pins.
Interfacing of Seven Segment with Arduino in Proteus
- Now we know all about Seven Segment Display and know how it works so let's interface Seven Segment with Arduino in Proteus.
- Now, I am assuming that you have installed the Arduino Library for Proteus and have also installed the Arduino Library for Seven Segment display.
- So, now open your Arduino Software and go to File>Examples>SevenSegment>Counting.
- Open this example, in this example I have added a counter which will start counting from 0 to 9 and once it reached 9 then it will start counting again.
- If you can't find this example then you must be making some mistake in installing the library, anyways the code is shown below.
Note:
- In order to run this example you will need two libraries, the inks are given below to download:
/*
Counting
This Arduino example is for Seven Segent display.
It will start the counter from 0 and will end up at 9
and will start again from 0.
This example code is in the public domain.
Created by Syed Zain Nasir at 14 March 2015.
You can get the explanation and latest version of this library at:
http://www.TheEngineeringProjects.com/
*/
#include "SevenSegment.h"
SevenSegment tep = SevenSegment(0,1,2,3,4,5,6);
char arr [10] = {'0','1','2','3','4','5','6','7','8','9'};
int index;
void setup(){
index = 0;
}
void loop(){
tep.display(arr[index++]);
delay(1000);
if(index == 11)
index = 0;
}
- Now open you Proteus Software and design the circuit in it as shown in below figure, I have also attached the file for download at the end.
- Now compile the code and gt the hex file and upload it in your Arduino Properties.
- Now Run the Proteus software, and you will see the seven segment display will start counting, a glimpse of it is shown in the below figure:
- Below is attached the Proteus file and the hex file for the counting example which you simply start and run but again I suggest that you should design it by yourself so that you get something out of it.
Download Proteus Simulation of Seven Segment with Arduino
- One last thing, any kind of contribution to this library from the readers is highly appreciated, design your projects and share codes with us and we will post them on our blog for other readers to get knowledge as knowledge is all about sharing.
That's all for today, hope it will help you in some way. Take care and have fun. :)
Arduino Library for Seven Segment Display
In today's post, I am gonna share a new Arduino Library for Seven Segment Display. In my recent project, I got a chance to work on seven segment displays, I have worked on them using PIC microcontroller but haven't got a chance to use them with Arduino. So, now as usual when I started working on them, I started searching for Arduino Library but I kind of got disappointed after getting quite heavy libraries for seven segments, and after a lot of search I thought of designing my own Arduino library for seven segment display, which I am gonna share in this post. :)
It's not very advanced library as we know seven segment displays are not too complex, so its quite simple and using it you can quite easily display any numerical digit on the seven segment display. Moreover, I have also included an example with the library which will start the counter from zero on seven segment display and keep on incrementing till 9 and after that it will start again from zero. Moreover, I have also posted the example about Interfacing of Seven Segment Display with Arduino in Proteus using this library, it will help you in better understanding of How this library works. You can download the working Proteus Simulation as well as hex file from that post.
Download Arduino Library for Seven Segment Display
- As I stated earlier, its a very simple Arduino Library for Seven Segment Display and it will only print the numeric on seven segment display, but I will work on it in future and will update it by adding more features in it.
- So, first of all click the below button to download the Arduino library for seven segment display.
Download Arduino Library for Seven Segment Display
- After downloading the library, place it in the libraries folder of your Arduino software.
- Now close your Arduino software and open it again.
- Go to File and then Examples and you will find SevenSegment in it and it will have an example which is named as Counting.
Functions in Arduino Library for Seven Segment Display
- I have added quite few function in it which are very basic and are very easy to use.
- The first function I have used is:
SevenSegment(int a,int b,int c,int d,int e,int f,int g);
- In this function, you need to give the pins of Arduino with which you are attaching your seven segment display. It will called as shown below:
SevenSegment tep = SevenSegment(0,1,2,3,4,5,6);
- Now tep is our seven segment object and we are gonna use it in rest of the example.
- The next function used in this arduino library for seven segment display is:
display(char c);
- This function will display the numeric on seven segment display which you will provide it.
- Moreover, it will automatically clear the screen before displaying any new character on the seven segment.
- It is called in the example as shown below:
tep.display('1');
That's all for today, in this next post you can download the example of how to
Interface Seven Segment Display Using Arduino in Proteus, it will help you in understanding of this library in detail.
Temperature Sensor 18B20 with Arduino
Hello everyone, in today's post we are gonna have a look at how to interface temperature sensor Dallas 18B20 with Arduino. There are many temperature sensors available in market like LM35, DHT11 etc but personally I like Dallas18B20 most of all, as it gives the most accurate result up to four decimal points. It operates on single wire and sends all data through this wire. Another advantage of this wire is you can interface multiple sensors with a single data line. You should also have a look at How to use 18B20 in Proteus ISIS.
In today's post, we are gonna get value from this sensor and then print it over the Serial Terminal as well as LCD. We will get the values in degree centigrade. Its not much difficult to interface 18B20 with arduino and also an Arduino library is also availble, using which you can quite easily interface 18B20 with Arduino. Let's get started with interfacing of 18B20 with Arduino.
Note:
Interfacing of Temperature Sensor 18B20 with Arduino
- As I explained earlier, it works on single wire and hence we are gonna need 1-wire library for Arduino along with 18B20 arduino library.
- Download both of these libraries by clicking on the below buttons:
Download One Wire Library Download Dallas Temperature Library
- After downloading the library, place it in the libraries folder of your Arduino Software.
- Now restart your Arduino software and you will find the Arduino folder in the Examples section.
- Next we need to interface our sensor 18B20 with Arduino so design your circuit as shown in below figure:
- So, connect the sensor 18B20 with Arduino as shown in the above figure, connections are quite simple and are as follows:
- Pin # 1 of 18B20 with GND
- Pin # 2 of 18B20 with Pin # 2 of Arduino.
- Pin # 3 of 18B20 with GND of Arduino.
- Add a pull up resistor of 4.7k ohm at pin # 2 of 18B20.
- Here's the images of hardware, we designed for this project, its a 20 x 4 lcd we have used:
- Below image shows the small 18B20 sensor, used in this project, it looks small but very efficient.
- Here's the image showing the complete project:
- Now, copy below code and upload it in your Arduino board and open your serial terminal.
#include <OneWire.h>
#include <DallasTemperature.h>
#include <LiquidCrystal.h>
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);
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);
}
- After uploading the code, when I start the project, it started showing the temperature values as shown below:
- As you can see, its giving the temperature of my room which is 23.56 degree centigrade.
- I have also designed a video for more demonstration which is given below:
- It's quite a simple code and is self explanatory but still if you need help ask in comments and I will help you out.
Interfacing of Multiple Ultrasonic Sensor With Arduino
Hello friends, hope you are having fun and enjoying life. Today, I am gonna post about interfacing of multiple Ultrasonic sensor with Arduino. In the previous post, we have seen Interfacing of Ultrasonic Sensor With Arduino and in this post I have interfaced single ultrasonic sensor but in projects especially related to robotics, we have to interface multiple ultrasonic sensors. For example you have an obstacle detection robot, now in order to detect obstacle in front of robot you have to place once sensor on the front side but now you can't detect any object present on left or right side of your robot, so you have to place two sensors one on the left side of robot and one on the right side so in this project you need to use total three ultrasonic sensors, one on the front, one on left and one on right side of robot. Similarly, in another project I have to move the robot in a maze having walls on the side of robots, and my task was to move the robot straight within these walls without hitting the walls. In that case, I also used two ultrasonic sensors on both sides of robot and then applied PID algorithm in order to avoid hitting the walls. So, in short its a common practice to use multiple ultrasonic sensor with Arduino and today we are gonna have a look at how to do it.
I have posted about the basics of Ultrasonic sensor and how it works in my previous post so I am not gonna go into that detail. If you haven't read it then I recommend that you should first read Interfacing of Ultrasonic sensor with Arduino. Now, let's get started with Interfacing of multiple ultrasonic sensor with arduino, which isn't that difficult. :)
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:
Interfacing of Multiple Ultrasonic Sensor With Arduino
- Let me first summarize the working of ultrasonic sensor again. With ultrasonic sensor, what we need to do is to generate a trigger signal on its trigger pin for around 10 microsecond.
- As soon as the ultrasonic sensor gets this trigger signal, it sends out an ultrasonic signal.
- This ultrasonic signal then hits something and bounced back.
- Now, in order to check this bouncing signal, we have to read the Echo pin and check for how long it remains HIGH, and on the basis of this duration we calculate our distance with the object.
- This is the process for single ultrasonic sensor and when we are using multiple ultrasonic sensors, what we need to do is simply repeat the whole procedure for all the sensors one by one.
- First of all, we will generate the trigger pulse for first sensor and the read its echo pin and get the distance, then we generate the trigger pulse for second sensor and read its echo pin and so on for the third.
- So, here I am gonna use three ultrasonic sensor and the circuit diagram is shown below:
- I have tried my best while designing this image to make it simple but as there are too much wires so it has become a little complex.
- I am pointing out the pin configuration here so it will be easy for you to interface your sensors with arduino. The pin configuration is as follows:
- Vcc of all sensors will go into +5V of Arduino.
- GND of all sensors will go into GND of Arduino.
- Trig Pin of first sensor into Pin # 3 of Arduino.
- Echho Pin of first sensor into Pin # 2 of Arduino.
- Trig Pin of second sensor into Pin # 4 of Arduino.
- Echo pin of second sensor into Pin # 5 of Arduino.
- Trig Pin of third sensor into Pin # 7 of Arduino.
- Echo pin of third sensor into Pin # 8 of Arduino.
- After connecting the pins as discussed above, now copy the below code and upload it in your arduino board.
- After uploading the code in your arduino, open the Serial Terminal of Arduino software and you will start receiving the distances for all the three sensors.
#define trigPin1 3
#define echoPin1 2
#define trigPin2 4
#define echoPin2 5
#define trigPin3 7
#define echoPin3 8
long duration, distance, RightSensor,BackSensor,FrontSensor,LeftSensor;
void setup()
{
Serial.begin (9600);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(trigPin3, OUTPUT);
pinMode(echoPin3, INPUT);
}
void loop() {
SonarSensor(trigPin1, echoPin1);
RightSensor = distance;
SonarSensor(trigPin2, echoPin2);
LeftSensor = distance;
SonarSensor(trigPin3, echoPin3);
FrontSensor = distance;
Serial.print(LeftSensor);
Serial.print(" - ");
Serial.print(FrontSensor);
Serial.print(" - ");
Serial.println(RightSensor);
}
void SonarSensor(int trigPin,int echoPin)
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
}
- The code is quite similar to the one we used while interfacing single ultrasonic sensor with arduino, the only thing we changed here is the repetition.
- Before, we were using the same function SonarSensor() but calling it only once for our single sensor interfaced with arduino but now we are calling it three times for all the three sensors.
- Its kind of a generic code, you can interface more sensors with it if you want and what you need to do is only calling this function for the next interfaced sensor.
That's all for today, I think we have posted a lot on the ultrasonic sensor so I am not gonna post any more tutorial on this sensor and now I will start writing on some other sensor. You should also have a look at
Arduino Projects for Beginners. Thanks for reading and share it with your friends and help us grow. :)
Interfacing of Ultrasonic Sensor With Arduino
Today, we are gonna have a look on How to Interface Ultrasonic Sensor with Arduino. Few days ago, I have posted a complete tutorial on How to Use Ultrasonic Sensor Library in Proteus and later I have posted different examples on How to Simulate Ultrasonic Sensor in Proteus. Those posts were about Proteus Simulations and weren't about hardware interfacing, so I thought today let's interface it in hardware.
Simulation is a good starting point for projects but they are really far away from real world. It happened to me a lot of times that my simulations are working perfectly fine but when I design the same circuit in hardware then it says no I am not gonna work. :) So, the bottom line is never trust simulations, unless you properly test it on hardware. So, today I am gonna interface an Ultrasonic sensor with arduino and will check its output on the Arduino Serial Terminal.
1. Introduction to Ultrasonic Sensor
- "Ultrasonic Sensor HC-SR04 is a simple sensor which emits Ultrasonic Radiations from its transmitter and is used for measuring the distance between sensor itself and any obstacle in front of it. The sensor has a transmitter and a receiver on it."
- This sensor consists of four pins, which are:
- Vcc (+5V) : You need to provide +5V at this Ultrasonic Sensor HC-SR04 Pin.
- Trig (Trigger) : It's a trigger Pin where we need to provide a trigger after which this sensor emits ultrasonic waves.
- Echo : When Ultrasonic waves emitted y the transmitter, hit some object then they are bounced back and are received by the receiver and at that moment this echo Pin goes HIGH.
- GND : We need to provide ground to this PIN of HC-SR04 Ultrasonic Sensor.
Note:
- If you haven't bought your components yet for this project, then you can buy them from these reliable sources:
[ultimate_spacer height="13"]
|
[ultimate_spacer height="13"]
|
- Trigger pin is an output pin while the Echo pin is an input pin, we will discuss them in Working section in detail.
- Moreover, it requires +5V to start operating.
- It is normally used to detect objects in front of it or to measure the distance between different objects.
2. Working of Ultrasonic Sensor
- Its working is quite simple, as discussed above, it has a trigger and an echo pin.
- A signal of +5V is sent over to Trigger pin for around 10 microseconds in order to trigger the sensor.
- When ultrasonic sensor gets a trigger signal on its trigger pin then it emits an ultrasonic signal from the transmitter.
- This ultrasonic senor, then goes out and reflected back after hitting some object in front.
- This reflected ultrasonic signal is then captured by the receiver of ultrasonic sensor.
- As the sensor gets this reflected signal, it automatically make the Echo pin high.
- The time for which the Echo pin will remain HIGH, depends on the reflected signal.
- What we need to do is, we need to read this time for which the echo pin is high, which we are gonna do in our next section.
- So, let's have a look at Ultrasonic Sensor Arduino Interfacing.
3. Interfacing of Ultrasonic Sensor With Arduino
- Now we have seen the working of Ultrasonic sensor, so we have some idea what we need to do in order to get the values from it. Let's now have a look at Ultrasonic Sensor Arduino Interfacing.
- First of all, we need to generate a signal of 10 microsecond and then send it over to trigger pin.
- After sending the trigger pin we then need to read the echo pin and wait for it to get HIGH.
- Once it got HIGH then we need to count the time for how long it remained HIGH.
- On the basis of this time, we are gonna calculate the distance of the object from the ultrasonic sensor.
- So, first of all, interface your ultrasonic sensor with arduino as shown in below figure:
- Now, use the below code and upload it your arduino board. After uploading the code, open your serial terminal of Arduino software and you will start receiving the values.
#define trigPin1 8
#define echoPin1 7
long duration, distance, UltraSensor;
void setup()
{
Serial.begin (9600);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
}
void loop() {
SonarSensor(trigPin1, echoPin1);
UltraSensor = distance;
Serial.println(UltraSensor);
}
void SonarSensor(int trigPin,int echoPin)
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
delay(100);
}
- Now if you check in the SonarSensor() function, we are generating a pulse of 10 microsecond and sending it to trigPin, which is the trigger pin of our ultrasonic sensor.
- After sending this pulse weare using a funcion pulseIn() , its a builtin arduinofunction and is used to check for how long the echoPin remains HIGH.
- This value is further saved in the duration value and after that we have divided this duration by 2 because the pulse is first sent and then received so in actual it covers double distance, so we need to divide it by 2 in order to get distance between object and the sensor.
- Furthermore, it is again divided by 29.1, which is basically the speed of ultrasonic sound and finally we saved it in a variable named distance which is now in centimeters.
- After uploading the sketch in Arduino, you need to open the Serial Terminal and you will start receiving the values of distance.
That's all for today. I hope you have enjoyed this Interfacing of Ultrasonic Sensor with Arduino. It wasn't that difficult, in our coming post we are gonna
Interface Multiple ultrasonic sensors with Arduino and will get their values on the serial terminal. Till then Take care and have fun !!! :)
Receive SMS with AT Commands using Sim900 and Arduino
Update: I have updated the code and removed the bug. Thanks for informing. Now this code will work perfectly.
Buy This Project
Hello friends, hope you all are fine and having good health. Today, as the name suggests, I am gonna post on how to Receive SMS with AT Commands using Sim900 and Arduino. I have already posted a tutorial on How to Send SMS with Arduino UNO and Sim900, so now we are gonna check the opposite. Sending SMS is quite easy, you just need to write some AT commands and write the message you wanna send and hit the Cntrl + Z and it will be sent. But receiving a text message on your SIM900 shield is a bit difficult because now you need to place a check when user will send a message. So, ideally whenever anyone send a message to your SIM900 module, you should get notified. Today, we are gonna cover this how to receive SMS with AT Commands in detail.
Now, after you get notified, there's a need to read the message as well and also who has sent this message. So, we are also gonna cover it today. So, first of all we will place a check that whenever someone sends a message to our SIM900 module, we get notified and after that we will extract the message and the mobile number of sender. We have designed this code after a lot of effort that's why this code isn't free but we haven't placed a very small amount of $20 so that engineering students can also buy it easily. We can also interface our GSM board with other microcontrollers like PIC Microcontroller as well as 8051 Microcontroller. I have also posted tutorial on How to Receive SMS with SIM900 & PIC Microcontroller and How to Send SMS with PIC Microcontroller so if you are working on PIC Microcontroller then you must give it a look. So, let's get started with How to receive SMS with AT Commands using SIM900 and Arduino.
You must also check GSM Library for Proteus, using this library you can easily simulate your GSM module in Proteus ISIS. Moreover, also have a look at Send SMS with Sim900D in Proteus ISIS in which I have designed a simulation of sms sending in Proteus ISIS.
Receive SMS with AT Commands using Sim900 and Arduino
- There are many GSM modules available in the market so it doesn't matter which one you are using unless its having SIM900 module in it.
- I have explained in my previous post that all GSM modules work on AT commands, so here first of all we are gonna have a look on AT commands we are gonna use for receiving the SMS.
- ATE0 - IT is used to turn off the Echo of GSM shield.
- AT - Just to check that your GSM module is working fine.
- AT + CMGF = 1 - This command will convert the message style to text. In other words we are telling our shield that we are expecting a text message.
- AT+CNMI=1,2,0,0,0 - This command will alert our GSM shield and now whenever it will receive message, it will automatically send an alert on the serial port.
- We are gonna use these four commands in our code and we will be able to receive text message on the GSM shield.
- Remember we have to put Enter after each of the above AT commands in order to execute it.
- Below is the first phase of the code and as you can see in this code we are simply sending these four commands serially from arduino to GSM shield.
- These are two functions I have shown below, the first function is Config() which is simply sending the commands via serially and then the Response() function which is called after every AT command and is receiving the response of that AT command.
- So, here's the partial code for How to Receive SMS with AT Commands using Sim900 and Arduino.
void Config()
{
delay(1000);
Serial.print("ATE0r");
Response();
Serial.print("ATr");
Response();
Serial.print("AT+CMGF=1r");
Response();
Serial.print("AT+CNMI=1,2,0,0,0r");
Response();
}
void Response()
{
int count = 0;
Serial.println();
while(1)
{
if(Serial.available())
{
char data =Serial.read();
if(data == 'K'){Serial.println("OK");break;}
if(data == 'R'){Serial.println("GSM Not Working");break;}
}
count++;
delay(10);
if(count == 1000){Serial.println("GSM not Found");break;}
}
}
- The response of these commands is shown below on the Serial Monitor of Arduino.
- For each AT command, we get a response "OK" from the GSM shield.
- Now, I know that I have sent all these four AT commands and my GSM shield is ready to receive the text messages and will inform me.
- So, when you send a message to your GSM shield, it will give a notification as shown in the below figure:
- Each message received by SIM900 module is start with "+CMT" and after that it has the mobile number of the sender and at the end lies the body of the message, which in our message is "www.TheEngineeringProjects.com"
- So now let's extract this mobile number and the text body from this CMT string.
Getting the SMS Text & Sender Mobile Number
- Till now we have learnt How to Receive SMS with AT Commands using Sim900 and Arduino and send you notification over the serial monitor.
- Now we have to place some checks in our code so that we could be able to get the required data out of this string.
- In order to do so, I am gonna first save this CMT string into an array, which I named as RcvdMsg[index].
- But before saving the data into this string, first I need to make sure that I am actually getting the requried string, that's aso possible that I am receving some garbage values.
- So, I placed a check first, which is checking for these four characters "+CMT", and when I got these character on my serial terminal I got sure that I have the string ready so I made the index = 0 and starting receving the string.
- Next thing I need to do is make sure that I have got the complete string, that was really a tricky part as there's no end character in the string.
- So, I used "n" null character for that. If you check the string then you can see that we are getting two null characters in complete string.
- I placed this check that when I get 2 null characters means I have got the complete string so I stopped receving the string.
- After that I simply count the charaters, in my string the sender mobile number is at posting 4 to 16 so I made a loop and save it in another array. and similarly did for the message text.
- Now when I send message after uploading this final code into my Arduino board, I get the below result on my Serial Monitor.
- Isn't it cool :) So, now we have separated the complete text as well as the sender's mobile number from our GSM string and we can use it anywhere we want.
- We can use this mobile number in the previous post code and can reply some text back and can also give a missed call to the user, anything we want. I am gonna post on How to send a call using SIM900 in the next post.
- You can buy the codefor How to Receive SMS with AT Commands using Sim900 and Arduino from our shop by clicking the below button:
Buy This Project
- I have highlighted all the functions in the code.
- As I always say, understand it first and then write on your own and do mistakes so that you learn.
That's all for today. I hope you have enjoyed this project named Receive SMS with AT Commands using Sim900 and Arduino. I will meet you guys in the next post. Till then 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.
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
Arduino Lilypad Library for Proteus
Hello friends, few day ago I have posted a tutorial on how to do Arduino Simulation in Proteus. In that post, we have used an Arduino Library for Proteus but as this library is in its initial phases that's why currently it supports only three basic Arduino boards which are Arduino UNO, Arduino Mega2560 and Arduino Mega1280. But as we know there are numerous Arduino boards which are used these days. So, I searched a little and I came across this amazing Arduino Lilypad Library for Proteus which has the support for few other arduino boards, so I thought to share it with you guys. I have tested this library myself as always and its 100% working. I have tested it on Proteus 7 and I think it will work fine on Proteus 8 as well. As we have the support for above three boards in the previous library so the two new boards here are Arduino Lilypad and Arduino Nano, both of them are quite used these days. I have explained it in detail, step by step below, if you still feel problem in any step then ask in comments.This library has the support for following boards:
- Arduino UNO
- Arduino UNO SMD
- Arduino Mega
- Arduino Nano
- Arduino Lilypad
Note:
- This library isn't designed by our team so all credit goes to its creator, who is blogembarcado. Hats off dude !!!
- We are just spreading the knowledge so that more and more engineers could get benefit out of it.
- I have also posted Ultrasonic Sensor Library for Proteus, which you can download, using this library you can simulate Ultrasonic Sensor in Proteus, moreover you can also download different examples on Ultrasonic Sensor Simulation in Proteus to get a complete grip on this sensor.
Arduino Lilypad Library for Proteus
- First of all, download this new Arduino Lilypad Library for Proteus by clicking on the button below:
Arduino Lilypad Library for Proteus
- Once you downloaded the rar file, extract the file named as "BLOGEMBARCADO.LIB".
- Now place this file in the library folder of Proteus, which, in my case, is "C:\Program Files (x86)\Labcenter Electronics\Proteus 7 Professional\LIBRARY". I hope it will give you the idea where to place the file.
- After placing the file in this folder, now open the Proteus ISIS and click on the component selection button.
- In the search box write "Arduino" and the list of all the arduino boards will be shown immediately as shown in the below figure:
- You can see all the five boards in the above figure and you can select any of them.There's also another components in the list which is ultrasonic sensor. Yes, this library also supports ultrasonic sensor but I haven't tested it yet that's why didn't mentioned it, I will test this sensor soon and then will also explain its working.
- Now you can select any of these boards and can start working on them rite away. All the five boards are shown in the below figure:
- The two new Arduino boards in this library are shown below:
- So, now simply design your circuit and write the code in the Arduino ide. After writing the code, get the hex file from arduino software and upload it to these boards.
Note:
- In order to upload the hex file simply double click it and the properties window will pop up. In the Properties window, there will be an option named Program File. In this Program File, browse for the hex file and upload it.
- Now run your Proteus simulation and it will work like charm.
- I will post few projects on these boards soon as soon as I get time to write them, so stay tuned and have fun.
- I have posted a small project on how to use Arduino Lilypad in Proteus which you can read and download from Arduino Lilypad Simulation in Proteus.
Getting Data From Webserver using Arduino Wifi
In today’s post, as the name suggests, we will see how to get data from online webserver using Arduino Wifi in simple steps. Getting data from web server using Arduino Wifi Shield has always remained a problem for the engineers. Its not much difficult task as its usually considered to be. In today’s post, I will create a small project in which I will control two simple LEDs via online web server. It’s really a very interesting project and when I completed it, I felt like Hurrah!!!
Arduino Wifi Shield is used to connect Arduino board with Wifi. After connectivity with Wifi, one can perform many tasks using this shield. We can built a complete server on it and can also use it as a client. Server designed on an Arduino Wifi Shield are usually quite simple as it doesn’t have much processing power to support heavy server. Arduino Wifi Shield is mostly used in home automation projects where home appliances are controlled by Wifi or can also be used for security purposes. In short, it has numerous applications and is widely used.
In today’s project, we will use Arduino UNO board for programming purposes, and will interface two leds with it and then we will control these leds via an online web server. Using that online web server, we will ON and OFF these leds on command. For controlling leds from an online server, we have to design two things:
- Online Web Server.
- Arduino Web Client.
Note:
- The complete project has been sent to all the subscribed members. If you want this project code, then Subscribe to our mailing list, and it will be automatically emailed to you as well.
Project Description
First of all, I will explain what we are doing and what we want to achieve. In hardware, we will use:
- Arduino UNO
- Arduino Wifi Shield
- LEDs x 2
- 10k ohm x 2
Their arrangement and pin configuration is shown in the Arduino Web Client section. We will arrange them in such a way that two leds will be mounted on the Arduino UNO shield. In web server, we will design a simple page, which will be having four buttons on it, which will be:
- LED 1 ON
- LED 1 OFF
- LED 2 ON
- LED 2 OFF
When someone will open this web page and will pres any of these buttons, respective task will be performed on the Leds. i.e. if someone pressed the LED 1 ON button then Led 1 present on the Arduino board will get ON and when someone press LED 1 OFF button, that Led will go OFF and same function will be performed for second led. There won’t be any connection between the hardware and that web server, the only connection will be the Wifi. The Arduino Shield must have a Wifi connection available and one sitting from across the world can control them. Now let’s discuss these two parts, one by one.
Online Web Server
I have designed the online web server on my own site The Engineering Projects. This is a php page which I have uploaded on my web server. In order to make this page, simply follow the below steps:
- Create a notepad and rename it to ArduinoWifi.php and save it somewhere, from where you can easily access it.
- The webserver code is for sale and you can buy it just for $50. We have input a lot of effort to accomplish this project that's why we have placed a very small amount on it. You can easily buy it by clicking the below button.
Buy WebServer Code
- Save the file again and our web page is now ready to be uploaded. This web page will act as a web server for the Arduino device and will send commands to it.
- Now we need to upload this web page on some website so that it can start working. In order to do so, you must have some web domain and hosting as I have mine on Godaddy or you can also use some free web hosting service.
- What this code is doing, its actually using a file system. Whenever any button on this web page is pressed, it simply create a txt file with a letter. In this code, when someone pressed LE 1 ON button, character “1" is saved in the txt file. Similarly character “2" is saved in the txt file when LED 1 OFF is pressed and so on.
Note:
- When you upload the webpage on the web server, then hit any button and check your web location where this page is uploaded, you must find a data.txt file in the same location.
- If you can’t find the data.txt then generate it by yourself because in some web servers, generation of such files automatically is not granted.
We are done with the Web Server part, now let’s come to the Arduino Web Client part.
Arduino Web Client
- First of all, place the Arduino Wifi Shield over the Arduino UNO shield, as shown in the below figure:
- Now, you need to place the two leds on two your Arduino UNO. The pin configuration for these LEDs are shown in the below figure:
- Two leds are connected to pin no 3 and 4 of Arduino UNO board and are pulled down.
- Now connect your Arduino UNO board with the computer and burn the below sketch into it.
#include <SPI.h>
#include <WiFi.h>
char ssid[] = “EvoWingle-12F3“; // your network SSID (name)
char pass[] = “093B3453“; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
char server[] = “www.theengineeringprojects.com“; // name address for Google (using DNS)
String location = “/Examples/data.txt HTTP/1.0“;
char inString[500]; // string for incoming serial data
int stringPos = 0; // string index counter
byte statusLed = 0;
char c;
int led1 = 3;
int led2 = 4;
WiFiClient client;
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
boolean lastConnected = false; // state of the connection last time through the main loop
const unsigned long postingInterval = 10*1000; // delay between updates, in milliseconds
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(“WiFi shield not present”);
// don’t continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print(“Attempting to connect to SSID: “);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(“Connected to wifi”);
printWifiStatus();
Serial.println(“nStarting connection to server…”);
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println(“connected to server”);
// Make a HTTP request:
client.print(“GET “);
client.println(location);
client.println(“Host: theengineeringprojects.com”);
// client.println(“Connection: close”);
client.println();
//readPage();
}else{
Serial.println(“connection failed”);
}
}
void loop(){
while (client.available()) {
c = client.read();
Serial.write(c);
CheckingStatus();
}
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println(“disconnecting.”);
client.stop();
}
if(!client.connected() && (millis() – lastConnectionTime > postingInterval)) {
PingRequest();
}
lastConnected = client.connected();
}
void PingRequest(){
if (client.connect(server, 80)) {
// Serial.println(“connected to server”);
// Make a HTTP request:
client.print(“GET “);
client.println(location);
client.println(“Host: theengineeringprojects.com”);
client.println(“Connection: close”);
client.println();
//readPage();
lastConnectionTime = millis();
}else{
//Serial.println(“connection failed”);
client.stop();
}
}
void CheckingStatus(){
inString[stringPos] = c;
if(c == ‘*’)
{
statusLed = inString[stringPos - 1];
stringPos = 0;
// Serial.write(statusLed);
delay(500);
UpdatingStatus();
// delay(500);
// client.flush();
// delay(10000);
//PingServer();
}
stringPos ++;
}
void UpdatingStatus(){
if(statusLed == ’1')
{
digitalWrite(led1, HIGH);
// Serial.write(‘OK’);
}
if(statusLed == ’2')
{
digitalWrite(led1, LOW);
}
if(statusLed == ’3')
{
digitalWrite(led2, HIGH);
}
if(statusLed == ’4')
{
digitalWrite(led2, LOW);
}
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(“SSID: “);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(“IP Address: “);
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(“signal strength (RSSI):”);
Serial.print(rssi);
Serial.println(” dBm”);
}
- Before burning this sketch into your Arduino Shield, you need to change few things which I have written in bold style in the above code, and mentioned below:Now, everything’s done, so power up your Arduino and make sure that it has got connected with the Wifi and then hit the LED 1 ON button on your web page. If everything’s gone fine then the led on your Arduino board will get ON.
- ssid is the name of your Wifi connection.
- pass is the password of your wifi connection.
- server is the server name on which the web page is uploaded, which in my case is my own site.
- location is the location of the txt file generated by the webpage, the above web page code generated a txt file in the same location and gives it a name data.txt so I simply used that. (This part is bit confusing but read it twice and you will get it.)
- I have added comments with the Arduino code but if still, you get into some trouble, ask in comments and I will try my best to resolve them.
Note:
- Before starting anything, first run the demo code which comes with the Arduino Library and make sure that your Arduino Shield get connected with your Wifi connection.
- Give the link of txt file generated by the web page, not the the web page itself.
That’s all for today, Stay Blessed, take care. :))