Posts

Showing posts from 2014

Linux command to get the number of CPU present

To get the number of CPUs/cores present ,type the following command in terminal nproc or grep --count  processor /proc/cpuinfo

Arduino pure programming part-6 uart loopback test

Connect the TX and RX of the arduino using a wire #include <avr/io.h> #include <avr/interrupt.h> /* UDR-->UART Data Register UCSRA,B,C---> Uart control status register a,b,c UBRRnL,UBRRnH --> UART Baud Rate Register */ ISR(USART_RX_vect) { if(UDR0 == 'C'){ PORTB |=1<<5; } } void uart_init(unsigned int ubrr) { //ubrrn = fosc/16(Baud) -1.for 9600 = 104 //set baud rate UBRR0H = (unsigned char)ubrr>>8; UBRR0L = (unsigned char)ubrr; //enable the receiver and transmitter and receiver enable interrupt UCSR0B = (1<<RXEN0) |(1<<TXEN0) | (1<<RXCIE0); UCSR0C = (1<<UCSZ01) | (1<<UCSZ00); //8-bit //enable global interrupt sei(); //wait for udr to be empty while(!(UCSR0A&&1<<UDRE0)); UDR0 = 'C'; //wait for transmission to complete while(!(UCSR0A&&1<<TXC0)); while(1); } int main() { DDRB |= 1<<5; PORTB &am

arduino pure programming part5 - external interrupt

#include <avr/io.h> #include <avr/interrupt.h> #define SET_BIT(X,Y) X|=1<<Y #define CLR_BIT(X,Y) X&=~(1<<Y) #define IS_BIT_SET(X,Y) X&(1<<Y) #define TOGGLE_BIT(X,Y) X^=(1<<Y) ISR(INT0_vect) { TOGGLE_BIT(PORTB,PB5); } void delaymicroseconds(unsigned long us) { unsigned long temp = us; SET_BIT(TCCR0B,CS01); //Starting the timer with prescaler clock/8 which is 0.125us while(temp != 0) { TCNT0 = 247; while(!IS_BIT_SET(TIFR0,TOV0)); CLR_BIT(TIFR0,TOV0); temp--; } } int main() { SET_BIT(DDRD,2); SET_BIT(PORTD,2); DDRB |= 1<<5; PORTB &= ~(1 << PB5); EIMSK = 1<<INT0; EICRA = 1<<ISC01; sei(); while (1){delaymicroseconds(3000000U);} return 0; }

arduino pure programming part7--printf implementation

#include <avr/io.h> #include <avr/interrupt.h> /* UDR-->UART Data Register UCSRA,B,C---> Uart control status register a,b,c UBRRnL,UBRRnH --> UART Baud Rate Register */ void print_init(unsigned int ubrr) { //ubrrn = fosc/16(Baud) -1.for 9600 = 104 //set baud rate UBRR0H = (unsigned char)ubrr>>8; UBRR0L = (unsigned char)ubrr; //enable the receiver and transmitter and receiver enable interrupt UCSR0B = (1<<RXEN0) |(1<<TXEN0) ; UCSR0C = (1<<UCSZ01) | (1<<UCSZ00); //8-bit } void putch(unsigned char ch) { while(!(UCSR0A&&1<<UDRE0)); UDR0 = ch; while(!(UCSR0A&&TXC0)); } void print(char *string) { int i=0; while(string[i]) { putch(string[i]); i++; } } int main() { print_init(104); //putch('c'); print("Hello World"); return 0; } To see the output use cutecom or minicom with baud rate set to 9600,8data bits , 1 stop bit and no

Arduino Pure C-Programming Part-4 delaymicroseconds

#include<avr/io.h> #define SET_BIT(X,Y) X|=1<<Y #define CLR_BIT(X,Y) X&=~(1<<Y) #define IS_BIT_SET(X,Y) X&(1<<Y) #define TOGGLE_BIT(X,Y) X^=(1<<Y) void delaymicroseconds(unsigned long us) { unsigned long temp = us; SET_BIT(TCCR0B,CS01); //Starting the timer with prescaler clock/8 which is 0.125us while(temp != 0) { TCNT0 = 247; while(!IS_BIT_SET(TIFR0,TOV0)); CLR_BIT(TIFR0,TOV0); temp--; } } int main() { SET_BIT(DDRB,PB5); TOGGLE_BIT(PORTB,PB5); TOGGLE_BIT(PORTB,PB5); while(1) { delaymicroseconds(5000000L); TOGGLE_BIT(PORTB,PB5); } return 0; }

Hello World in assembly for x86

Code : ;author:md.jamal mohiuddin global _start section .text _start: ;print hello world on the screen mov eax,0x4 ;system call number mov ebx,0x1 ;fd =1 mov ecx,message ;buf points to the message mov edx,11 ;len = 11 int 0x80 ;trap interrupt(software defined) ;exit gracefully mov eax,0x1 ;system call number mov ebx,0x3 ;first argument int 0x80 ;trap interrupt(software defined) section .data message : db "Hello World\n" To execute  nasm -f elf32 -o hello.o hello.asm  ld -o hello hello.o ./hello To check the return type: echo $?

Arduino pure C-programming part -3 EEPROM

/* Writing to the AVR EEPROM */ #include <avr/io.h> #include <avr/eeprom.h> #include <avr/interrupt.h> struct accelerometer_data { int x,y,z; }; struct accelerometer_data data = {10,12,32}; uint8_t i=123; int main() { while(!eeprom_is_ready()); //wait for the eeprom to be ready cli(); eeprom_write_block((const void*)&data,(void *)0,sizeof(struct accelerometer_data)); sei(); while(!eeprom_is_ready());  //wait for the eeprom to be ready cli(); eeprom_write_byte((uint8_t *)40,i); sei(); while(1); }

Arduino pure c programming part2 push button

/* Toggle a on-board led if push button is pressed */ #include <avr/io.h> void init_io() { DDRB |= 1<<PB5; //Setting the pin as output DDRD &= ~(1<<PD2); //Setting the pin as input } int is_button_pressed() { return (PIND&(1<<PD2)) ; } void toggle_led() { PORTB ^= 1<<PB5; } int main() { init_io(); while(1){ if(is_button_pressed()) toggle_led(); } return 0; }

Arduino pure C programming part1 Blinking On-Board Led

Code: /* Program to blink the on-board led */ #include <avr/io.h> #include <util/delay.h> int main(void){ DDRB |= (1 << PB5); while(1) { PORTB ^= (1 << PB5); _delay_ms(2000); } } Commands avr-gcc -mmcu=atmega328p -Wall -Os -o blink.elf blink.c  -DF_CPU=16000000UL avr-objcopy -j .text -j .data -O ihex blink.elf blink.hex sudo avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM0 -b 115200 -U flash:w:blink.hex 

msp430 timer programming interrupt based

Image
Basically msp4302xxx family has two 16-bit timers. Timer A and Timer B. We will see today about Timer A. Timer A can work in four modes based on the values of MCx in TACTL register If MCx = 00 then it is in stop mode. It means the timer is stopped. If MCx = 01 then it is in Up mode. It means the timer counts up to the value present in the TACCR0 register and goes to zero and repeats the cycle If MCx = 10 then it is in Continuous mode,in which the timer counts up to the value  0xffff and jumps to zero and repeats the same. If MCx = 11 then it is in Up/Down mode where the timer counts up to the value present in the TACCR0 and starts decrementing to zero and again starts from zero to TACCR0 The timer can be sourced from either ACLK,TACLK,SMCLK and INCLK with a divisor factor upt0 8 based on the values of TASSELx and IDx in the TACTL register We will see how to program the timer A present in msp430. For programming we have to use the Timer A registers. 1) TAR: It i

#pragma warn example in C

For disabling warnings (non-critical Messages ) we can use #pragma warn directive Syntax: #pragma warn +xxx #pragma warn -xxx #pragma warn .xxx + -----> means on - -----> means off . ------> means toggle xxx is  a 3 character warning code. For example rvl means ignore all the warnings where there is function which has to  return value but is not returning. Code: #include<stdio.h> #pragma warn rvl int add(int a,int b); int main() { add(3,5); } int add(int a,int b){ printf("The result is %d",a+b); } This will not be supported by gcc  compiler as it does not support all the #pragma directives . First if we compile this program with gcc ,the compiler will not show any warnings. To see the warnings we have to pass -Wall arguments to the gcc compiler. 

Pragmas in C language

Pragma directive is a method specified by the C standard for providing additional information to the C compiler.Basically it can be used to turn on or turn off certain features.Pragmas are operating system specific and are different for every compiler. Examples of some of the pragmas  are #pragma startup,#pragma exit Example of #pragma startup: Syntax:  #pragma startup <function name> [priority] By using #pragma startup directive we can call the functions on startup before main function execution #include<stdio.h> void print1() { printf("Before Main 1\n"); } void print2() {     printf("Before Main 2\n"); } #pragma startup print1 0 #pragma startup print2   1 int main() {                                                   printf("In Main\n");     return 0; } This will not work when compiled on gcc as it does not recognize this pragma directive.If we want any function to be called before main function by us

C Program for shutting down the Operating System

#include<stdio.h> #include<stdlib.h> int main() { //for linux based systems system("sudo init 0"); //system executes a  shell command. //for windows        //system("shutdown -s"); return 0; }

C-Program to check whether a number is power of 2 or not

#include <stdio.h> #include <string.h> main() {   int number;   printf("Enter the number\n");   scanf("%d",&number);   if(!(number&(number-1)))       printf("%d is a power of 2\n",number);   else       printf("%d is not a power of 2\n",number); }

C-Program to count the number of ones in a Number

We will see the different ways in which a number of ones in a number can be calculated. For example in the number 25(11001) it has 3 ones present in it. We will get that value programmatically. There are two methods for getting the result: Method1: #include <stdio.h> #include <string.h> main() {   int number,count=0;      printf("Enter the number\n");   scanf("%d",&number);      while(number>0){       count++;       number=number&(number-1); //this will clear the last set bit          }   printf("The count is %d",count); } Method 2: #include <stdio.h> #include <string.h> main() {   int number,count=0;      printf("Enter the number\n");   scanf("%d",&number);      while(number>0){ //checking the last bit whether it is 1 and shifting by 1       if(number&1)         count++;       number=number>>1;   }   printf("The

Hello World Device Driver

hello_world.c: #include<linux/module.h> #include<linux/init.h> MODULE_LICENSE("GPL"); MODULE_AUTHOR("EMBEDDED GURUJI"); static int hello_init(void) {       printk("Hello World\n");       return 0; } static void hello_exit(void) {      printk("Bye World\n"); } module_init(hello_init); module_exit(hello_exit); Makefile: obj-m := hello_world.o KERNELDIR := /lib/modules/$(shell uname -r)/build PWD := $(shell pwd) all :     $(MAKE) -C $(KERNEL) M=$(PWD) modules clean:    $(MAKE) -C $(KERNEL) M=$(PWD) clean Now we will understand the code line by line #include<linux/module.h> #include<linux/init.h> These header files contains the definition of the module_init() and module_exit() functions. MODULE_LICENSE("GPL"); MODULE_LICENSE() informs the kernel the license used by the source code,which will affect the functions it can access from  the kernel.MODULE_LICENSE("

How Diodes works

Image
A diode is the two-terminal semiconductor device which allows the current to flow only in one direction and blocks the current that flows in the opposite direction. Symbol of the diode:    A diode is made by connecting a part of N-type material to P-type Material,N-type material has excess of negative charged particles(electrons) whereas P-type material has excess of positive charged particles(holes). As there are more holes in P-type and more electrons in N-type whenever both  are connected,holes will move from P-type to N-type and electrons will move from N-type to P-type and the holes and electrons combine and form depletion layer.In the depletion region , semiconductor will return back to the insulating state. To remove the depletion region,you have to apply enough potential which will make the electrons will move from  N-type to P-type and holes will move P-type to N-type.To do this,connect the N-type to of the diode to the negative terminal of the bat

msp430 embedded c programming part2 - configuring DCO

Image
Introduction : MSP430 Clock system has three clocks which provides different frequencies . Need of three different clocks not only one is power consumption. That is we will use the clock with lowest frequency when we want to save the power and we will use the clock with highest frequency when we want high speed. The three clocks present in MSP430 are 1. MCLK(Master Clock) : Used by CPU and few peripherals such as ADC. It is  a high frequency clock but can be configured to provide a low frequency 2.SMCLK(Sub-Main CLock) : Distributed to Peripherals. It can be the same frequency as MCLK,or different depending on the application 3. ACLK(Auxiliary CLock) : Basically it is a low frequency clock, used for peripherals. There are four Sources for these clocks 1.LFXTCLK: As the name implies it is to use with low frequency crystal.A 32khz can be connected to msp430 for low power operation 2 XT2CLK:  This is not available in every device.it is to use with a second crystal 3.DCO

msp430 embedded c programming part 1 --- Blinking a LED

/*   Blinking a LED which is connected to port 5.5 of the MSP430F2618 */ //step1 : include the microcontroller header file #include <msp430f2618.h> int main(void) { //step2 :  stop the watchdog timer,otherwise it will reboot the system if the timer fires WDTCTL=WDTPW+WDTHOLD; //WDTCTL is  a 2 byte register in which the least 8 bits are used for controlling the watchdog timer and 8 most significant bits are for setting the password for the watchdog timer as it is password protected.Setting the 7 lsb bit will stop the watchdog timer which is the value of WDTHOLD(0x0080) and the password for the Watchdog timer is 0x5a which WDTPW(0x5a00) has in it //step3: setting up the pins /* There are basically 5 registers for each port PxSEL -> Select the functionality PxDIR -> Selecting the direction of pin whether it is input(0) or output(1) PxIN  -> Input Register of the port PxOUT -> Output Register of the port PxREN -> Selects if

Interfacing an LED to a microcontroller

Image
First identify which is the anode and cathode,the shorter leg is the cathode(negative) and longer leg is anode(positive). Now we will see how to interface  a LED to a microcontroller. We can do this in two ways. Method 1: Connect the anode to a microcontroller GPIO pin and cathode to ground with a resistor connected between anode and the microcontroller pin , to reduce current flowing into the led . The value of the resistor depends on the amount of the current that can be supported by the LED.In order to ON the LED we have to send a Logical High from the microcontroller pin. Method 2:  Connect the cathode to the microcontroller GPIO pin and anode to the 5V with a resistor i between. Now we have to send a logical LOW from the microcontroller pin for making the LED glow

What is Electric Field

Image
Forces come in two categories: Contact Forces and Non-Contact Forces. Contact Forces are quite usual and customary to us. Electric Force and Gravitational Force are examples of non-contact forces.Non-contact forces or Action-at-a-distance forces requires a more difficult explanation. Example of Non Contact force is that the Moon has a gravitational field around it,and if we get close to the moon,it will pull us down to its surface. Scientists understood why forces acted the way they did when objects touched.The idea that confused them was forces that acted at a distance without touching them.To help them explain what was happening they used the idea of "field". They imagined that there was an area around the object,and anything that entered would feel a force. An electric field describes the area near any electrically charged object. It is also called an electrostatic field.Any other charge that enters the area will feel a force. A normal field is a vector,and is re

Arduino 2 - Serial Communication between Arduino and PC

Image
This post is for serial communication between the Arduino and PC connected through the USB Cable Parts Required: 1.Arduino Uno 2. USB Cable A-B Sketch: //one-time initialization void setup() {      Serial.begin(9600); //setting the baud rate to 9600 } //infinite loop void loop() {      Serial.write("Hello World"); //writing Hello world on the console      delay(3000); //delay of 3 sec } To check the output , go to Tools and click on SerialBoard Monitor

Arduino-1 Blink LED

Image
This post consists of blinking an LED Present on the Arduino Uno Board. On the Arduino Uno Board there is an yellow LED labelled with L on the Board. Parts Required: 1.Arduino Uno 2. USB Cable A-B Sketch: const int LED=13; void setup() {       pinMode(LED,OUTPUT); //setting the pin 13 as output on which the L LED is connected } void loop() {      digitalWrite(LED,HIGH); //writing one on the pin to make the LED ON      delay(1000);//1 sec delay      digitalWrite(LED,LOW);//writing zero on the pin to make the LED OFF      delay(1000);//1 sec delay }

voltage and current

voltage: force responsible for movement of electrons(electric current) through a electric circuit current:amount of electrons flowing at a point per second

Pull-up and Pull-down resistors

Image
Suppose in a microcontroller ,you have configured the GPIO functionality of a particular pin to input, and if you read the state of the pin when nothing is connected to it,will it be high(Vcc) or low(Gnd).This is difficult to tell and the state it is present is known as floating state(high impedance state).To prevent this unknown state or floating state,a pull-up or pull-down resistor will ensure that the pin is either in a high state or low state.            A pull-up resistor is connected to 3.3V or 5V (Vcc) and the pull-down resisitor is connected to ground(GND).       Pull-ups are often used with buttons and switches. When the pull-up resistor is connected,the input pin will read a high state when the button is not pressed,a small amount of current will be flowing between the input pin and the VCC thus the input pin is reading to close to VCC.When the button is pressed it connects the input pin directly to the ground,the current flows through the resistor to the ground

What is the difference between phase and polarity

Image
Phase :  For phase to measure we require two signals, and it gives the time relationships of the signals. Polarity :  Can be measured on a single signal. It refers to positive and negative values of a signal.So a signal can have either positive polarity or negative polarity. Inverting the polarity means shifting the amplitude,so that positive components become negative and negative components become positive. Sine wave are the waves which alternates from positive to negative and back to positivie,place where the voltage is zero volts is taken to be zero degrees and place where the voltage starts becoming negative is taken to be 180 degrees,when it gets back to positive again it is 360 degrees which is 0 degrees. Phase Difference :  Difference between two sinusoidal signals of the same frequency in time or degrees and  they are referenced at the same point is known as phase difference. In-Phase:  Two sinusoidal signals having the same frequency and no phase differenc

How to Setup an FTP Server in Ubuntu 12.04

In order to install an FTP Server in ubuntu 12.04, we have to install the corresponding package sudo apt-get  install vsftdp For setting the ftp server, we have to modify the following file /etc/vsftpd.conf To start the ftp server sudo /etc/init.d/vsftpd restart Then u can open the browser and  type : ftp://ipaddress of the interface t check whether it is successfully running or not. Copy the files to /srv/ftp to keep it on the ftp server

c in C

unsetenv is used to delete the  variable name from the environment Syntax : int unsetenv(const char *name); Arguments Passed: name of the variable which you want to remove Return  Value :  Returns zero on success else returns -1 Code: #include<stdio.h> #include<stdlib.h> int main() { int result=putenv("NAME=TEST"); if(result==0) { printf("\n environmental variable successfully written"); printf("\n value of the environmental variable written is %s",getenv("NAME")); }else{ printf("\n error in writing the environmental variable"); } unsetenv("NAME"); printf("\n value of the environmental variable written is %s",getenv("NAME")); return 0; }

putenv example in C

Use : To change the environmental variable value Syntax: int putenv(char *string) Arguments : Takes a string as NAME=VALUE, where NAME  is the name of the environmental variable and VALUE is the value of the environmental variable you want to set If NAME is present in the environment list then replace the value else it will add this to the environmental list Return Type: 0 on success                       -1  if any error Code: #include<stdio.h> #include<stdlib.h> int main() { int result=putenv("NAME=TEST"); if(result==0) { printf("\n environmental variable successfully written"); printf("\n value of the environmental variable written is %s",getenv("NAME")); }else{ printf("\n error in writing the environmental variable"); } return 0; }

getenv example in C

Syntax:  char* getenv(const char* name) Arguments Passed: Name of the environmental variable Return Value:  Value of the environmental variable if present else returns null Code: #include<stdio.h> #include<stdlib.h> int  main() { printf("HOME Path :%s\n",getenv("HOME")); printf("ROOT Path :%s\n",getenv("ROOT")); printf("USER :%s\n",getenv("USER")); printf("Present Working Directory: %s\n",getenv("PWD")); return 0; }

Examples of Ping Command

Ping command is used to check the network status between two nodes. Developed by : Mike Muss Abbreviation : Packet INternet Grouper How it Works : Ping works by sending an ICMP Echo Request(Type 8) packet to the other node specifying that Iam Alive and asking about his status,if the other node receives the packet he will reply with an ICMP Echo Reply(Type 0) packet telling the node he is also Alive. With this ICMP messages Ping gives us the time that takes to reach and get back the reply from a node(round trip time). Syntax : ping <ip_address> Example : ping 192.168.1.5 We will see different examples in which we can use ping 1.Setting the Interval:              By default ping sends an Echo Request for every one second. If you want to change the interval you can do it by specifying with 'i' option. If you want to have anything beyond 200 ms you have to be in root permissions       Suppose if we want to send an ICMP Echo Request every 500 ms then we h

Lifecycle from .c to .out in Linux

Suppose we have written a C-Program as the following #include<stdio.h> #define pi 3.14 int main() {         printf("\n the value of pi is %d",pi);         return 0; } Stage 1: Pre-Processing:           In this stage all the things which start with a #(macros,includes) gets expanded.All the comments will also be removed in this stage(//, /* */) In our example the contents of stdio.h will be included in our file and pi will be replaced with 3.14 O/P of Pre-processing stage is still a C file Linux Command: gcc -E file.c Step 2: Compiling         In this stage c code will be  converted into assembly code.First the syntax checking will be done if the syntax is ok then each C instruction will be converted into its assembly instruction. The code will now have instructions such as push,movx etc O/P of compiling stage is Assembly Code Linux Command : gcc -S file.c Step3: Assembly:   The assembly code is given as input to the assembler and he ge

pcap_findalldevs example

The program lists out all the interfaces present on the system which can be processed by using pcap library #include<stdio.h> #include<pcap.h> int main(int argc,char *argv[]) {     char error[PCAP_ERRBUF_SIZE];     pcap_if_t *interfaces,*temp;     int i=0;     if(pcap_findalldevs(&interfaces,error)==-1)     {         printf("\nerror in pcap findall devs");         return -1;        }     printf("\n the interfaces present on the system are:");     for(temp=interfaces;temp;temp=temp->next)     {         printf("\n%d  :  %s",i++,temp->name);             }         return 0; }

pcap_lookupdev example

#include<stdio.h> #include<pcap.h> #define ERROR_BUFFER_SIZE 20 int main(int argc,char *argv[]) { /* First thing we have to do here is know the  network interface which we have to listen. If we already know the interface which Ww have to listen then we can directly specify it or we can ask libpcap give us the interface with the function char* pcap_lookupdev(char *errbuf).This function returns the pointer to the string specifying the interface which is suitable for packet capturing */ char *interface,error[PCAP_ERRBUF_SIZE]; interface=pcap_lookupdev(error); if(interface == NULL){ printf("no interface exist on which we can listen"); return -1; } printf("\n the interface on which we can listen is %s",interface); return 0; } My Previous posts has how to install pcap library if you have not installed yet Use the following command to generate the binary gcc -o test test.c -lpcap and run it by using roo

How to install libpcap library into ubuntu12.04

Steps for installing libpcap library Step1: Download libpcap.tar.gz from www.tcpdump.org and decompress it by using tar -xzvf Step2: Download the latest version of flex.tar.gz from  http://flex.sourceforge.net/  and decompress it by using the same command Step3: Download the latest version of bison.tar.gz from  ftp://ftp.gnu.org/gnu/bison/  and decompress it Step4: Download the lateest version of m4.gz  from  ftp://ftp.gnu.org/gnu/m4/  and decompress it Step5 : Go inside each directory and run the following commands              sudo ./configure             sudo make             sudo make install Step6:  Follow the order in this m4->flex->bison->libpcap Your libpcap libraries will be installed in the /usr/local/lib folder you can check it with by typing ls-l /usr/local/lib | grep "libpcap" copy all into the /usr/lib/pcap and now you can start programming ...

How to extract tar.gz and tar.bz2 files in Ubuntu 12.04

Now we are going to see how to extract the most common tar files : tar.gz and tar.bz2. gz: GNU zip bz2: bunzip2 In order to extract the files with the following extensions we will use the command "tar" For extracting gz files: tar -xzvf filename.gz For extracting bz2 files tar -xjvf filename.bz2 For more details you can do man tar in your command line

Open the Terminal Option in the Right Click Ubuntu

We can open  the terminal by a right click and selecting Open in Terminal if we install the following package step1: Open the terminal(ctrl+alt+t) Step2: sudo apt-get install nautilus-open-terminal Step3 : nautilius -q Now u can open the terminal anywhere  by just right click