Wednesday, 30 December 2015

This mini-project explains the use of PIC16F877A internal PWM module to control the speed of a DC motor, it also describes the use of H-Bridge circuit to control the direction of rotation.

The Concept of Pulse-Width-Modulation (PWM) :
a square wave signal is described by three parameters, amplitude, frequency and duty cycle (AKA pulse width).
The term "duty cycle" describes the ratio of the ON state of the signal to the period of that signal,
i.e.

Duty = TON/T = TON/( TON+TOFF)

Duty cycle has no unit, its represented by percentage with 100% describing the fully ON state and 0% describing the fully OFF state.

PWM concerns about the duty cycle of a square wave signal, it's the technique in which we change the pulse width to get the desired duty cycle.

Speed Control Using PWM:

The idea of speed control is to switch the motor ON and OFF at varying speeds, let us say we have a 12V DC motor and we applied a constant 12V signal to that motor, the motor would run in its full power (full speed).
Now assume we apply a 50% duty cycle signal to the motor (at several KHz frequency), the motor will turn ON and OFF continuously and the effective voltage applied to the motor is 6V, this would decrease the  motor speed by the half, and the motor would be running at 50% of it's full power.
Varying the duty cycle of the applied signal would cause the speed to vary, a 0% duty cycle signal would turn OFF the motor, and a 100% one would run the motor at it's full speed.

The PIC16F877A PWM Module:

16F877a includes two PWM modules included in the CCP1,CCP2 modules (CCP stands for Capture-Compare-PWM), and there are 3 steps for using those modules:

  1. Set the desired CCP module to PWM mode.
  2. Setup The TIMER2 module, which controls the frequency and the base of your PWM signal.
  3. Set your duty cycle, rely on the equations below to select it properly.
We'll be using CCS PIC-C compiler to explain those steps, if you have a question on using other compilers to set it, post a comment.
To set The CCP1 module to PWM mode, we'll use the code line:
setup_ccp1(CCP_PWM);
 and the first step is done.
Now setting up Timer2 module using PIC-C is a bit easy, use the code line: setup_timer_2(divider,preload,postscalar).
the divider and the preload values determines the frequency of the PWM signal by the following function:
Signal Frequency = (Crystal/4) / (divider * (preload+1))
The divider takes the values : T2_DIV_BY_1, T2_DIV_BY_4, T2_DIV_BY_16.
the preload is 8Bits and takes the values 0-255
So let us say we have 4MHz crystal and we set Timer2 like this:
setup_timer_2( T2_DIV_BY_1, 255, 1);
thus, our signal frequency is (4MHz/1)/(4 * 256) =  3.9KHz

Now the final step is to set your duty cycle using the function: set_pwm1_duty(duty_parameter);
to get the duty_parameter of your desired duty cycle, note the following:
the maximum value of duty_paramter (MAX) = ((preload+1)*4) -1
so in our case the maximum value is ((255+1)*4)-1 = 1023 and it represents a 100% duty cycle.
now if we need a duty cycle of 50% it would be 1023*0.5 = 512, and a duty cycle of 25% would be 1023*0.25 = 256, thus,

set_pwm1_duty(1023L); ---> 100% duty (Full Speed)
set_pwm1_duty(512L);  ----> 50% duty
set_pwm1_duty(256L);  ----> 25% duty
set_pwm1_duty(0);        ----> 0% duty (OFF)

Note: the capital letter L at the end of the parameter instructs the compiler to treat the number as Long integer.

The H-Bridge and the Direction of Rotation:

L298 is a dual H-Bridge transistor circuitry used to isolate and control DC Motors, Micrcontrollers has current limitations so it can't drive a high power element such as a motor, the H-Bridge solves the problem by providing a different power supply for driving the motors.
For a single motor connected to OUT1,OUT2 respectively, the inputs IN1,IN2 controls the direction of rotation, setting IN1=1 IN2=0 would rotate the motor clockwise, while setting IN1=0 IN2=1 would rotate it counter clockwise, and the setting IN1=0 IN2=0 would turn it OFF.
The pin ENA (Enable motor A) is used turn ON/OFF the motor regardless of the inputs IN1 IN2, thus, our PWM signal could be connected to ENA to control the speed of the motor.


The Schematic Design:





Buttons UP/Down are used to increase/decrease the speed (the duty cycle)
Button Direction is used to flip the direction of rotation (CW/CCW)
CCP1 Pin 17 carries the PWM signal and connected to the motor enable pin ENA
Diodes D1-D4 are free-wheeling diodes used to protect the circuit from reverse currents.
C1 is an electromagnetic interference elimination capacitor, to protect against voltage spikes.




pic coding:






#include <16f877a.h>
#fuses XT,NOLVP,NOWDT,NOPROTECT
#use delay(clock=4000000)

#define  Wire1 PIN_B6
#define  Wire2 PIN_B7
#define  Up    PIN_A0
#define  Down  PIN_A1
#define  Dir   PIN_A2

int16 duty_cycle=512;

void main()
{
   setup_adc(ADC_OFF);           // Turn ADC OFF
   setup_adc_ports(NO_ANALOGS);  // All Ports are digital I/O
   output_high(Wire1);          
   output_low(Wire2);            // Set the motor to CW direction
  
   /* PWM Configurations */
   setup_timer_2(T2_DIV_BY_1,255,1);   // Set PWM frequency
   setup_ccp1(CCP_PWM);          // Configure CCP1 to PWM mode
   set_pwm1_duty(512L);          // default duty cycle = 50% (Half Speed)

   while(1)
   {
      while(input(Up) && input(Down) && input(Dir)); // Hold until a button is pressed
     
      if(!input(Up))    // Button (Up) Selected?
      {
         duty_cycle+=64;   // increase the duty cycle by some percentage (+6.25%)
         set_pwm1_duty(duty_cycle); // set the duty cycle
      }
      if(!input(Down))  // Button (Down) Selected?
      {
         duty_cycle-=64;   // decrease the duty cycle
         set_pwm1_duty(duty_cycle); // set the duty cycle
      }
      if(!input(Dir))   // Button (Direction) Selected?
      {
         output_toggle(Wire1);   // Toggle the polarity of IN1 IN2
         output_toggle(Wire2);   // 0 becomes 1 , 1 becomes 0
      }
     
      delay_ms(500); // 0.5 second delay to release the selected button
   }
}
  
all the best
by gkarthik

android os

Android Operating System and Advantages

Android Operating System
Android Operating System
The Android operating system, is a trending OS now, that is used in android phones.There are many Advantages of android operating systems, these operating systems powers more than billion smartphones and tablets. Android is a mobile and a tablet operating system owned by google. It is the main competitor to the Apple Ios platform. Android was started up in 2003 and it’s taken by Google in 2005. The first version was released in September, 2008. The versions released are cupcake (v1.5), Donut (v1.6), Eclair (v2.0) in 2009. Froyo (v2.3), Gingerbread (v2.4) in 2010. Honeycomb (v3.0), Ice cream sandwich (4.0) in 2011, JellyBean (4.1 to 4.3) in 2012 and KitKat (4.4) in 2013. Lollipop (5.0) in 2014.This article gives a brief information about android OS, advantages of android operating system and applications.

What is the Android Operating System

Android is a mobile operating system based on the Linux kernel and now developed by Google. Android is primarily designed for touch screen mobile devices like smartphones, table computers, specialized user interface for Android TV, android enabled vehicles, and android wear. Android OS uses touch inputs to manipulate on-screen objects, and uses virtual keyboard. Basically, it was designed for touch screen input, it has been used by in game equipments, cameras, PC’s and other electronic devices. It is the most widely used operating systems and it is the highest selling mobile operating system nowadays. Over 1 billion users already using this operating system mobiles. This is open source and anyone can use to build applications.
Android Versions
Android Versions
Android is a Linux-based operating system for smartphones and tablets. Android  includes a touch screen user interface with other features that enable a cell phone to be called a smartphone. This  is a platform that supports various applications, available through the Android Stores. This platform allows end users to develop there own apps , can install and use their own applications on top of the Android framework.

Android Architecture

Before knowing all about the development of Android, we should know all about basic internal architecture. By Knowing how things are arranged inside makes us understand the application framework better. We can design the application in a better way. The Android OS is based on Linux and it is pretty similar to Linux. The following figure illustrates the Android architecture. Software stack above the hardware that is provided by the OEMs. Topmost layer is the applications.
Android Architecture
Android Architecture

Basic Applications

For example, The above diagram depicts four basic apps like App 1, App 2, App 3 and App 4 like any user interface on Android. Music player, app for making calls, a camera app, and so on. These apps are not necessarily from Google. You Can develop an app and make it available to everyone through Google Play Store. Apps are developed in Java, installed directly, no need to integrate with Android OS.

Application Framework

Below the applications, we take application framework, application developers can develop Android applications. The Framework offers a huge set of interfaces used by developers for various standards, no need to code every basic task. The Framework consists of different entities.
Activity Manager
It manages the activities that govern the application life cycle and has several states. These applications may have multiple activities, with their own life cycles. But, there is one main activity that starts when the application is launched. Usually, every activity in an application is given a window that has its own layout and user interface.
Notification Manager
It enables the applications to create customized alerts.
Views
These are used to create layouts, including components such as grids, lists, buttons.
Resource Managers
The Apps do require external resources, such as graphics, external strings managed by the resource manager, which makes them available in a standardized way.
Content Provider
Applications shares data when they require. From time to time, one application may need some data from another application. The International calling application will need to access the user’s address book, access to another application’s data is enabled by the content providers.

Libraries

This layer holds all the Android native libraries. Libraries are written in C/C++ and offer capabilities similar to the application layer, with sitting on top of the kernel. These major native libraries include
  • Surface Manager: Display and compositing window-in manager.
  • Media framework: Audio and video formats and codecs, including their playback and recording.
  • System C Libraries: Basic C library like libc targeted for ARM or embedded devices.
  • OpenGL ES Libraries: 2D and 3D graphics.
  • SQLite: Database engine.
Android Runtime
The Android runtime consists of the Dalvik Virtual Machine which is basically a virtual machine for embedded devices like other , virtual machine is a by tecode interpreter. A Virtual machine for embedded systems, it is low on memory, slower and runs on battery power. It also consists of the core libraries like Java libraries and are available for all devices.
Kernel
The Android OS is derived from Linux Kernel 2.6 and compiled for electronic equipment. Memory management and process management are similar. The kernel acts as a Hardware Abstraction Layer between hardware and the Android software stack.
Android SDK
Android is an open source and  the source code is available for all developers. So It is called the Android SDK. It can be downloaded, build and work on Android in a number of different ways.  If goal is to develop an Android application, no need to download all the source. Recommended  the Eclipse IDE, for which there is an available Android Developer Tools (ADT) plugin. Which  you can install the specific SDK, can create projects, launch emulators, finally can debug.
Memory Requirements
It is always a wise idea to check the memory requirements before starting any project. Android SDK is around 8.5GB and you will need around 30GB free disk space to build it.
Prerequisite Installations
Before downloading the SDK and starting cross-compiling, different prerequisites of the Android SDK we need to have. Set these up before jumping into the Android SDK software, prevention is much better than debugging. The Android version we have chosen.

Advantages and Disadvantages of Android Operating System

Supports 2D, 3D graphics
It supports various platforms like 2D and 3D. Earlier we used to watch movies and play games in almost in 2D, but nowadays various applications are using 3D format. To provide different graphics in videos, games OS should support 3D format. Android supports 2D And 3D format to provide a better advantage in videos and in games.
2D and 3D Graphics
2D and 3D Graphics
Supports Multiple Languages
Android supports different languages. We can say all famous languages about more than 100. By using this feature it is easy to adopt to different languages. Earlier in the feature phones English is to be the only language in the mobile devices.
Supports Multiple Languages
Supports Multiple Languages
Java Support
The Java supporting feature enables developers to enhance more features. As it supports Java, operating can be developed.
Faster Web Browser
As it enabled with web browser we surf web easily without complexity just like in a computer. It easily loads multimedia so that it makes web browsing faster.
It Supports MP4, 3GP, MPEG4, MIDI
It supports different types of formats. There is no need to convert from one format to      another, as it enabled with different formats of audio and video styles.
Additional Hardware Support
Any hardware can be easily connected with the Android based devices easily. We can make a device to connect internally to get more features.
Video Calling
Faster data connection enables to do video call. We can take advantage of bandwidth and new generation networks using Android.
Video Calling
Video Calling
Open Source Framework
It makes users to make their own applications and to make changes required for themselves. Enthusiasts can make  Andriod more powerful and useful by developing themselves. As it is an open source operating system, we can use it easily and without cost in the equipments.
Uses of Tools are Very Simple
It makes use of a single button to do more than assigned work. For example volume control button can be made to click a photo by changing simple algorithm in the android.
Availability of Apps
Anyone can make use lot of free apps in the app store and from other android stores. It gives freedom to install from third party users.
Great Social Networking Integration
Integration can be made to different social networking sites,so you can enhance features.
Free to customize the applications and features, using user enabled development
Better Notification System
It makes users to check important notifications directly from the dashboard. It makes work easy. Earlier we used to go for every application refresh to check updates.
Updated User Interface Design
Interfacing that means human to machine integration made to update in android. Touchscreen made very useful change in the mobile use. It enables zooming and tapping features which perform very effectively in the Android operating system
At a Time Aplications
Can run numerous applications which allow consumers to help save time and efforts
Low Chance of Crashing
The Android OS is very smooth and easy to operate and less chances of crashing down
Stability
Stability and security is better than other mobiles OS as it is based on Linux Kernel. The Linux based operating system enabled with high security with unix. Every operation goes into command mode. If detected any security threats it goes to basic mode by storing to another application like cloud computing and crashes all the data on the device.
It Lets you Change Your Settings Faster
Android makes fast changes to settings. By enabling different apps and tasks we can make use of android operating system.
It Gives you More Options to Fit your Budget
Android makes cheap and gives better performance for lower costs. It is open source and open framework.
Support for Extra Large Screen Sizes and Resolutions
Android supports better screen sizes for applications and enhanced resolutions make users more freedom to enjoy bright and clear formats.
System Wide Copy and Paste Functionalities
Earlier we used to copy and paste in the same application. Developers thought to make whole phone operating as a computer based operating system. Android came with the system wide copy and paste option. It makes user to edit more easily.
Redesigned Multi Touch Software Keyboard
Redesigned keyboards like qwerty touch made users to type with more freedom. Intelligent keyboards made vast changes in the mobile typing keyboards. It made dictionary to adoptable and various features like drag and detect made revolution.
Audio,Graphical and Input Enhancements for Game Developers
Android made various changes in the multimedia used for the mobile devices. Different audio enhancements made changes to the audio quality.
Improved Power Management and Application Control
It only allows current applications to consume power and RAM memory. Other apps also will continue in the background to update. After switching to app system will allocate memory and power.with this method,  device can consume can save power and memory in the system. Support for multiple cameras.

Disadvantages of Android OS

Slow response
compared to ‘ios’ of apple,windows 8 of Microsoft.when we open same app in the ios and windoes8. We observe the slow response of the android when we open apps in the different platforms.
Heat
Compared to other operating systems android makes use of processes very efficient. This  makes processor to get heat. Some hardware companies take care to reduce heat,but it went in vain when we operate it a long time and at low battery.
Advertisement
When we use an android app we encounter several adds in between application use, because anyone can make add by inserting some logic in the app program and can interfere in into the phones information.
This is all about android operating system and the advantages of android operating system, which  made tremendous changes in last five years. Almost every smart phone, tablet and electronic device using android operating system. It is user friendly and open source to develop. It provides lots of advantages so it already attracted more than one and half billion users.Furthermore, any queries regarding this article or android based projects, please give your valuable suggestions by commenting in the comment section below.
 Photo Credits:

opncv python image histogram coding



Image Histogram-gkarthik
"An image histogram is a type of histogram that acts as a graphical representation of the tonal distribution in a digital image. It plots the number of pixels for each tonal value. By looking at the histogram for a specific image a viewer will be able to judge the entire tonal distribution at a glance."
Histogram is a graphical representation of the intensity distribution of an image.
  • Histogram quantifies the number of pixels for each intensity value.
Here is a simple code for just loading the image:
import cv2
import numpy as np

gray_img = cv2.imread('images/SunsetGoldenGate.jpg', cv2.IMREAD_GRAYSCALE)
cv2.imshow('GoldenGate',gray_img)

while True:
    k = cv2.waitKey(0) & 0xFF    
    if k == 27: break             # ESC key to exit
cv2.destroyAllWindows()

GGsunset.png

Histo_gray.png
The code for histogram looks like this:
import cv2
import numpy as np
from matplotlib import pyplot as plt

gray_img = cv2.imread('images/GoldenGateSunset.png', cv2.IMREAD_GRAYSCALE)
cv2.imshow('GoldenGate',gray_img)
hist = cv2.calcHist([gray_img],[0],None,[256],[0,256])
plt.hist(gray_img.ravel(),256,[0,256])
plt.title('Histogram for gray scale picture')
plt.show()

while True:
    k = cv2.waitKey(0) & 0xFF    
    if k == 27: break             # ESC key to exit
cv2.destroyAllWindows()
Note: This is how ravel() works, and it's equivalent of reshape(-1).
>>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> print np.ravel(x)
[1 2 3 4 5 6]
>>> x.reshape(-1)
array([1, 2, 3, 4, 5, 6])











Histogram Terminology
Before using that function, we need to understand some terminologies related with histograms.
  • bins :The histogram above shows the number of pixels for every pixel value, from 0 to 255. In fact, we used 256 values (bins) to show the above histogram. It could be 8, 16, 32 etc. OpenCV uses histSize to refer to bins.
  • dims : It is the number of parameters for which we collect the data. In our case, we collect data based on intensity value. So, in our case, it is 1.
  • range : It is the range of intensity values we want to measure. Normally, it is [0,256], ie all intensity values.


calcHist()
OpenCV comes with an in-built cv2.calcHist() function for histogram. So, it's time to look into the specific parameters related to the cv2.calcHist() function.
cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])
In the code, we used:
hist = cv2.calcHist([gray_img],[0],None,[256],[0,256])
The parameters are:
  • images: source image of type uint8 or float32. it should be given in as a list, ie, [gray_img].
  • channels: it is also given in as a list []. It the index of channel for which we calculate histogram. For example, if input is grayscale image, its value is [0]. For color image, you can pass [0],[1] or [2] to calculate histogram of blue,green or red channel, respectively.
  • mask: mask image. To find histogram of full image, it is set as None. However, if we want to get histogram of specific region of image, we should create a mask image for that and give it as mask.
  • histSize: this represents our BIN count. Need to be given in []. For full scale, we pass [256].
  • ranges: Normally, it is [0,256].





NumPy - np.histogram()
NumPy also provides us a function for histogram, np.histogram(). So, we can use NumPy fucntion instead of OpenCV function:
import cv2
import numpy as np
from matplotlib import pyplot as plt

gray_img = cv2.imread('images/GoldenGateSunset.png', cv2.IMREAD_GRAYSCALE)
cv2.imshow('GoldenGate',gray_img)
#hist = cv2.calcHist([gray_img],[0],None,[256],[0,256])
hist,bins = np.histogram(gray_img,256,[0,256])

plt.hist(gray_img.ravel(),256,[0,256])
plt.title('Histogram for gray scale picture')
plt.show()

while True:
    k = cv2.waitKey(0) & 0xFF    
    if k == 27: break             # ESC key to exit
cv2.destroyAllWindows()
Other parts of the code remain untouched, and it gives us the same histogram.


Histogram for color image
Let's draw RGB histogram:

GoldenGateSunsetCV.png

Color_HIstogram.png
The code:
import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('images/GoldenGateSunset.png', -1)
cv2.imshow('GoldenGate',img)

color = ('b','g','r')
for channel,col in enumerate(color):
    histr = cv2.calcHist([img],[channel],None,[256],[0,256])
    plt.plot(histr,color = col)
    plt.xlim([0,256])
plt.title('Histogram for color scale picture')
plt.show()

while True:
    k = cv2.waitKey(0) & 0xFF    
    if k == 27: break             # ESC key to exit
cv2.destroyAllWindows()

Tuesday, 29 December 2015

Assign A Static IP to The Raspberry Pi

 

Assign A Static IP to The Raspberry Pi


 gkarthik

 

Step 1: Getting Ready

What You Will Need:
- Raspberry Pi
- A MicroSD card with Raspbian installed.
 To see how to install Raspbian read This Instructables or watch This Video
- Connection to the router (The router doesn't need to have a internet connection).
- A USB keyboard and Mouse (not needed if you want to SSH into the pi)
- A Display (not needed if you want to SSH into the pi)
- A power adapter.
Setting Up The Pi:
- Connect all the peripherals to the Pi and connect power.
- Log in and open command line or the terminal (if you are in the desktop enviornment).
- Proceed to the next step.

Step 2: Gathering Intelligence

Before we change any settings on the pi, we need to collect some information regarding our network.
- In the command line type the following command and hit enter.
ifconfig
- From the info that comes up, note down the following things:
-> inet addr
-> Bcast
-> Mask
- When you have got all this information, you need even more information. Enter the following command and hit enter
netstat -nr
- From the table that comes up note down the following:
-> Destination
-> Gateway
This is what I got:
  • inet addr : 192.168.137.82
  • Bcast : 192.168.137.255
  • Mask : 255.255.255.0
  • Destination : 192.168.137.0
  • Gateway : 192.168.137.1
These numbers will most probabaly will be different for you so don't copy mine by mistake.
After you have got all this, you can proceed to the next step.

Step 3: Execution

Now we can finally get a Static IP.
Enter the following command and hit enter.
sudo nano /etc/network/interfaces
A file editor will open up.
- In the third line, 'dhcp' means that we are currently getting our IP address from the router.
iface eth0 inet dhcp
- In this line replace 'dhcp' with 'static'
iface eth0 inet static
- Now in the line below this you need to write type the following
<p>address [your inet addr]<br>netmask [your mask address]
network [your destination address]
broadcast [your bcast address]
gateway [your gateway address]</p>
Finally your whole document will look something like this:
<p>auto lo</p><p>iface lo inet loopback
iface etho inet static
address 192.168.137.82
netmask 255.255.255.0
network 192.168.137.0
broadcast 192.168.137.255
gateway 192.168.137.1</p><p>allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp</p>
Be careful to enter YOUR addresses, don't use my numbers by mistake
- Save the file by pressing cntrl + X , then Y , then enter.
- Restart the pi by running the command.
sudo reboot
- After the reboot is complete, you should have a static IP address!!!!
Your Static IP will be the inet address that you noted down earlier.

Step 4: Alternative

While the above mentioned method will certainly work in almost all scenarios irrespective of your router and network, a better method to assign a static IP would be to do it through your router settings.
All the routers, even of different models from the same company, have very different setting layout and option availability. Thus there cannot be a unified guide for all the routers. You should check out the user manual that came with your router to see how to assign a static IP through your router. Doing so will require you to know the MAC Address of your Pi. You can know the MAC address by running the command "ifconfig", in the first line, the HWaddr if your MAC address.
You need to assign the static IP to the MAC address of your Pi.