Education – Deep Focus https://fazals.ddns.net/ Embrace it! Thu, 04 Feb 2021 09:07:01 +0000 en-US hourly 1 https://wordpress.org/?v=5.6.1 https://fazals.ddns.net/wp-content/uploads/2020/08/react-native-300-150x150.png Education – Deep Focus https://fazals.ddns.net/ 32 32 173186184 Sampling theorem | Verification of NYQUIST’S sampling theorem using MATLAB https://fazals.ddns.net/sampling-theorem-nyquists-theorem-using-matlab/ Thu, 04 Feb 2021 08:18:32 +0000 https://fazals.ddns.net/?p=3168

We all know that there are two kinds of signals:
1. Analog Signals
2. Digital Signals
We know that the signals that exists in nature are analog by default. And we also know that the signals that we store on our computers and memory devices like pen-drives, hard disks, SD cards and so on are of-course digital in nature.
Now the question that might come to your mind:

how do you convert an analog signal to a digital signal?

The answer to that is simple, first we sample the analog signal, and then we quantize it. Sampling is a process where in you hold the analog signal’s amplitude for a brief amount of time, so that the continuous time and continuous valued signal, becomes discrete time, continuous valued signal.

Sampling Theorem
The given image simply demonstrates how an analog signal in sampled.

Sampling Theorem

Now, there’s a theorem that governs the sampling process. Harry Nyquist, a Swedish electronic engineer came up with it. Now, it’s known as the sampling theorem.

Sampling Theorem states that the minimum sampling rate for an analog signal, when uniformly sampled is two times that frequency of the analog signal being sampled. Or in simple words, the sampling frequency must be twice that of the signal being sampled.

This minimum frequency, or the sampling rate is also called as the Nyquist rate.

Proving Sampling Theorem in MATLAB.

So basically, we need to prove that when a signal is sampled at a frequency less than the Nyquist Sampling rate, proper recovery of the signal is not possible. We can easily prove it in the frequency domain. When the sampling frequency is less than Nyquist Rate, we can show that the recovered signal’s frequency is not same as that of the actual analog signal.

MATLAB Code to prove Nyquist Sampling Theorem

You can download the complete code at the end of this post.

Before we start, we make sure that the workspace is cleaned.

clear all;
close all;
clc;

Next, we initialize all the required variables

widthOfTheLine = 1.5;
numberOfWaves = 5; % Number of waveforms to be shown
messageSignalFrequency = input("Enter the Message Signal Frequency: "); % Taking the user's input for Message Signal Frequency
initialSamplingFreq = 50*messageSignalFrequency; % Sampling Frequency for Unsampled Signal
timePerSample = 1/initialSamplingFreq; % Time needed for a single sample
stopTime = 1; % Samples to be generated up to.
timeAxis = 0:timePerSample:stopTime-timePerSample; % Generating the time axis
totalNumberOfSamples = size(timeAxis,2); % Calculating the number of samples
samplingFrequencyInterval = initialSamplingFreq/totalNumberOfSamples; % Calculating the frequency interval to generate the frequency axis;
frequencyAxis = -initialSamplingFreq/2:samplingFrequencyInterval:initialSamplingFreq/2-samplingFrequencyInterval; % Generating the Frequency Axis
phiDegrees = 90; % in degrees
phi = phiDegrees * pi / 180;
  1. widthOfTheLine – It is the width of the line on the plot.
  2. numberOfWaves – Number of waves of the signal to be shown on the plot.
  3. messageSignalFrequency – Frequency of the signal to be sampled.
  4. initialSamplingFreq – It is 50 times that of the message signal frequency, just to show the unsampled analog signal as smooth as possible.
  5. stopTime – Samples will be generated up to stopTime.

We take a 90 degree phase shift so as to avoid the “0” sampled signal value for a perfectly sampled signal. You could easily replace the sin with a cos function and avoid adding the phase shift to the signal.

Check Out my other Posts

]]>
3168
Timers | Toggling in 8051 every 1 second using timer delay https://fazals.ddns.net/toggle-a-pin-in-8051-every-1-second-using-timers/ Tue, 19 May 2020 17:48:04 +0000 https://fazals.ddns.net/?p=1322 The 8051 or the AT89C51 is an 8-bit microcontroller. The 8051 microcontroller was designed long ago by Intel. It has a 40 pin DIP – Dual Inline Package. It has 4 kilobytes of ROM, 128 bytes of ram, two internal timers, and 5 interrupts. Namely, INT0, TF0, INT1, TF1 and RI/TI. The order of priority is same as the order they are written. It also has 1 non-maskable interrupt – RESET.

There are 2 timers available in the 8051. The timer0 and the timer1, and there are 4 modes in which both of these timers can be configured. And each of it can be configured as a Timer or as a Counter.

Difference between timers and counters

Timer in 8051 is used to provide timing or delays between two events in the controller. Whereas, a counter is used to count the number of events. The TMOD or the Timer MOD register, which is a byte addressable register, is used to configure the timer/counter.
Consider the TMOD register as shown below. The 0th and the 1st bit is used to configure the modes for timer0, and the 4th and 5th bit for timer1.
The 2nd and the 6th bit is used for configuring it in either timer mode or counter mode for timer0 and timer1 respectively. If the 2nd/6th bit is 0, its configured as timer, else it’s in counter mode.

The TMOD Register in 8051
  1. Gate: The gate bit decides whether the timer is controlled – RUN or STOP, with the internal interrupts, TR0 and TR1 or the external ones – INT0 & INT1.
  2. C/T: This bit decides whether to operate in timer mode or in counter mode
  3. M0, M1: These bits decides the mode of operation of the timers.

Timer modes in 8051

There are 4 timer modes in the 8051 microcontroller.

  • Mode 0
    Mode 0 is a 13-bit timer/counter. All the 8 bits from the upper byte are used with 5 most significant bit from the lower byte. Timer in this mode can be used by status check method. Maximum delay in this mode is 8.8 millisecond at a crystal frequency of 11.0592 MHz.
  • Mode 1
    When using mode 1, the timer/counter is configured in 16-bit mode. To be specific, it’s counts all the way from 0x0000 to 0xffff. And this mode gives a maximum delay of 71.106 millisecond, again at a crystal frequency of 11.0592 MHz.
  • Mode 2
    In mode 2 configuration, the timer/counter works in 8 bit mode but has a special feature this time. It has auto reload capacity. Meaning that, it can run continuously, all on its own, reloading the timer with the value stored in the higher byte. This mode is usually used for setting the baud rate for serial communication.
  • Mode 3
    Mode 3 is a split mode where in the timer or counter operates in the 8-bit mode. The TL0 uses the timer flag TF0, where as the TH0 uses the timer flag TF1. Yes, its timer0 using flags of both timer0 and timer1.

The concept of delays and timers

Now that you know the basic working of the timers in the 8051 microcontroller, let’s go through the concept of delays.
Delays are nothing but the cycles of operation with in the controller where the controller does nothing, literally nothing. If you know any programming language, its similar to a for or while loop that does nothing.

The most common clock frequency in the 8051 is 11.0592 MHz. The main reason to use this frequency is it compatibility with the most common baud rates in serial communication. Now, this clock frequency will give us a machine cycle time period of 1.085 microsecond. For a delay of 1 second, we need 921600 machine cycles.

We will be using timer0 in mode 1 configuration. Since it’s a 16-bit timer the maximum delay will be 71.11 millisecond. So, we need to run the timer for 14 complete cycles + 4096 machine cycles. I’ll leave the calculations to you.

So, now that we are done with the theory. Let’s have a look at the code.

The Assembly Code

				org 0000h
					mov p1, #00h
					mov tmod, #01h
loop:				cpl p1.5    ;compliment pin 1.5
					acall delay
					acall smallDelay
					sjmp loop

;the subroutine delay is to loop for 14 complete 16-bit timer cycles
;and the subroutine smallDelay is for looing for 4096 times.
;the rest of the code is self explainatory. 					
					
delay:				mov r0, #14
					mov tl0, #00h
					mov th0, #00h
					setb tr0
timerLoop:			jnb tf0, timerLoop
					clr tf0
					djnz r0, timerLoop
					clr tr0
					ret

smallDelay:			mov tl0, #00h
					mov th0, #0f0h
					setb tr0
timerLoop2:			jnb tf0, timerLoop2
					clr tr0
					clr tf0
					ret
					
					end

Download the code from here.
This code will result in toggling of pin 1.5 every second, only if operating at 11.0592 MHz. The C-equivalent code for the same program is also geven.

The embedded C Code | 8051 timer programming in C

#include<reg51.h>

sbit pin = P1^5;

void delay(){
    int i;
    TMOD = 0x01;
    for(i=0; i<1000; i++){
				TH0 = 0xFC;
				TL0 = 0x66;
				TR0 = 1;
        while(TF0 != 1){
            ;
        }
				TR0 = 0;
        TF0 = 0;
    }
}

void main(){
    while (1)
    {
        pin = ~pin;
        delay();
    }
    
}

Download this code from my Github.
That completes the part of toggling any pin with a delay of exactly 1 second.

Read more posts on 8051 from here.

FAQs

How do I change the pin that has to be toggled?

You can do that by simply changing the line cpl p1.5 or the line sbit pin = P1^5; in embedded C to the required pin. You can also modify the code to toggle an entire port instead of a single pin.

What’s the difference between a Timer and a Counter?

I suggest you read this again.

How do I change the time for toggling?

Simply change the delay function, by changing the value in the TH0 and TL0.

What are the different timer/counter modes in 8051

]]>
1322
Latest Spectrum Analyser using Python | Part-2 https://fazals.ddns.net/spectrum-analyser-part-2/ Mon, 11 May 2020 01:31:12 +0000 https://fazals.ddns.net/?p=1002 Latest Spectrum Analyser using Python | Part-2 Read More »

]]>

Since we have already built spectrum analyser in part 1, where we use the PyAudio Python library to open the microphone and bring in raw binary data into the code. Convert that binary data into 16-bit integers and displayed them on a Plot using the MatPlotLib’s PyPlot.
If you have not built it in the part one, click here and build the part 1 as this part will be a continuation to that.

The algorithm to calculate the Spectrum

We will be using the FFT or the Fast Fourier Transform to calculate spectrum for the spectrum analyser. Now, FFT is an algorithm that computes the Discrete Fourier Transform. In short the DFT of a sequence of signal to represent it in frequency domain.
There are many different FFT algorithms based on a wide range of published theories, from simple complex-number arithmetic to group theory and number theory. The one we will be using is the python fft algorithm from the library Numpy.

Package 📦 to import for fft in Python?

As far as the the part of the code which calculates the FFT of a sequence, there are many libraries that offer simple classes to do so. Since we already imported Numpy. And since it already provides the class or method to calculate the FFT. We will not be importing any new library.

Also, take a note that there are other libraries available that compute the FFT of a sequence of signal.

The code for audio spectrum analyser / audio visualizer

Since we have already coded in the first part, we will only be making a few changes to the code, a few additions and then we will be good to go. If you don’t have the code get it from here.

Now in the part where we initiallise the plot objects, that is to say the figure and the axises, make the following changes.

Instead of

fig, ax = plt.subplots()

make it

fig, (ax,ax1) = plt.subplots(2)

and add the following lines, to the code. The first line creates a one dimentional array containing the values from 0 uptill 44100 with number of parts equal to the size of CHUNK. And the next line sets the X axis as semilog since the frequency representation is always done on semilog plots.

x_fft = np.linspace(0, RATE, CHUNK)
line_fft, = ax1.semilogx(x_fft, np.random.rand(CHUNK), 'b')

Since the output of the FFT computations are going to range from 0 to 1. We change the Y limits of the frequency plot. And also, since the computation produces a mirror of the spectrum after half the sampling rate. We dont need the part after half the sampling rate, that is after 22050. And hence we change the X limit also.

ax1.set_xlim(20,RATE/2)
ax1.set_ylim(0,1)

And then in the infinite loop, add the following lines to compute the FFT and plot it.
Since the computed FFT contains both the real and the imaginary part. We take the absolute value of the returned FFT spectrum, multiply it by 2, and then divide it by 33000 times CHUNK to produce a plot with Y values ranging from 0 to 1.

line_fft.set_ydata(np.abs(np.fft.fft(dataInt))*2/(33000*CHUNK))

The Complete code

import numpy as np #importing Numpy with an alias np
import pyaudio as pa 
import struct 
import matplotlib.pyplot as plt 

CHUNK = 1024 * 1
FORMAT = pa.paInt16
CHANNELS = 1
RATE = 44100 # in Hz

p = pa.PyAudio()

stream = p.open(
    format = FORMAT,
    channels = CHANNELS,
    rate = RATE,
    input=True,
    output=True,
    frames_per_buffer=CHUNK
)



fig, (ax,ax1) = plt.subplots(2)
x_fft = np.linspace(0, RATE, CHUNK)
x = np.arange(0,2*CHUNK,2)
line, = ax.plot(x, np.random.rand(CHUNK),'r')
line_fft, = ax1.semilogx(x_fft, np.random.rand(CHUNK), 'b')
ax.set_ylim(-32000,32000)
ax.ser_xlim = (0,CHUNK)
ax1.set_xlim(20,RATE/2)
ax1.set_ylim(0,1)
fig.show()

while 1:
    data = stream.read(CHUNK)
    dataInt = struct.unpack(str(CHUNK) + 'h', data)
    line.set_ydata(dataInt)
    line_fft.set_ydata(np.abs(np.fft.fft(dataInt))*2/(11000*CHUNK))
    fig.canvas.draw()
    fig.canvas.flush_events()

Then, when you run the program, you should be able to see the time domain as well as the frequency domain representation of the sequence from the microphone.

Spectrum Analyser

You shoud be able to get plots similar to one given above. Use this website to generate pure sine/square/triangular waves with any frequency you want to test out this project.

Liked the project? Drop your reviews in the comment section, and share it among your fellow mates. 👍🏻
Check out my other posts.
Follow me on Social Media 👇👇👇

]]>
1002
How to connect seven segment display with 8051| Easiest method | Proteus Simulation https://fazals.ddns.net/seven-segment-display-with-8051-proteus-simulation/ Sat, 02 May 2020 10:21:25 +0000 https://fazals.ddns.net/?p=745 How to connect seven segment display with 8051| Easiest method | Proteus Simulation Read More »

]]>
In this post you will learn how to interface seven segment display with the 8051 microcontroller (AT89C51) in multiplexed method, alternatively rolling seven segment display in a simulation software called Proteus.

The basic concept behind multiplexed seven segment display is to turn on one display at a time, at a rate so fast that it seems to our eyes that all of the displays are turned on. I will be using 8 such displays and show you how to use them in the right way.

Introduction to seven segment display

As it can be seen from the picture beside that the digit 8 is made up of 7 segments which can be indivisually turned on or off to display a character. Also, make a note that it can be used to display all the numbers, but not all the letters. For instance, letters like Z, N, G, J, K, M, Q, R, and so on can’t be displayed. While letters like O, B, D cause a lot of confusion when interpreting.

The displays can be used in 2 modes or 2 configurations.
1. Common Anode (common +ve terminal)
2. Common Cathode (common ground)
We will be using the 2nd one, the common cathode or the common ground because it causes less confusions in logics.

We will be using the entire 8 bit port. So we have to connect led A to the MSB, led B to next LSB and so on up till the last one. This will make the led G connect to the last but one bit. The last bit will have to be connected to the DP, or the point.

So inorder to display the letter A, you must turn on led E, F, A, B, C, G and turn off the rest. That combination would give us 11101110 in binary that has to be sent to the required port. Like wise, to display the letter E, would have to send 10011110 in binary to the required port. This covers the basics.

The Hardware

Indeed the first thing you need to do is to set up the hardware. Connect the seven segment displays as shown in the schematic. If you have indivisual displays and not blocks of them. Just connect them in parallel and then connect them to the microcontroller.

Seven Segment Display
The 8051 μController

The assembly code

In order to use the seven segment display, we need to use the lookup table method. Lookup table method is a way to access the data based on the addresses or in programming terminology, the indexed. So we will write the table starting from location 500h on the ROM as follows.

org 500h
numbers: db 11111100b, 01100000b, 11011010b, 11110010b, 01100110b, 10110110b, 10111110b, 11100000b, 11111110b, 11110110b
_H: db 01101110b
_E: db 10011110b
_L: db 00011100b
_O: db 11111100b
_A: db 11101110b
_F: db 10001110b
_Z: db 11011010b
_C: db 10011100B
_: db 00000001b

The 1st bit from the right, in other words, the LSB, corresponds to the point (DP) led on the seven segment display. So sending the value 00000001b to the displays will turn on the point. The MSB bit corresponds to the segment A, the next bit to B, the next one to C and so on up to G.

The main program

org 0000h
mov p1, #0ffh
mov p2, #00h

Port 1 is set to turn off all the displays, and Port 2 is cleared to configure it as output port.

startOver:mov dptr, #_H
acall display1
mov dptr, #_E
acall display2
mov dptr, #_L
acall display3
mov dptr, #_L
acall display4
mov dptr, #_O
acall display5
mov dptr, #_
acall display6
mov dptr, #_
acall display7
mov dptr, #_
acall display8
sjmp startOver

the command mov dptr, #_H loads the hex value of code from the lookup table. Since we have used 8 displays in multiplexed mode, the subroutine acall display1 send the data to 1st display and turns the display ON for some time and then turns it OFF. Similarly, acall display2 sends the data to 2nd display, turns it ON for some time and then turns it OFF. The rest of the commands similar to acall display* send the data to corresponding display, turns it ON for some time and then turns it OFF again.

Since this process is repeated at a very high rate, our eyes perceives them as if all the displays are turned ON simultainously.

acall routine:clr a
movc a, @a+dptr
mov p2, a
acall lessDelay                   ;CAN BE OMITTED
ret

display1:clr p1.7
acall routine
setb p1.7
ret

display2:clr p1.6
acall routine
setb p1.6
ret

display3:clr p1.5
acall routine
setb p1.5
ret

display4:clr p1.4
acall routine
setb p1.4
ret

display5:clr p1.3
acall routine
setb p1.3
ret

display6:clr p1.2
acall routine
setb p1.2
ret

display7:clr p1.1
acall routine
setb p1.1
ret

display8:clr p1.0
acall routine
setb p1.0
ret

Now the delay function is as follows. You can omit the delay part if you want

lessDelay:mov r0, #0fh
loop5:mov r1, #127
loop4:djnz r1, loop4
djnz r0, loop5
ret

Download the assembly language codes, .asm file as well as the Proteus file from here.

You can customize the code and workaround to have your content displayed.

Visit my github github icon page for more codes like this.

Intrested in creating a website for free ? Or setting up your own Blynk server for IoT ?

Care to share.😄

]]>
745
What is cloud ? | Google Cloud Platform in 10 mins. https://fazals.ddns.net/what-is-cloud/ Sun, 26 Apr 2020 08:12:28 +0000 https://fazals.ddns.net/?p=790 What is cloud ? | Google Cloud Platform in 10 mins. Read More »

]]>
So the first question I’m going to answer is what is cloud? So before I answer that question specifically, let’s cover a little bit of history.

The history behind cloud

I’m going to go through three different stages of how companies and people use computers. And then we’re going get into what cloud actually is.

So first of all, we’re gonna look into the world as we used to know it.Whice is, when companies were in the on premise world, so basically this is back in the day.

let’s say I’m a startup and I’m spinning up the newest social media website, let’s call it like facenotebook.com or something like that. And I have five users at that point. I have one server sitting in my closet and I have one person just managing that server. Everything’s fine because I only have five users.
The next day though, word spreads and I have a thousand users, and then my website keeps crashing, why is that happening ? Does anyone know the answer?

It’s because I only have one server and, one server is not capable of handling that heavy traffic. So I have to do something called as scaling. And nowadays if we think about scaling, that’s another buzz word that startups love to use. But back in the days scaling was this. I had to go to a store, buy a brand new computer, put it on top of the other computer in my closet. Download code on that, do a bunch of other stuff to add it to my network. And then it could handle a thousand users and that took almost an entire day. That was a huge headache.

And so, this was just that’s basically one of the things that led to cloud.

What’s time sharing?

But the pain point is what led to the thing called time sharing. So we have startups that have these computers. But the other side of the aisle, we have these huge companies think like IBM, Google, and they have a lot of money they can buy gigantic sets of computers. They don’t need to guess and say,

“okay, we have a thousand users today, and what if I have a million tomorrow and then we are going to buy that many computers to basically manage that traffic.”

IBM and Google, they could just go out and buy a million computers, right? But what if they over-budget and now they have like 200 computers that are not being used. And then one smart person says

“hey let’s rent these out. Let’s allow other companies like these startups to rent out these computers for certain amounts of time. So that then it’s cheaper for them and we’re making passive income.”

And so that’s how we got to the idea called time sharing.

The emergence of “the cloud”

And then this got more and more popular and it just became mainstream. It became very normal for smaller startups companies to go to large companies and rent out their computers for a certain amount of time.

And then, after a while these bigger companies said,

“oh! What if we can make more money off of this time sharing thing? What if we provided additional services on top of this infrastructure that we’re renting out?”

And these additional services, or the suite of services that was created then is what’s called as cloud.

So cloud is often broken up into three different umbrellas or categories of tools. And the first set of tools is what’s known as infrastructure as a service. Infrastructure as a service is timesharing. That is if you have a computer and you are not using it all the time. So you sell it for a certain amount of time to other companies.

You have storage discs. You sell it, that’s infrastructure. It’s literally the hardware that you can touch and feel. So you are selling that. And then companies said –

“what if we can add additional tooling to this infrastructure? What if we just had a tool that could handle tens of millions of users?”

It’s basically infrastructure with some software involved – The second set of tools.

And then lastly is software as a service. This is basically the tools that you know. Like Google Docs ,Drive, Slides and Sheets.

In conclusion cloud is a set of tools that helps developers spend less time managing and spend more time creating.

And so now what is GCP? and the services it offers

GCP or the Google Cloud Platform is obviously a cloud tool but it’s many things altogether. Before we get into the specifics of GCP, lets discuss Google Cloud as a whole.

GCP vs G Suite

Google Cloud is the mixture of both GCP and G Suite. GCP in a basic sense is the infrastructure and platform where you can run codes, store data things like that. And then G Suite as you all probably know is things like Google Docs, Google Drive, that is the software as a service. G Suite also has a ton of APIs that you can use to enhance the GCP user experience.

So, on GCP you can do a lot of things. First of all, you can run a virtual machine and you can literally run a giant script that’ll take a week. Instead of running it on your own computer and worrying about the battery dying, and this and that. You can just put it on a virtual machine in the cloud. Or, you can deploy a web application and have the code run on cloud.

Services

You can store data on the SQL databases and the NoSQL databases. There are tools for networking, and monitoring. So let’s say you have all these tools in your cloud and you want to monitor how they’re working. For instance, if one thing crashes, you can see why that happened.

There are tools like IoT. Core that can help you build internet of things projects. There are tools to build your own API, its called Apairy. There are some open source tools like TensorFlow. It’s a machine learning platform, totally open source, many other software companies and developers use it as well.

Learn more on how to use google cloud platform. Learn how to setup your own Blynk server.

]]>
790 12.3325477 76.6807412 12.3325477 76.6807412